spongebob-cli 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- spongebob/__init__.py +1 -0
- spongebob/__main__.py +375 -0
- spongebob/analyzer/__init__.py +9 -0
- spongebob/analyzer/__main__.py +39 -0
- spongebob/analyzer/analyzer.py +234 -0
- spongebob/bus/__init__.py +6 -0
- spongebob/bus/bus.py +38 -0
- spongebob/diagnose/__init__.py +29 -0
- spongebob/diagnose/__main__.py +111 -0
- spongebob/diagnose/adapter.py +82 -0
- spongebob/diagnose/models.py +79 -0
- spongebob/diagnose/probes.py +129 -0
- spongebob/engine/__init__.py +26 -0
- spongebob/engine/__main__.py +25 -0
- spongebob/engine/models.py +161 -0
- spongebob/engine/simulator.py +196 -0
- spongebob/export/__init__.py +25 -0
- spongebob/export/exporter.py +354 -0
- spongebob/meter/__init__.py +7 -0
- spongebob/meter/__main__.py +50 -0
- spongebob/meter/meter.py +140 -0
- spongebob/narrator/__init__.py +25 -0
- spongebob/narrator/narrator.py +352 -0
- spongebob/plugins/__init__.py +28 -0
- spongebob/plugins/loader.py +308 -0
- spongebob/plugins/models.py +47 -0
- spongebob/scenarios/__init__.py +25 -0
- spongebob/scenarios/builtin/__init__.py +1 -0
- spongebob/scenarios/builtin/control-line.toml +33 -0
- spongebob/scenarios/builtin/crowded-wifi.toml +33 -0
- spongebob/scenarios/builtin/flaky-last-mile.toml +33 -0
- spongebob/scenarios/builtin/long-haul-orbit.toml +33 -0
- spongebob/scenarios/builtin/overloaded-uplink.toml +35 -0
- spongebob/scenarios/builtin/tunnel-burst.toml +38 -0
- spongebob/scenarios/loader.py +205 -0
- spongebob/scenarios/models.py +55 -0
- spongebob/scenarios/runner.py +24 -0
- spongebob/ui/__init__.py +23 -0
- spongebob/ui/__main__.py +11 -0
- spongebob/ui/app.py +88 -0
- spongebob/ui/canvas.py +147 -0
- spongebob/ui/diagnose_screen.py +525 -0
- spongebob/ui/export_modal.py +158 -0
- spongebob/ui/menu_screen.py +159 -0
- spongebob/ui/replay.py +209 -0
- spongebob/ui/settings_screen.py +101 -0
- spongebob/ui/simulate_screen.py +566 -0
- spongebob/ui/theme.py +364 -0
- spongebob/ui/visualize_screen.py +411 -0
- spongebob_cli-0.3.2.dist-info/METADATA +78 -0
- spongebob_cli-0.3.2.dist-info/RECORD +54 -0
- spongebob_cli-0.3.2.dist-info/WHEEL +5 -0
- spongebob_cli-0.3.2.dist-info/entry_points.txt +2 -0
- spongebob_cli-0.3.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import heapq
|
|
4
|
+
import random
|
|
5
|
+
from collections import deque
|
|
6
|
+
from typing import Iterable, Literal
|
|
7
|
+
|
|
8
|
+
from .models import DropReason, Event, Flow, Hop, Packet, default_path
|
|
9
|
+
|
|
10
|
+
_ActionKind = Literal["send", "arrive_hop", "finish_hop"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Simulator:
|
|
14
|
+
"""Deterministic discrete-event network impairment simulator on a virtual clock."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, path: Iterable[Hop] | None = None, seed: int | None = None) -> None:
|
|
17
|
+
hops = list(default_path() if path is None else path)
|
|
18
|
+
if not hops:
|
|
19
|
+
raise ValueError("path must contain at least one hop")
|
|
20
|
+
for hop in hops:
|
|
21
|
+
if not isinstance(hop, Hop):
|
|
22
|
+
raise TypeError(f"path elements must be Hop instances, got {type(hop).__name__}")
|
|
23
|
+
self.path: tuple[Hop, ...] = tuple(hops)
|
|
24
|
+
self.seed = seed
|
|
25
|
+
|
|
26
|
+
def _sample_hop_delay(self, hop: Hop, rng: random.Random) -> float:
|
|
27
|
+
if hop.jitter_ms == 0.0:
|
|
28
|
+
return hop.delay_ms
|
|
29
|
+
if hop.jitter_model == "uniform":
|
|
30
|
+
offset = rng.uniform(-hop.jitter_ms, hop.jitter_ms)
|
|
31
|
+
else:
|
|
32
|
+
offset = rng.gauss(0.0, hop.jitter_ms)
|
|
33
|
+
return max(0.0, hop.delay_ms + offset)
|
|
34
|
+
|
|
35
|
+
def _should_drop_random(self, hop: Hop, rng: random.Random) -> bool:
|
|
36
|
+
if hop.loss_pct <= 0.0:
|
|
37
|
+
return False
|
|
38
|
+
if hop.loss_pct >= 100.0:
|
|
39
|
+
return True
|
|
40
|
+
return rng.random() < (hop.loss_pct / 100.0)
|
|
41
|
+
|
|
42
|
+
def _should_drop_gilbert(
|
|
43
|
+
self, hop: Hop, hop_index: int, in_good_state: list[bool], rng: random.Random
|
|
44
|
+
) -> bool:
|
|
45
|
+
if in_good_state[hop_index]:
|
|
46
|
+
if hop.p_good_to_bad > 0.0 and rng.random() < hop.p_good_to_bad:
|
|
47
|
+
in_good_state[hop_index] = False
|
|
48
|
+
else:
|
|
49
|
+
if hop.p_bad_to_good > 0.0 and rng.random() < hop.p_bad_to_good:
|
|
50
|
+
in_good_state[hop_index] = True
|
|
51
|
+
|
|
52
|
+
loss_pct = hop.loss_good if in_good_state[hop_index] else hop.loss_bad
|
|
53
|
+
if loss_pct <= 0.0:
|
|
54
|
+
return False
|
|
55
|
+
if loss_pct >= 100.0:
|
|
56
|
+
return True
|
|
57
|
+
return rng.random() < (loss_pct / 100.0)
|
|
58
|
+
|
|
59
|
+
def _check_loss(
|
|
60
|
+
self, hop: Hop, hop_index: int, in_good_state: list[bool], rng: random.Random
|
|
61
|
+
) -> DropReason | None:
|
|
62
|
+
if hop.loss_model == "random":
|
|
63
|
+
return "random" if self._should_drop_random(hop, rng) else None
|
|
64
|
+
return "burst" if self._should_drop_gilbert(hop, hop_index, in_good_state, rng) else None
|
|
65
|
+
|
|
66
|
+
def run(self, flow: Flow) -> list[Event]:
|
|
67
|
+
"""Run a flow through the configured path and return chronological events."""
|
|
68
|
+
if not isinstance(flow, Flow):
|
|
69
|
+
raise TypeError(f"flow must be a Flow instance, got {type(flow).__name__}")
|
|
70
|
+
|
|
71
|
+
rng = random.Random(self.seed)
|
|
72
|
+
events: list[Event] = []
|
|
73
|
+
queue: list[tuple[float, int, _ActionKind, Packet, int, float, int | None]] = []
|
|
74
|
+
order = 0
|
|
75
|
+
|
|
76
|
+
num_hops = len(self.path)
|
|
77
|
+
in_good_state = [True] * num_hops
|
|
78
|
+
link_free_time = [0.0] * num_hops
|
|
79
|
+
queued_finish_times: list[deque[float]] = [deque() for _ in range(num_hops)]
|
|
80
|
+
|
|
81
|
+
for seq in range(flow.packet_count):
|
|
82
|
+
send_time_ms = seq * flow.interval_ms
|
|
83
|
+
packet = Packet(seq=seq, size_bytes=flow.size_bytes, send_time_ms=send_time_ms)
|
|
84
|
+
heapq.heappush(queue, (send_time_ms, order, "send", packet, 0, 0.0, None))
|
|
85
|
+
order += 1
|
|
86
|
+
|
|
87
|
+
last_hop_index = num_hops - 1
|
|
88
|
+
|
|
89
|
+
while queue:
|
|
90
|
+
time_ms, _, action, packet, hop_index, hop_delay, queue_depth = heapq.heappop(queue)
|
|
91
|
+
|
|
92
|
+
if action == "send":
|
|
93
|
+
events.append(
|
|
94
|
+
Event(
|
|
95
|
+
type="packet_sent",
|
|
96
|
+
seq=packet.seq,
|
|
97
|
+
time_ms=time_ms,
|
|
98
|
+
hop=None,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
heapq.heappush(queue, (time_ms, order, "arrive_hop", packet, 0, 0.0, None))
|
|
102
|
+
order += 1
|
|
103
|
+
|
|
104
|
+
elif action == "arrive_hop":
|
|
105
|
+
hop = self.path[hop_index]
|
|
106
|
+
drop_reason = self._check_loss(hop, hop_index, in_good_state, rng)
|
|
107
|
+
if drop_reason is not None:
|
|
108
|
+
events.append(
|
|
109
|
+
Event(
|
|
110
|
+
type="packet_dropped",
|
|
111
|
+
seq=packet.seq,
|
|
112
|
+
time_ms=time_ms,
|
|
113
|
+
hop=hop.name,
|
|
114
|
+
reason=drop_reason,
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
continue
|
|
118
|
+
|
|
119
|
+
if hop.bandwidth_kbps is not None:
|
|
120
|
+
hop_queue = queued_finish_times[hop_index]
|
|
121
|
+
while hop_queue and hop_queue[0] <= time_ms:
|
|
122
|
+
hop_queue.popleft()
|
|
123
|
+
depth = len(hop_queue)
|
|
124
|
+
if hop.queue_limit_packets is not None and depth >= hop.queue_limit_packets:
|
|
125
|
+
events.append(
|
|
126
|
+
Event(
|
|
127
|
+
type="packet_dropped",
|
|
128
|
+
seq=packet.seq,
|
|
129
|
+
time_ms=time_ms,
|
|
130
|
+
hop=hop.name,
|
|
131
|
+
reason="queue_full",
|
|
132
|
+
)
|
|
133
|
+
)
|
|
134
|
+
continue
|
|
135
|
+
tx_time_ms = (packet.size_bytes * 8.0) / hop.bandwidth_kbps
|
|
136
|
+
start_tx = max(time_ms, link_free_time[hop_index])
|
|
137
|
+
finish_tx = start_tx + tx_time_ms
|
|
138
|
+
link_free_time[hop_index] = finish_tx
|
|
139
|
+
hop_queue.append(finish_tx)
|
|
140
|
+
serialization_delay = finish_tx - time_ms
|
|
141
|
+
applied_delay = serialization_delay + self._sample_hop_delay(hop, rng)
|
|
142
|
+
recorded_depth: int | None = depth
|
|
143
|
+
else:
|
|
144
|
+
applied_delay = self._sample_hop_delay(hop, rng)
|
|
145
|
+
recorded_depth = None
|
|
146
|
+
|
|
147
|
+
finish_time = time_ms + applied_delay
|
|
148
|
+
heapq.heappush(
|
|
149
|
+
queue,
|
|
150
|
+
(finish_time, order, "finish_hop", packet, hop_index, applied_delay, recorded_depth),
|
|
151
|
+
)
|
|
152
|
+
order += 1
|
|
153
|
+
|
|
154
|
+
elif action == "finish_hop":
|
|
155
|
+
hop = self.path[hop_index]
|
|
156
|
+
total_latency = time_ms - packet.send_time_ms
|
|
157
|
+
if hop_index == last_hop_index:
|
|
158
|
+
events.append(
|
|
159
|
+
Event(
|
|
160
|
+
type="packet_delivered",
|
|
161
|
+
seq=packet.seq,
|
|
162
|
+
time_ms=time_ms,
|
|
163
|
+
hop=hop.name,
|
|
164
|
+
delay_ms=hop_delay,
|
|
165
|
+
total_latency_ms=total_latency,
|
|
166
|
+
queue_depth=queue_depth,
|
|
167
|
+
)
|
|
168
|
+
)
|
|
169
|
+
else:
|
|
170
|
+
events.append(
|
|
171
|
+
Event(
|
|
172
|
+
type="packet_delayed",
|
|
173
|
+
seq=packet.seq,
|
|
174
|
+
time_ms=time_ms,
|
|
175
|
+
hop=hop.name,
|
|
176
|
+
delay_ms=hop_delay,
|
|
177
|
+
total_latency_ms=total_latency,
|
|
178
|
+
queue_depth=queue_depth,
|
|
179
|
+
)
|
|
180
|
+
)
|
|
181
|
+
heapq.heappush(
|
|
182
|
+
queue,
|
|
183
|
+
(time_ms, order, "arrive_hop", packet, hop_index + 1, 0.0, None),
|
|
184
|
+
)
|
|
185
|
+
order += 1
|
|
186
|
+
|
|
187
|
+
return events
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def simulate(
|
|
191
|
+
flow: Flow,
|
|
192
|
+
path: Iterable[Hop] | None = None,
|
|
193
|
+
seed: int | None = None,
|
|
194
|
+
) -> list[Event]:
|
|
195
|
+
"""Convenience function to run a discrete-event simulation for a flow and path."""
|
|
196
|
+
return Simulator(path=path, seed=seed).run(flow)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .exporter import (
|
|
4
|
+
SUPPORTED_EXTENSIONS,
|
|
5
|
+
ExportPayload,
|
|
6
|
+
default_export_path,
|
|
7
|
+
export_report,
|
|
8
|
+
get_downloads_dir,
|
|
9
|
+
render_csv,
|
|
10
|
+
render_export,
|
|
11
|
+
render_json,
|
|
12
|
+
render_markdown,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"SUPPORTED_EXTENSIONS",
|
|
17
|
+
"ExportPayload",
|
|
18
|
+
"default_export_path",
|
|
19
|
+
"export_report",
|
|
20
|
+
"get_downloads_dir",
|
|
21
|
+
"render_csv",
|
|
22
|
+
"render_export",
|
|
23
|
+
"render_json",
|
|
24
|
+
"render_markdown",
|
|
25
|
+
]
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import ctypes
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import uuid
|
|
12
|
+
from dataclasses import asdict, dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
from spongebob import __version__
|
|
17
|
+
from spongebob.analyzer import Finding
|
|
18
|
+
from spongebob.engine.models import Event
|
|
19
|
+
from spongebob.meter import Metrics
|
|
20
|
+
from spongebob.narrator import MASCOT_NAME, Line
|
|
21
|
+
from spongebob.scenarios.models import Scenario
|
|
22
|
+
|
|
23
|
+
SUPPORTED_EXTENSIONS = (".json", ".csv", ".md")
|
|
24
|
+
_FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
|
|
25
|
+
_DOWNLOADS_FOLDER_GUID = uuid.UUID("{374DE290-123F-4565-9164-39C4925E467B}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _GUID(ctypes.Structure):
|
|
29
|
+
_fields_ = [
|
|
30
|
+
("Data1", ctypes.c_uint32),
|
|
31
|
+
("Data2", ctypes.c_uint16),
|
|
32
|
+
("Data3", ctypes.c_uint16),
|
|
33
|
+
("Data4", ctypes.c_ubyte * 8),
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _uuid_to_guid(uid: uuid.UUID) -> _GUID:
|
|
38
|
+
data = uid.bytes_le
|
|
39
|
+
guid = _GUID()
|
|
40
|
+
ctypes.memmove(ctypes.byref(guid), data, 16)
|
|
41
|
+
return guid
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def get_downloads_dir() -> Path:
|
|
45
|
+
"""Resolve the user's Downloads folder without creating directories."""
|
|
46
|
+
if sys.platform == "win32":
|
|
47
|
+
ptr = ctypes.c_wchar_p()
|
|
48
|
+
guid = _uuid_to_guid(_DOWNLOADS_FOLDER_GUID)
|
|
49
|
+
shell32 = ctypes.windll.shell32 # type: ignore[attr-defined]
|
|
50
|
+
ole32 = ctypes.windll.ole32 # type: ignore[attr-defined]
|
|
51
|
+
hr = shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
|
|
52
|
+
try:
|
|
53
|
+
if hr != 0 or not ptr.value:
|
|
54
|
+
raise FileNotFoundError("Could not resolve Windows Downloads folder.")
|
|
55
|
+
downloads = Path(ptr.value)
|
|
56
|
+
finally:
|
|
57
|
+
if ptr.value is not None:
|
|
58
|
+
ole32.CoTaskMemFree(ptr)
|
|
59
|
+
else:
|
|
60
|
+
downloads = Path.home() / "Downloads"
|
|
61
|
+
|
|
62
|
+
if not downloads.is_dir():
|
|
63
|
+
raise FileNotFoundError(f"Downloads folder does not exist: {downloads}")
|
|
64
|
+
return downloads
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _sanitize_target(target: str) -> str:
|
|
68
|
+
cleaned = re.sub(r"[^a-z0-9.-]", "_", target.lower())
|
|
69
|
+
while ".." in cleaned:
|
|
70
|
+
cleaned = cleaned.replace("..", "_")
|
|
71
|
+
cleaned = re.sub(r"_+", "_", cleaned)
|
|
72
|
+
cleaned = re.sub(r"-+", "-", cleaned)
|
|
73
|
+
cleaned = cleaned.lstrip(".")
|
|
74
|
+
cleaned = cleaned[:60].rstrip(".")
|
|
75
|
+
return cleaned or "target"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def default_export_path(
|
|
79
|
+
kind: str = "diagnose",
|
|
80
|
+
target: str = "target",
|
|
81
|
+
fmt: str = "md",
|
|
82
|
+
) -> Path:
|
|
83
|
+
"""Build a collision-free default export path inside the user's Downloads folder."""
|
|
84
|
+
ext = fmt.lstrip(".").lower()
|
|
85
|
+
if f".{ext}" not in SUPPORTED_EXTENSIONS:
|
|
86
|
+
supported = ", ".join(SUPPORTED_EXTENSIONS)
|
|
87
|
+
raise ValueError(f"Unsupported export format {fmt!r}. Supported: {supported}")
|
|
88
|
+
|
|
89
|
+
downloads = get_downloads_dir()
|
|
90
|
+
safe_kind = _sanitize_target(kind)
|
|
91
|
+
safe_target = _sanitize_target(target)
|
|
92
|
+
stem = f"spongebob-{safe_kind}-{safe_target}"
|
|
93
|
+
|
|
94
|
+
candidate = downloads / f"{stem}.{ext}"
|
|
95
|
+
suffix_num = 2
|
|
96
|
+
while candidate.exists():
|
|
97
|
+
candidate = downloads / f"{stem}-{suffix_num}.{ext}"
|
|
98
|
+
suffix_num += 1
|
|
99
|
+
return candidate
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class ExportPayload:
|
|
104
|
+
"""Data bundle exported to JSON, CSV, or Markdown."""
|
|
105
|
+
|
|
106
|
+
source: Literal["simulation", "diagnose"]
|
|
107
|
+
metrics: Metrics
|
|
108
|
+
findings: list[Finding]
|
|
109
|
+
events: list[Event]
|
|
110
|
+
narrator_lines: tuple[Line, ...] = ()
|
|
111
|
+
scenario: Scenario | None = None
|
|
112
|
+
latency_kind: Literal["one_way", "rtt"] = "one_way"
|
|
113
|
+
target_host: str | None = None
|
|
114
|
+
target_port: int | None = None
|
|
115
|
+
include_events: bool = False
|
|
116
|
+
include_narrator: bool = True
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _escape_csv_cell(value: Any) -> str:
|
|
120
|
+
text = "" if value is None else str(value)
|
|
121
|
+
if text.startswith(_FORMULA_PREFIXES):
|
|
122
|
+
return f"'{text}"
|
|
123
|
+
return text
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _scenario_to_dict(scenario: Scenario) -> dict[str, Any]:
|
|
127
|
+
return {
|
|
128
|
+
"name": scenario.name,
|
|
129
|
+
"description": scenario.description,
|
|
130
|
+
"flow": {
|
|
131
|
+
"packets": scenario.flow.packet_count,
|
|
132
|
+
"interval_ms": scenario.flow.interval_ms,
|
|
133
|
+
"size_bytes": scenario.flow.size_bytes,
|
|
134
|
+
"seed": scenario.seed,
|
|
135
|
+
},
|
|
136
|
+
"hops": [asdict(h) for h in scenario.hops],
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _metrics_to_dict(metrics: Metrics) -> dict[str, Any]:
|
|
141
|
+
return {
|
|
142
|
+
"sent": metrics.sent,
|
|
143
|
+
"delivered": metrics.delivered,
|
|
144
|
+
"lost": metrics.lost,
|
|
145
|
+
"loss_pct": metrics.loss_pct,
|
|
146
|
+
"loss_by_hop": dict(metrics.loss_by_hop),
|
|
147
|
+
"latency_ms": asdict(metrics.latency_ms) if metrics.latency_ms is not None else None,
|
|
148
|
+
"jitter_ms": metrics.jitter_ms,
|
|
149
|
+
"jitter_mean_abs_ms": metrics.jitter_mean_abs_ms,
|
|
150
|
+
"reordered": metrics.reordered,
|
|
151
|
+
"throughput_kbps": metrics.throughput_kbps,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def render_json(payload: ExportPayload) -> str:
|
|
156
|
+
"""Render ExportPayload as deterministic JSON."""
|
|
157
|
+
data: dict[str, Any] = {
|
|
158
|
+
"schema": 1,
|
|
159
|
+
"spongebob_version": __version__,
|
|
160
|
+
"source": payload.source,
|
|
161
|
+
"scenario": _scenario_to_dict(payload.scenario) if payload.scenario is not None else None,
|
|
162
|
+
"metrics": _metrics_to_dict(payload.metrics),
|
|
163
|
+
"findings": [asdict(f) for f in payload.findings],
|
|
164
|
+
}
|
|
165
|
+
if payload.source == "diagnose":
|
|
166
|
+
data["latency_kind"] = payload.latency_kind
|
|
167
|
+
data["target"] = {
|
|
168
|
+
"host": payload.target_host,
|
|
169
|
+
"port": payload.target_port,
|
|
170
|
+
}
|
|
171
|
+
if payload.include_narrator:
|
|
172
|
+
data["narrator"] = [asdict(line) for line in payload.narrator_lines]
|
|
173
|
+
if payload.include_events:
|
|
174
|
+
data["events"] = [asdict(ev) for ev in payload.events]
|
|
175
|
+
return json.dumps(data, indent=2) + "\n"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def render_csv(payload: ExportPayload) -> str:
|
|
179
|
+
"""Render per-packet CSV with formula-injection escaping."""
|
|
180
|
+
per_seq: dict[int, list[Event]] = {}
|
|
181
|
+
for ev in payload.events:
|
|
182
|
+
per_seq.setdefault(ev.seq, []).append(ev)
|
|
183
|
+
|
|
184
|
+
buf = io.StringIO()
|
|
185
|
+
writer = csv.writer(buf, lineterminator="\n")
|
|
186
|
+
writer.writerow(["seq", "send_time_ms", "outcome", "latency_ms", "drop_hop", "drop_reason"])
|
|
187
|
+
|
|
188
|
+
for seq in sorted(per_seq):
|
|
189
|
+
seq_events = per_seq[seq]
|
|
190
|
+
send_ev = next((e for e in seq_events if e.type == "packet_sent"), None)
|
|
191
|
+
deliv_ev = next((e for e in seq_events if e.type == "packet_delivered"), None)
|
|
192
|
+
drop_ev = next((e for e in seq_events if e.type == "packet_dropped"), None)
|
|
193
|
+
|
|
194
|
+
send_time = send_ev.time_ms if send_ev is not None else ""
|
|
195
|
+
if deliv_ev is not None:
|
|
196
|
+
outcome = "delivered"
|
|
197
|
+
latency = deliv_ev.total_latency_ms if deliv_ev.total_latency_ms is not None else ""
|
|
198
|
+
drop_hop = ""
|
|
199
|
+
drop_reason = ""
|
|
200
|
+
elif drop_ev is not None:
|
|
201
|
+
outcome = "dropped"
|
|
202
|
+
latency = ""
|
|
203
|
+
drop_hop = _escape_csv_cell(drop_ev.hop or "")
|
|
204
|
+
drop_reason = _escape_csv_cell(drop_ev.reason or "")
|
|
205
|
+
else:
|
|
206
|
+
outcome = "sent"
|
|
207
|
+
latency = ""
|
|
208
|
+
drop_hop = ""
|
|
209
|
+
drop_reason = ""
|
|
210
|
+
|
|
211
|
+
writer.writerow([seq, send_time, outcome, latency, drop_hop, drop_reason])
|
|
212
|
+
|
|
213
|
+
return buf.getvalue()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def render_markdown(payload: ExportPayload) -> str:
|
|
217
|
+
"""Render ExportPayload as a readable Markdown report."""
|
|
218
|
+
lines: list[str] = []
|
|
219
|
+
if payload.scenario is not None:
|
|
220
|
+
lines.append(f"# Spongebob Report — {payload.scenario.name}")
|
|
221
|
+
lines.append("")
|
|
222
|
+
lines.append(payload.scenario.description)
|
|
223
|
+
elif payload.target_host is not None:
|
|
224
|
+
port_part = f":{payload.target_port}" if payload.target_port is not None else ""
|
|
225
|
+
lines.append(f"# Spongebob Diagnose Report — {payload.target_host}{port_part}")
|
|
226
|
+
else:
|
|
227
|
+
lines.append("# Spongebob Report")
|
|
228
|
+
|
|
229
|
+
m = payload.metrics
|
|
230
|
+
if payload.source == "simulation" and payload.scenario is not None:
|
|
231
|
+
cfg_delay = sum(h.delay_ms for h in payload.scenario.hops)
|
|
232
|
+
cfg_jitter = max(h.jitter_ms for h in payload.scenario.hops)
|
|
233
|
+
survive = 1.0
|
|
234
|
+
for h in payload.scenario.hops:
|
|
235
|
+
survive *= 1.0 - (h.loss_pct / 100.0)
|
|
236
|
+
cfg_loss = (1.0 - survive) * 100.0
|
|
237
|
+
|
|
238
|
+
meas_delay = f"{m.latency_ms.avg:.2f} ms" if m.latency_ms is not None else "n/a"
|
|
239
|
+
meas_jitter = f"{m.jitter_ms:.2f} ms" if m.jitter_ms is not None else "n/a"
|
|
240
|
+
meas_loss = f"{m.loss_pct:.2f}%"
|
|
241
|
+
|
|
242
|
+
lines.extend(
|
|
243
|
+
[
|
|
244
|
+
"",
|
|
245
|
+
"## Configured vs Measured",
|
|
246
|
+
"",
|
|
247
|
+
"| Metric | Configured | Measured |",
|
|
248
|
+
"| --- | --- | --- |",
|
|
249
|
+
f"| DELAY (avg) | {cfg_delay:.2f} ms | {meas_delay} |",
|
|
250
|
+
f"| JITTER (max hop / RFC3550) | {cfg_jitter:.2f} ms | {meas_jitter} |",
|
|
251
|
+
f"| LOSS | {cfg_loss:.2f}% | {meas_loss} |",
|
|
252
|
+
]
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
lines.extend(["", "## Metrics", ""])
|
|
256
|
+
lines.append(f"- **Sent:** {m.sent}")
|
|
257
|
+
lines.append(f"- **Delivered:** {m.delivered}")
|
|
258
|
+
lines.append(f"- **Lost:** {m.lost} ({m.loss_pct:.2f}%)")
|
|
259
|
+
if m.latency_ms is not None:
|
|
260
|
+
lat_label = "Round-trip time" if payload.latency_kind == "rtt" else "Latency"
|
|
261
|
+
lines.append(
|
|
262
|
+
f"- **{lat_label} (ms):** min={m.latency_ms.min:.2f}, "
|
|
263
|
+
f"avg={m.latency_ms.avg:.2f}, max={m.latency_ms.max:.2f}, p95={m.latency_ms.p95:.2f}"
|
|
264
|
+
)
|
|
265
|
+
else:
|
|
266
|
+
lines.append("- **Latency (ms):** n/a")
|
|
267
|
+
jit_str = f"{m.jitter_ms:.2f} ms" if m.jitter_ms is not None else "n/a"
|
|
268
|
+
lines.append(f"- **Jitter (RFC3550):** {jit_str}")
|
|
269
|
+
lines.append(f"- **Reordered:** {m.reordered}")
|
|
270
|
+
tp_str = f"{m.throughput_kbps:.2f} kbps" if m.throughput_kbps is not None else "n/a"
|
|
271
|
+
lines.append(f"- **Throughput:** {tp_str}")
|
|
272
|
+
|
|
273
|
+
lines.extend(["", "## Findings", ""])
|
|
274
|
+
if payload.findings:
|
|
275
|
+
for f in payload.findings:
|
|
276
|
+
hop_label = f.hop if f.hop is not None else "path"
|
|
277
|
+
lines.append(
|
|
278
|
+
f"- **[{f.severity.upper()}] {f.code}** ({hop_label}): "
|
|
279
|
+
f"{f.value:.2f} > {f.threshold:.2f}"
|
|
280
|
+
)
|
|
281
|
+
else:
|
|
282
|
+
lines.append("- None.")
|
|
283
|
+
|
|
284
|
+
if payload.include_narrator:
|
|
285
|
+
lines.extend(["", f"## {MASCOT_NAME}", ""])
|
|
286
|
+
if payload.narrator_lines:
|
|
287
|
+
for nl in payload.narrator_lines:
|
|
288
|
+
lines.append(f"- {nl.text}")
|
|
289
|
+
else:
|
|
290
|
+
lines.append("- None.")
|
|
291
|
+
|
|
292
|
+
if payload.source == "diagnose":
|
|
293
|
+
lines.extend(
|
|
294
|
+
[
|
|
295
|
+
"",
|
|
296
|
+
"## Honest Limits",
|
|
297
|
+
"",
|
|
298
|
+
"- Measurements reflect **round-trip time** (not one-way delay).",
|
|
299
|
+
"- TCP connect **timeouts approximate packet loss** and are not exact loss.",
|
|
300
|
+
"- Throughput is **n/a** because no application data is sent.",
|
|
301
|
+
]
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
lines.append("")
|
|
305
|
+
return "\n".join(lines)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def render_export(payload: ExportPayload, extension: str) -> str:
|
|
309
|
+
"""Render payload according to file extension (.json, .csv, .md)."""
|
|
310
|
+
ext = extension.lower()
|
|
311
|
+
if ext == ".json":
|
|
312
|
+
return render_json(payload)
|
|
313
|
+
if ext == ".csv":
|
|
314
|
+
return render_csv(payload)
|
|
315
|
+
if ext == ".md":
|
|
316
|
+
return render_markdown(payload)
|
|
317
|
+
supported = ", ".join(SUPPORTED_EXTENSIONS)
|
|
318
|
+
raise ValueError(f"Unsupported export format {extension!r}. Supported: {supported}")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def export_report(
|
|
322
|
+
payload: ExportPayload,
|
|
323
|
+
path: str | Path,
|
|
324
|
+
force: bool = False,
|
|
325
|
+
) -> Path:
|
|
326
|
+
"""Atomically write an export report to the exact user-specified path."""
|
|
327
|
+
out_path = Path(path)
|
|
328
|
+
ext = out_path.suffix.lower()
|
|
329
|
+
if ext not in SUPPORTED_EXTENSIONS:
|
|
330
|
+
supported = ", ".join(SUPPORTED_EXTENSIONS)
|
|
331
|
+
raise ValueError(f"Unsupported export format {out_path.suffix!r}. Supported: {supported}")
|
|
332
|
+
|
|
333
|
+
if not out_path.parent.is_dir():
|
|
334
|
+
raise FileNotFoundError(f"Parent directory does not exist: {out_path.parent}")
|
|
335
|
+
|
|
336
|
+
if out_path.exists() and not force:
|
|
337
|
+
raise FileExistsError(f"File already exists (use --force to overwrite): {out_path}")
|
|
338
|
+
|
|
339
|
+
content = render_export(payload, ext)
|
|
340
|
+
|
|
341
|
+
tmp_fd, tmp_name = tempfile.mkstemp(dir=out_path.parent, prefix=".spongebob_", suffix=".tmp")
|
|
342
|
+
tmp_path = Path(tmp_name)
|
|
343
|
+
try:
|
|
344
|
+
with os.fdopen(tmp_fd, "w", encoding="utf-8", newline="") as handle:
|
|
345
|
+
handle.write(content)
|
|
346
|
+
handle.flush()
|
|
347
|
+
os.fsync(handle.fileno())
|
|
348
|
+
os.replace(tmp_path, out_path)
|
|
349
|
+
except BaseException:
|
|
350
|
+
if tmp_path.exists():
|
|
351
|
+
tmp_path.unlink()
|
|
352
|
+
raise
|
|
353
|
+
|
|
354
|
+
return out_path
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from spongebob.engine import Flow, Hop, simulate
|
|
4
|
+
from spongebob.meter import measure
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main() -> None:
|
|
8
|
+
path = [
|
|
9
|
+
Hop(name="client", delay_ms=5.0, jitter_ms=1.0, loss_pct=0.0),
|
|
10
|
+
Hop(name="router", delay_ms=15.0, jitter_ms=5.0, loss_pct=2.0),
|
|
11
|
+
Hop(name="isp", delay_ms=25.0, jitter_ms=8.0, loss_pct=3.0),
|
|
12
|
+
Hop(name="server", delay_ms=5.0, jitter_ms=1.0, loss_pct=0.0),
|
|
13
|
+
]
|
|
14
|
+
flow = Flow(packet_count=500, interval_ms=10.0, size_bytes=64)
|
|
15
|
+
events = simulate(flow=flow, path=path, seed=42)
|
|
16
|
+
metrics = measure(events, packet_size_bytes=flow.size_bytes)
|
|
17
|
+
|
|
18
|
+
configured_delay = sum(h.delay_ms for h in path)
|
|
19
|
+
configured_loss = (
|
|
20
|
+
1.0 - (1.0 - 0.0) * (1.0 - 0.02) * (1.0 - 0.03) * (1.0 - 0.0)
|
|
21
|
+
) * 100.0
|
|
22
|
+
configured_rate_kbps = (flow.size_bytes * 8.0) / flow.interval_ms
|
|
23
|
+
|
|
24
|
+
print("Configured:")
|
|
25
|
+
print(f" packets={flow.packet_count} size_bytes={flow.size_bytes} interval_ms={flow.interval_ms}")
|
|
26
|
+
print(f" total_delay_ms={configured_delay:.2f} expected_loss_pct={configured_loss:.2f}% rate_kbps={configured_rate_kbps:.2f}")
|
|
27
|
+
print("Measured:")
|
|
28
|
+
print(f" sent={metrics.sent} delivered={metrics.delivered} lost={metrics.lost} loss_pct={metrics.loss_pct:.2f}%")
|
|
29
|
+
print(f" loss_by_hop={metrics.loss_by_hop}")
|
|
30
|
+
if metrics.latency_ms is not None:
|
|
31
|
+
print(
|
|
32
|
+
" latency_ms="
|
|
33
|
+
f"min:{metrics.latency_ms.min:.2f} "
|
|
34
|
+
f"avg:{metrics.latency_ms.avg:.2f} "
|
|
35
|
+
f"max:{metrics.latency_ms.max:.2f} "
|
|
36
|
+
f"p95:{metrics.latency_ms.p95:.2f}"
|
|
37
|
+
)
|
|
38
|
+
else:
|
|
39
|
+
print(" latency_ms=None")
|
|
40
|
+
print(f" jitter_ms={metrics.jitter_ms:.2f}" if metrics.jitter_ms is not None else " jitter_ms=None")
|
|
41
|
+
print(
|
|
42
|
+
f" jitter_mean_abs_ms={metrics.jitter_mean_abs_ms:.2f}"
|
|
43
|
+
if metrics.jitter_mean_abs_ms is not None
|
|
44
|
+
else " jitter_mean_abs_ms=None"
|
|
45
|
+
)
|
|
46
|
+
print(f" reordered={metrics.reordered} throughput_kbps={metrics.throughput_kbps:.2f}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
if __name__ == "__main__":
|
|
50
|
+
main()
|