Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /mattyopon_faultray /src /faultray /cli /simulate.py
| # Copyright (c) 2025-2026 Yutaro Maeda. All rights reserved. | |
| # Licensed under the Apache License 2.0. See LICENSE file for details. | |
| """Simulate and dynamic simulation CLI commands.""" | |
| from __future__ import annotations | |
| import json | |
| import os | |
| from pathlib import Path | |
| import typer | |
| from rich.panel import Panel | |
| from faultray.cli.main import ( | |
| DEFAULT_MODEL_PATH, | |
| InfraGraph, | |
| _print_ai_analysis, | |
| _print_dynamic_results, | |
| app, | |
| console, | |
| ) | |
| from faultray.reporter.report import print_simulation_report | |
| from faultray.simulator.engine import SimulationEngine | |
| def _print_evidence_sprint_hint(service: str | None = None) -> None: | |
| """Print a single, tasteful next-step hook after a simulation run. | |
| Points the user at turning the run into a DORA pre-audit evidence pack and | |
| booking an Evidence Sprint scoping call. Non-spammy: one line, once. | |
| Suppressed when ``FAULTRAY_NO_HINTS=1`` is set (so JSON/machine-output and | |
| CI users never see it). The caller is responsible for not invoking this in | |
| JSON/quiet modes. | |
| """ | |
| if os.environ.get("FAULTRAY_NO_HINTS") == "1": | |
| return | |
| target = service or "<name>" | |
| console.print( | |
| f"\n[dim]→ Turn this into a DORA pre-audit evidence pack: " | |
| f"[cyan]faultray report dora --service {target}[/cyan] · " | |
| f"Book a 20-min Evidence Sprint scoping call: " | |
| f"https://faultray.com/evidence-sprint[/]" | |
| ) | |
| def _suggest_service_for_hint(report: object, graph: object) -> str | None: | |
| """Pick a concrete service name for the next-step hint, if one is obvious. | |
| Prefers the component behind the first critical finding; otherwise returns | |
| None so the hint shows a generic ``<name>`` placeholder. | |
| """ | |
| try: | |
| criticals = getattr(report, "critical_findings", None) or [] | |
| for result in criticals: | |
| cid = getattr(result, "component_id", "") or getattr(result, "target_id", "") | |
| if cid: | |
| comp = graph.get_component(cid) if graph is not None else None | |
| return getattr(comp, "name", "") or cid | |
| except Exception: | |
| return None | |
| return None | |
| def _dynamic_results_to_json(results: list) -> dict: | |
| """Convert dynamic simulation results to a JSON-serialisable dict.""" | |
| total = len(results) | |
| critical = sum(1 for r in results if getattr(r, "is_critical", False)) | |
| warning = sum(1 for r in results if getattr(r, "is_warning", False)) | |
| passed = total - critical - warning | |
| scenarios = [] | |
| for r in results: | |
| name = getattr(r, "scenario", None) | |
| name = getattr(name, "name", "unknown") if name else "unknown" | |
| scenarios.append({ | |
| "name": name, | |
| "peak_severity": getattr(r, "peak_severity", 0.0), | |
| "peak_time_seconds": getattr(r, "peak_time_seconds", None), | |
| "recovery_time_seconds": getattr(r, "recovery_time_seconds", None), | |
| "is_critical": getattr(r, "is_critical", False), | |
| "is_warning": getattr(r, "is_warning", False), | |
| "autoscaling_events": len(getattr(r, "autoscaling_events", [])), | |
| "failover_events": len(getattr(r, "failover_events", [])), | |
| }) | |
| return { | |
| "total": total, | |
| "critical": critical, | |
| "warning": warning, | |
| "passed": passed, | |
| "scenarios": scenarios, | |
| } | |
| def _static_report_to_json(report: object) -> dict: | |
| """Convert a static SimulationReport to a JSON-serialisable dict.""" | |
| results = getattr(report, "results", []) | |
| getattr(report, "critical_findings", []) | |
| getattr(report, "warnings", []) | |
| getattr(report, "passed", []) | |
| scenarios = [] | |
| for r in results: | |
| scenario = getattr(r, "scenario", None) | |
| risk_score = getattr(r, "risk_score", 0.0) | |
| is_critical = getattr(r, "is_critical", False) | |
| is_warning = getattr(r, "is_warning", False) | |
| cascade = getattr(r, "cascade", None) | |
| if is_critical: | |
| severity = "critical" | |
| elif is_warning: | |
| severity = "warning" | |
| elif risk_score > 0: | |
| severity = "info" | |
| else: | |
| severity = "passed" | |
| affected = [] | |
| if cascade: | |
| for eff in getattr(cascade, "effects", []): | |
| affected.append({ | |
| "component": getattr(eff, "component_name", getattr(eff, "component_id", "?")), | |
| "health": getattr(eff, "health", "unknown").value if hasattr(getattr(eff, "health", None), "value") else str(getattr(eff, "health", "unknown")), | |
| "reason": getattr(eff, "reason", ""), | |
| }) | |
| scenarios.append({ | |
| "name": getattr(scenario, "name", "unknown") if scenario else "unknown", | |
| "description": getattr(scenario, "description", "") if scenario else "", | |
| "severity": severity, | |
| "risk_score": round(risk_score, 2), | |
| "affected_components": affected, | |
| "cascade_trigger": getattr(cascade, "trigger", "") if cascade else "", | |
| }) | |
| # Count top-level totals from per-scenario severity so they are consistent | |
| # with the scenario-level breakdown (not from the legacy list properties). | |
| n_critical = sum(1 for s in scenarios if s["severity"] == "critical") | |
| n_warning = sum(1 for s in scenarios if s["severity"] == "warning") | |
| n_info = sum(1 for s in scenarios if s["severity"] == "info") | |
| n_passed = sum(1 for s in scenarios if s["severity"] == "passed") | |
| return { | |
| "resilience_score": round(getattr(report, "resilience_score", 0.0), 1), | |
| "total_scenarios": len(results), | |
| "total_generated": getattr(report, "total_generated", len(results)), | |
| "was_truncated": getattr(report, "was_truncated", False), | |
| "critical": n_critical, | |
| "warning": n_warning, | |
| "info": n_info, | |
| "passed": n_passed, | |
| "scenarios": scenarios, | |
| } | |
| def _baseline_summary_from_report(report: object) -> dict: | |
| """Extract a baseline summary dict from a SimulationReport for saving/comparison.""" | |
| return { | |
| "resilience_score": round(getattr(report, "resilience_score", 0.0), 1), | |
| "critical": len(getattr(report, "critical_findings", [])), | |
| "warning": len(getattr(report, "warnings", [])), | |
| "passed": len(getattr(report, "passed", [])), | |
| "total_scenarios": len(getattr(report, "results", [])), | |
| } | |
| def _write_baseline(path: Path, report: object) -> None: | |
| """Write a baseline summary JSON for the given report.""" | |
| current_summary = _baseline_summary_from_report(report) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(path, "w", encoding="utf-8") as fh: | |
| json.dump(current_summary, fh, indent=2, ensure_ascii=False) | |
| def _load_baseline_data(path: Path) -> dict: | |
| """Load and validate a baseline JSON file. | |
| Exits with code 1 (clean error) if the file is unreadable, not valid JSON, | |
| or is missing fields required by the comparison logic. | |
| """ | |
| try: | |
| with open(path, encoding="utf-8") as fh: | |
| baseline_data = json.load(fh) | |
| except (json.JSONDecodeError, OSError) as exc: | |
| console.print(f"\n[red]Failed to load baseline: {exc}[/]") | |
| raise typer.Exit(1) | |
| required_keys = {"resilience_score", "critical", "warning"} | |
| if not isinstance(baseline_data, dict) or not required_keys <= set(baseline_data): | |
| have = set(baseline_data) if isinstance(baseline_data, dict) else set() | |
| missing = ", ".join(sorted(required_keys - have)) | |
| console.print( | |
| f"\n[red]Baseline file is missing required field(s): {missing}[/]" | |
| ) | |
| raise typer.Exit(1) | |
| return baseline_data | |
| def _compare_baseline(current: dict, baseline: dict, con) -> bool: | |
| """Compare current results against baseline and print summary. | |
| Returns True if regression detected (resilience score dropped). | |
| """ | |
| cur_score = current["resilience_score"] | |
| base_score = baseline["resilience_score"] | |
| score_delta = cur_score - base_score | |
| cur_crit = current["critical"] | |
| base_crit = baseline["critical"] | |
| crit_delta = cur_crit - base_crit | |
| cur_warn = current["warning"] | |
| base_warn = baseline["warning"] | |
| warn_delta = cur_warn - base_warn | |
| # Format delta strings | |
| def _delta_str(delta: float | int, invert: bool = False) -> str: | |
| """Format a delta value with color. If invert, positive is bad.""" | |
| if delta == 0: | |
| return "[dim]no change[/]" | |
| sign = "+" if delta > 0 else "" | |
| if invert: | |
| color = "red" if delta > 0 else "green" | |
| else: | |
| color = "green" if delta > 0 else "red" | |
| return f"[{color}]{sign}{delta}[/]" | |
| score_str = _delta_str(round(score_delta, 1), invert=False) | |
| crit_str = _delta_str(crit_delta, invert=True) | |
| warn_str = _delta_str(warn_delta, invert=True) | |
| regressed = score_delta < 0 | |
| border = "red" if regressed else "green" | |
| status = "[bold red]REGRESSION DETECTED[/]" if regressed else "[bold green]No regression[/]" | |
| summary = ( | |
| f"[bold]Resilience Score:[/] {base_score:.1f} -> {cur_score:.1f} ({score_str})\n" | |
| f"[bold]Critical findings:[/] {base_crit} -> {cur_crit} ({crit_str})\n" | |
| f"[bold]Warnings:[/] {base_warn} -> {cur_warn} ({warn_str})\n\n" | |
| f"{status}" | |
| ) | |
| con.print() | |
| con.print(Panel( | |
| summary, | |
| title="[bold]Baseline Comparison[/]", | |
| border_style=border, | |
| )) | |
| return regressed | |
| def simulate( | |
| model: Path = typer.Option(DEFAULT_MODEL_PATH, "--model", "-m", help="Model file path"), | |
| html: Path | None = typer.Option(None, "--html", help="Export HTML report to this path"), | |
| pdf: Path | None = typer.Option(None, "--pdf", help="Export print-ready HTML report (open in browser → Ctrl+P for PDF)"), | |
| md: Path | None = typer.Option(None, "--md", help="Export Markdown report to this path"), | |
| dynamic: bool = typer.Option(False, "--dynamic", "-d", help="Run dynamic time-stepped simulation"), | |
| analyze_flag: bool = typer.Option(False, "--analyze", "-a", help="Run AI analysis after simulation"), | |
| plugins_dir: Path | None = typer.Option(None, "--plugins-dir", help="Directory of plugin .py files to load"), | |
| slack_webhook: str | None = typer.Option(None, "--slack-webhook", help="Slack webhook URL for notifications"), | |
| pagerduty_key: str | None = typer.Option(None, "--pagerduty-key", help="PagerDuty routing key for critical alerts"), | |
| max_scenarios: int = typer.Option(0, "--max-scenarios", help="Max scenarios to test (0 = engine default)"), | |
| max_depth: int = typer.Option(20, "--max-depth", help="Max cascade propagation depth (D_max, default 20)"), | |
| json_output: bool = typer.Option(False, "--json", help="Output JSON summary"), | |
| baseline: Path | None = typer.Option(None, "--baseline", help="Compare against a previous baseline JSON file"), | |
| save_baseline: Path | None = typer.Option(None, "--save-baseline", help="Save current results as a baseline JSON file"), | |
| ) -> None: | |
| """Run chaos simulation against infrastructure model. | |
| Examples: | |
| # Basic simulation | |
| faultray simulate | |
| # Simulate with a specific model | |
| faultray simulate --model my-model.json | |
| # Run dynamic time-stepped simulation | |
| faultray simulate --dynamic | |
| # Run with AI analysis | |
| faultray simulate --analyze | |
| # Export HTML report | |
| faultray simulate --html report.html | |
| # Export Markdown report | |
| faultray simulate --md report.md | |
| # JSON output for CI/CD pipelines | |
| faultray simulate --json | |
| # Limit scenario count | |
| faultray simulate --max-scenarios 50 | |
| # Save baseline for regression detection | |
| faultray simulate --save-baseline baseline.json | |
| # Compare against a baseline | |
| faultray simulate --baseline baseline.json | |
| # Load custom plugins | |
| faultray simulate --plugins-dir ./my-plugins/ | |
| # Send notifications on completion | |
| faultray simulate --slack-webhook https://hooks.slack.com/... | |
| """ | |
| if not model.exists(): | |
| console.print(f"[red]Model file not found: {model}[/]") | |
| console.print("Run [cyan]faultray scan[/] first to create a model.") | |
| raise typer.Exit(1) | |
| # Load plugins if a directory is specified. Naming --plugins-dir is the | |
| # user's explicit opt-in to execute that directory's code, so we pass | |
| # trusted=True but surface a clear security notice first. | |
| if plugins_dir is not None: | |
| from faultray.plugins.registry import PluginRegistry | |
| console.print( | |
| f"[yellow]Loading plugins from {plugins_dir} — this executes Python " | |
| f"from that directory. Only use directories you trust.[/]" | |
| ) | |
| PluginRegistry.load_plugins_from_dir(plugins_dir, trusted=True) | |
| if json_output: | |
| # Suppress logging to stdout so JSON output is parseable | |
| import logging as _logging | |
| _logging.getLogger("faultray").setLevel(_logging.ERROR) | |
| else: | |
| console.print("[cyan]Loading infrastructure model...[/]") | |
| graph = InfraGraph.load(model) | |
| if dynamic: | |
| from faultray.simulator.dynamic_engine import DynamicSimulationEngine | |
| if not json_output: | |
| console.print(f"[cyan]Running dynamic simulation ({len(graph.components)} components)...[/]") | |
| dyn_engine = DynamicSimulationEngine(graph, max_depth=max_depth) | |
| report = dyn_engine.run_all_dynamic_defaults() | |
| # report is a DynamicSimulationReport; extract .results list | |
| results = getattr(report, "results", report) if not isinstance(report, list) else report | |
| if json_output: | |
| console.print_json(data=_dynamic_results_to_json(results)) | |
| return | |
| _print_dynamic_results(results, console) | |
| return | |
| if not json_output: | |
| console.print(f"[cyan]Running chaos simulation ({len(graph.components)} components)...[/]") | |
| engine = SimulationEngine(graph, max_depth=max_depth) | |
| report = engine.run_all_defaults(max_scenarios=max_scenarios) | |
| # Auto-record to history | |
| _auto_record_history(graph, report) | |
| if json_output: | |
| # JSON mode: still honor --save-baseline / --baseline side effects, but | |
| # keep stdout as pure JSON (no human-readable text, no comparison panel). | |
| if save_baseline is not None: | |
| _write_baseline(save_baseline, report) | |
| baseline_regressed = False | |
| if baseline is not None and baseline.exists(): | |
| baseline_data = _load_baseline_data(baseline) | |
| current_summary = _baseline_summary_from_report(report) | |
| baseline_regressed = ( | |
| current_summary["resilience_score"] < baseline_data["resilience_score"] | |
| ) | |
| console.print_json(data=_static_report_to_json(report)) | |
| if baseline_regressed: | |
| raise typer.Exit(1) | |
| return | |
| # Scenario stats | |
| if report.was_truncated: | |
| console.print( | |
| f"\n[yellow]\u26a0 {report.total_generated:,} scenarios generated, " | |
| f"truncated to {len(report.results):,}. " | |
| f"Use --max-scenarios to adjust.[/]" | |
| ) | |
| console.print( | |
| f"[dim]Scenarios: {report.total_generated:,} generated, " | |
| f"{len(report.results):,} tested" | |
| + (f" ({report.total_generated - len(report.results):,} skipped)" if report.was_truncated else "") | |
| + "[/]" | |
| ) | |
| print_simulation_report(report, console, graph=graph) | |
| if analyze_flag: | |
| from faultray.ai.analyzer import FaultRayAnalyzer | |
| console.print("\n[cyan]Running AI analysis...[/]") | |
| ai_analyzer = FaultRayAnalyzer() | |
| ai_report = ai_analyzer.analyze(graph, report) | |
| _print_ai_analysis(ai_report, console) | |
| if html: | |
| from faultray.reporter.html_report import save_html_report | |
| save_html_report(report, graph, html) | |
| console.print(f"\n[green]HTML report saved to {html}[/]") | |
| if pdf: | |
| from faultray.reporter.pdf_report import save_pdf_ready_html | |
| save_pdf_ready_html(report, graph, pdf) | |
| console.print(f"\n[green]Print-ready HTML report saved to {pdf}[/]") | |
| console.print("[dim]Open in a browser and press Ctrl+P to save as PDF.[/]") | |
| if md: | |
| from faultray.reporter.pdf_report import export_markdown | |
| export_markdown(report, graph, md) | |
| console.print(f"\n[green]Markdown report saved to {md}[/]") | |
| # Webhook notifications | |
| if slack_webhook or pagerduty_key: | |
| import asyncio | |
| from faultray.api.server import _report_to_dict | |
| report_dict = _report_to_dict(report) | |
| async def _send_notifications(): | |
| if slack_webhook: | |
| from faultray.integrations.webhooks import send_slack_notification | |
| ok = await send_slack_notification(slack_webhook, report_dict) | |
| if ok: | |
| console.print("[green]Slack notification sent.[/]") | |
| else: | |
| console.print("[yellow]Slack notification failed.[/]") | |
| if pagerduty_key: | |
| from faultray.integrations.webhooks import send_pagerduty_event | |
| ok = await send_pagerduty_event(pagerduty_key, report_dict) | |
| if ok: | |
| console.print("[green]PagerDuty event sent.[/]") | |
| else: | |
| console.print("[dim]PagerDuty: no critical findings, event skipped.[/]") | |
| try: | |
| asyncio.run(_send_notifications()) | |
| except Exception as exc: | |
| console.print(f"[yellow]Webhook notification error: {exc}[/]") | |
| # Save baseline | |
| if save_baseline is not None: | |
| _write_baseline(save_baseline, report) | |
| console.print(f"\n[green]Baseline saved to {save_baseline}[/]") | |
| # Next-step buyer hook (suppressible via FAULTRAY_NO_HINTS=1; never shown in | |
| # --json mode, which returns earlier). Suggest the most blast-affected | |
| # service so the example command is directly actionable. | |
| _print_evidence_sprint_hint(_suggest_service_for_hint(report, graph)) | |
| # Compare against baseline | |
| if baseline is not None: | |
| if not baseline.exists(): | |
| console.print(f"\n[yellow]Baseline file not found: {baseline} (skipping comparison)[/]") | |
| else: | |
| baseline_data = _load_baseline_data(baseline) | |
| current_summary = _baseline_summary_from_report(report) | |
| regressed = _compare_baseline(current_summary, baseline_data, console) | |
| if regressed: | |
| raise typer.Exit(1) | |
| def dynamic( | |
| model: Path = typer.Option(DEFAULT_MODEL_PATH, "--model", "-m", help="Model file path"), | |
| html: Path | None = typer.Option(None, "--html", help="Export HTML report to this path"), | |
| duration: int = typer.Option(300, "--duration", help="Simulation duration in seconds"), | |
| step: int = typer.Option(5, "--step", help="Time step interval in seconds"), | |
| json_output: bool = typer.Option(False, "--json", help="Output JSON summary"), | |
| ) -> None: | |
| """Run dynamic time-stepped chaos simulation with realistic traffic patterns. | |
| Examples: | |
| # Run dynamic simulation with defaults | |
| faultray dynamic | |
| # Custom duration and step interval | |
| faultray dynamic --duration 600 --step 10 | |
| # Export HTML report | |
| faultray dynamic --html dynamic-report.html | |
| # JSON output | |
| faultray dynamic --json | |
| # Use a specific model | |
| faultray dynamic --model my-model.json | |
| """ | |
| if not model.exists(): | |
| console.print(f"[red]Model file not found: {model}[/]") | |
| console.print("Run [cyan]faultray scan[/] first to create a model.") | |
| raise typer.Exit(1) | |
| # Validate durations are positive and step < duration | |
| if duration <= 0: | |
| raise typer.BadParameter("--duration must be > 0") | |
| if step <= 0: | |
| raise typer.BadParameter("--step must be > 0") | |
| if step >= duration: | |
| console.print("[red]Error: --step must be smaller than --duration[/]") | |
| raise typer.Exit(1) | |
| if not json_output: | |
| console.print("[cyan]Loading infrastructure model...[/]") | |
| graph = InfraGraph.load(model) | |
| from faultray.simulator.dynamic_engine import DynamicSimulationEngine | |
| if not json_output: | |
| console.print( | |
| f"[cyan]Running dynamic simulation " | |
| f"({len(graph.components)} components, " | |
| f"duration={duration}s, step={step}s)...[/]" | |
| ) | |
| engine = DynamicSimulationEngine(graph) | |
| report = engine.run_all_dynamic_defaults(duration=duration, step=step) | |
| # report is a DynamicSimulationReport; extract .results list | |
| results = getattr(report, "results", report) if not isinstance(report, list) else report | |
| if json_output: | |
| console.print_json(data=_dynamic_results_to_json(results)) | |
| return | |
| _print_dynamic_results(results, console) | |
| if html: | |
| from faultray.reporter.html_report import save_html_report | |
| save_html_report(report, graph, html) | |
| console.print(f"\n[green]HTML report saved to {html}[/]") | |
| def _auto_record_history(graph: object, report: object) -> None: | |
| """Auto-record simulation results to history tracker (best-effort).""" | |
| try: | |
| from faultray.history import HistoryTracker | |
| tracker = HistoryTracker() | |
| tracker.record(graph, report=report) | |
| except Exception: | |
| pass # History recording is best-effort, never breaks the CLI | |
Xet Storage Details
- Size:
- 21.6 kB
- Xet hash:
- f647c3f43767e07d1ef02a6b8a2eb012f373199494580caf1a31e2f08fbde1e4
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.