1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
import os, json, time, requests, io, sys, ipaddress
NTFY_ENDPOINT = os.environ["NTFY_ENDPOINT"]
NTFY_TOKEN = os.environ["NTFY_TOKEN"]
TITLE_PREFIX = os.getenv("NTFY_TITLE_PREFIX", "Iperf")
MIN_DURATION = int(os.getenv("MIN_DURATION_SECONDS", "0"))
LOGFILE = "/logs/iperf3.jsonl"
# Optional: second provider for lookup
IPINFO_TOKEN = os.getenv("IPINFO_TOKEN")
IP_LOOKUP_CACHE_TTL = int(os.getenv("IP_LOOKUP_CACHE_TTL", "86400"))
_ip_cache: dict[str, tuple[float, dict]] = {}
def iter_json_objects(fobj: io.TextIOBase):
buf, depth, in_string, escape = [], 0, False, False
while True:
chunk = fobj.read()
if not chunk:
time.sleep(0.3)
continue
for ch in chunk:
buf.append(ch)
if ch == '"' and not escape:
in_string = not in_string
if ch == '\\' and not escape:
escape = True
else:
escape = False
if not in_string:
if ch == '{':
depth += 1
elif ch == '}':
depth -= 1
if depth == 0:
s = ''.join(buf).strip()
buf.clear()
if s:
yield s
def human_mbps(bps: float | None) -> str:
return "n/a" if bps is None else f"{bps / 1e6:.2f} Mbit/s"
def extract_client_ip(d: dict) -> str:
try:
return d["start"]["connected"][0]["remote_host"]
except Exception:
return d.get("remote_host", "unknown")
def is_public_ip(ip: str) -> bool:
try:
return ipaddress.ip_address(ip).is_global
except Exception:
return False
def lookup_ip_ipapi(ip: str) -> dict:
url = f"http://ip-api.com/json/{ip}"
params = {
"fields": "status,message,country,regionName,city,isp,org,as,query",
}
r = requests.get(url, params=params, timeout=5)
r.raise_for_status()
j = r.json()
if j.get("status") != "success":
return {"ok": False}
return {
"ok": True,
"country": j.get("country"),
"region": j.get("regionName"),
"city": j.get("city"),
"asn_text": j.get("as"),
"isp": j.get("isp"),
"org": j.get("org"),
}
def lookup_ip(ip: str) -> dict:
now = time.time()
cached = _ip_cache.get(ip)
if cached and (now - cached[0]) < IP_LOOKUP_CACHE_TTL:
return cached[1]
if not is_public_ip(ip):
res = {"ok": False, "note": "private"}
_ip_cache[ip] = (now, res)
return res
try:
res = lookup_ip_ipapi(ip)
except Exception:
res = {"ok": False}
_ip_cache[ip] = (now, res)
return res
def format_ip_enrichment(info: dict) -> list[str]:
if not info.get("ok"):
return ["IP-Info: n/a"]
lines = []
loc = " / ".join(filter(None, [info.get("country"), info.get("region"), info.get("city")]))
if loc:
lines.append(f"Location: {loc}")
if info.get("asn_text"):
lines.append(f"ASN: {info['asn_text']}")
if info.get("isp"):
lines.append(f"ISP: {info['isp']}")
return lines
def detect_direction_server_view(d: dict) -> str:
test = d.get("start", {}).get("test_start", {}) or {}
rev = test.get("reverse")
if isinstance(rev, bool):
return "Senden" if rev else "Empfangen"
if isinstance(rev, int):
return "Senden" if rev == 1 else "Empfangen"
end = d.get("end", {})
recv = (end.get("sum_received") or {}).get("bits_per_second")
sent = (end.get("sum_sent") or {}).get("bits_per_second")
if recv is not None and sent is None:
return "Empfangen"
if sent is not None and recv is None:
return "Senden"
if isinstance(recv, (int, float)) and isinstance(sent, (int, float)):
return "Empfangen" if recv >= sent else "Senden"
return "unbekannt"
def build_message(d: dict) -> tuple[str, str]:
client_ip = extract_client_ip(d)
ipinfo = lookup_ip(client_ip)
test = d.get("start", {}).get("test_start", {})
proto = str(test.get("protocol", "TCP")).upper()
duration = test.get("duration")
streams = test.get("num_streams")
if MIN_DURATION and duration and duration < MIN_DURATION:
raise ValueError("Testdauer zu kurz")
direction = detect_direction_server_view(d)
messung = "Upload" if direction == "Empfangen" else "Download"
land = ipinfo.get("country") if ipinfo.get("ok") else "unbekannt"
title = f"Iperf: {messung}-Messung aus {land} erfolgt"
end = d.get("end", {})
body = [
f"Gegenstelle: {client_ip}",
f"Protokoll: {proto}",
f"Richtung (Server): {direction}",
]
body.extend(format_ip_enrichment(ipinfo))
if proto == "UDP":
s = end.get("sum") or end.get("sum_received") or {}
body.append(f"Speed: {human_mbps(s.get('bits_per_second'))}")
if s.get("jitter_ms") is not None:
body.append(f"Jitter: {s['jitter_ms']} ms")
if s.get("lost_percent") is not None:
body.append(f"Loss: {s['lost_percent']} %")
else:
recv = end.get("sum_received", {})
sent = end.get("sum_sent", {})
bps = recv.get("bits_per_second") if direction == "Empfangen" else sent.get("bits_per_second")
body.append(f"Throughput: {human_mbps(bps)}")
if sent.get("retransmits") is not None:
body.append(f"Retransmits: {sent['retransmits']}")
if duration:
body.append(f"Dauer: {duration}s")
if streams:
body.append(f"Streams: {streams}")
return title, "\n".join(body)
def publish_to_ntfy(title: str, body: str):
headers = {
"Authorization": f"Bearer {NTFY_TOKEN}",
"Title": title,
"Priority": "default",
}
r = requests.post(NTFY_ENDPOINT, data=body.encode("utf-8"), headers=headers, timeout=10)
r.raise_for_status()
def tail_file(path: str):
while not os.path.exists(path):
time.sleep(0.5)
with open(path, "r", encoding="utf-8", errors="ignore") as f:
f.seek(0, io.SEEK_END)
for raw in iter_json_objects(f):
try:
data = json.loads(raw)
title, body = build_message(data)
publish_to_ntfy(title, body)
print(f"[ntfy] Sent: {title}")
except Exception as e:
print(f"[error] {e}", file=sys.stderr)
if __name__ == "__main__":
tail_file(LOGFILE)
|