pingerplot 1.6.0__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.
pingerplot/places.py ADDED
@@ -0,0 +1,259 @@
1
+ """Where a router is, read from its name.
2
+
3
+ IP geolocation is good for homes and offices and poor for the backbone: a
4
+ carrier's routers are often registered to its headquarters, so a router in
5
+ Chicago "is" in Denver or Ashburn. The router's own DNS name is usually the
6
+ better witness, because carriers name routers after where they stand:
7
+
8
+ * a CLLI code, the telephone industry's six-letter place code
9
+ (``ae-5.r21.chcgil09.us.bb.example.net``: CHCG IL, Chicago);
10
+ * an airport or metro code (``be3036.ccr22.dfw01.example.com``: DFW, Dallas;
11
+ ``core1.lax1.example.net``: Los Angeles);
12
+ * the city spelled out (``ae-1.ear2.Dallas1.example.net``,
13
+ ``be-1101-cr01.newyork.ny.example.net``).
14
+
15
+ This reads those and nothing else, offline. It is a hint, said to be one:
16
+ names are a convention, not a promise, and a router can be named after the
17
+ city at the other end of its link. The tables hold only codes that are in
18
+ common use on carrier networks and unlikely to be anything else; airport
19
+ codes that are also router jargon or English words (MAN, LOS, SAN, AUS, CAN,
20
+ PER, DEL, IND, SAT) are left out, so a wrong guess is rarer than no guess.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from dataclasses import dataclass
26
+ from typing import Optional
27
+
28
+ # Six-letter CLLI place codes: four letters of city, two of state.
29
+ CLLI = {
30
+ "chcgil": ("Chicago", "US"), "nycmny": ("New York", "US"), "nwrknj": ("Newark", "US"),
31
+ "dllstx": ("Dallas", "US"), "hstntx": ("Houston", "US"), "snantx": ("San Antonio", "US"),
32
+ "austtx": ("Austin", "US"), "lsanca": ("Los Angeles", "US"), "snjsca": ("San Jose", "US"),
33
+ "sntcca": ("Santa Clara", "US"), "plalca": ("Palo Alto", "US"), "snfcca": ("San Francisco", "US"),
34
+ "sndgca": ("San Diego", "US"), "sttlwa": ("Seattle", "US"), "prtlor": ("Portland, Oregon", "US"),
35
+ "dnvrco": ("Denver", "US"), "phnxaz": ("Phoenix", "US"), "tcsnaz": ("Tucson", "US"),
36
+ "albqnm": ("Albuquerque", "US"), "slkcut": ("Salt Lake City", "US"), "atlnga": ("Atlanta", "US"),
37
+ "miamfl": ("Miami", "US"), "tampfl": ("Tampa", "US"), "orldfl": ("Orlando", "US"),
38
+ "jcvlfl": ("Jacksonville", "US"), "asbnva": ("Ashburn", "US"), "rcmdva": ("Richmond", "US"),
39
+ "washdc": ("Washington", "US"), "bltmmd": ("Baltimore", "US"), "phlapa": ("Philadelphia", "US"),
40
+ "pitbpa": ("Pittsburgh", "US"), "bstnma": ("Boston", "US"), "ptldme": ("Portland, Maine", "US"),
41
+ "mnchnh": ("Manchester, New Hampshire", "US"), "clevoh": ("Cleveland", "US"),
42
+ "clmboh": ("Columbus", "US"), "dtrtmi": ("Detroit", "US"), "mplsmn": ("Minneapolis", "US"),
43
+ "stlsmo": ("St. Louis", "US"), "kscymo": ("Kansas City", "US"), "omahne": ("Omaha", "US"),
44
+ "nsvltn": ("Nashville", "US"), "mmphtn": ("Memphis", "US"), "chrlnc": ("Charlotte", "US"),
45
+ "rlghnc": ("Raleigh", "US"), "nworla": ("New Orleans", "US"), "hnllhi": ("Honolulu", "US"),
46
+ }
47
+
48
+ # Airport and metro codes carriers use for their points of presence.
49
+ CODES = {
50
+ # North America
51
+ "atl": ("Atlanta", "US"), "bos": ("Boston", "US"), "bna": ("Nashville", "US"),
52
+ "bwi": ("Baltimore", "US"), "chi": ("Chicago", "US"), "cle": ("Cleveland", "US"),
53
+ "clt": ("Charlotte", "US"), "cmh": ("Columbus", "US"), "dal": ("Dallas", "US"),
54
+ "dca": ("Washington", "US"), "den": ("Denver", "US"), "dfw": ("Dallas", "US"),
55
+ "dtw": ("Detroit", "US"), "ewr": ("Newark", "US"), "hnl": ("Honolulu", "US"),
56
+ "hou": ("Houston", "US"), "iad": ("Ashburn", "US"), "ash": ("Ashburn", "US"),
57
+ "iah": ("Houston", "US"), "jax": ("Jacksonville", "US"), "jfk": ("New York", "US"),
58
+ "lax": ("Los Angeles", "US"), "lga": ("New York", "US"), "mci": ("Kansas City", "US"),
59
+ "mco": ("Orlando", "US"), "mem": ("Memphis", "US"), "mia": ("Miami", "US"),
60
+ "mke": ("Milwaukee", "US"), "msp": ("Minneapolis", "US"), "msy": ("New Orleans", "US"),
61
+ "nyc": ("New York", "US"), "oma": ("Omaha", "US"), "ord": ("Chicago", "US"),
62
+ "pdx": ("Portland, Oregon", "US"), "phl": ("Philadelphia", "US"), "phx": ("Phoenix", "US"),
63
+ "pit": ("Pittsburgh", "US"), "rdu": ("Raleigh", "US"), "sea": ("Seattle", "US"),
64
+ "sfo": ("San Francisco", "US"), "sjc": ("San Jose", "US"), "slc": ("Salt Lake City", "US"),
65
+ "stl": ("St. Louis", "US"), "tpa": ("Tampa", "US"), "was": ("Washington", "US"),
66
+ "yul": ("Montreal", "CA"), "yvr": ("Vancouver", "CA"), "yyz": ("Toronto", "CA"),
67
+ "yyc": ("Calgary", "CA"), "yow": ("Ottawa", "CA"), "ymq": ("Montreal", "CA"),
68
+ "yqb": ("Quebec City", "CA"), "yto": ("Toronto", "CA"), "dsm": ("Des Moines", "US"),
69
+ "cys": ("Cheyenne", "US"), "mex": ("Mexico City", "MX"),
70
+ "qro": ("Queretaro", "MX"),
71
+ # Europe
72
+ "ams": ("Amsterdam", "NL"), "arn": ("Stockholm", "SE"), "sto": ("Stockholm", "SE"),
73
+ "ath": ("Athens", "GR"), "bcn": ("Barcelona", "ES"), "bru": ("Brussels", "BE"),
74
+ "bud": ("Budapest", "HU"), "cdg": ("Paris", "FR"), "par": ("Paris", "FR"),
75
+ "cph": ("Copenhagen", "DK"), "dub": ("Dublin", "IE"), "fra": ("Frankfurt", "DE"),
76
+ "fco": ("Rome", "IT"), "hel": ("Helsinki", "FI"), "ham": ("Hamburg", "DE"),
77
+ "ist": ("Istanbul", "TR"), "lhr": ("London", "GB"), "lon": ("London", "GB"),
78
+ "lis": ("Lisbon", "PT"), "mad": ("Madrid", "ES"), "mrs": ("Marseille", "FR"),
79
+ "mil": ("Milan", "IT"), "mxp": ("Milan", "IT"), "muc": ("Munich", "DE"),
80
+ "osl": ("Oslo", "NO"), "otp": ("Bucharest", "RO"), "prg": ("Prague", "CZ"),
81
+ "sof": ("Sofia", "BG"), "vie": ("Vienna", "AT"), "waw": ("Warsaw", "PL"),
82
+ "zrh": ("Zurich", "CH"), "dus": ("Dusseldorf", "DE"),
83
+ # Asia, Oceania, Middle East, Africa, South America
84
+ "akl": ("Auckland", "NZ"), "bkk": ("Bangkok", "TH"), "bom": ("Mumbai", "IN"),
85
+ "cgk": ("Jakarta", "ID"), "dxb": ("Dubai", "AE"), "hkg": ("Hong Kong", "HK"),
86
+ "icn": ("Seoul", "KR"), "sel": ("Seoul", "KR"), "jnb": ("Johannesburg", "ZA"),
87
+ "kix": ("Osaka", "JP"), "osa": ("Osaka", "JP"), "kul": ("Kuala Lumpur", "MY"),
88
+ "maa": ("Chennai", "IN"), "mnl": ("Manila", "PH"), "nrt": ("Tokyo", "JP"),
89
+ "hnd": ("Tokyo", "JP"), "tyo": ("Tokyo", "JP"), "sin": ("Singapore", "SG"),
90
+ "syd": ("Sydney", "AU"), "mel": ("Melbourne", "AU"), "tpe": ("Taipei", "TW"),
91
+ "gru": ("Sao Paulo", "BR"), "eze": ("Buenos Aires", "AR"), "scl": ("Santiago", "CL"),
92
+ "bog": ("Bogota", "CO"), "lim": ("Lima", "PE"), "cpt": ("Cape Town", "ZA"),
93
+ "nbo": ("Nairobi", "KE"), "doh": ("Doha", "QA"),
94
+ }
95
+
96
+ # Cities spelled out, as some carriers name routers (spaces and dots removed).
97
+ NAMES = {
98
+ "chicago": ("Chicago", "US"), "dallas": ("Dallas", "US"), "houston": ("Houston", "US"),
99
+ "newyork": ("New York", "US"), "losangeles": ("Los Angeles", "US"), "sanjose": ("San Jose", "US"),
100
+ "seattle": ("Seattle", "US"), "denver": ("Denver", "US"), "phoenix": ("Phoenix", "US"),
101
+ "atlanta": ("Atlanta", "US"), "miami": ("Miami", "US"), "ashburn": ("Ashburn", "US"),
102
+ "washington": ("Washington", "US"), "boston": ("Boston", "US"),
103
+ "philadelphia": ("Philadelphia", "US"), "newark": ("Newark", "US"), "paloalto": ("Palo Alto", "US"),
104
+ "santaclara": ("Santa Clara", "US"), "sanfrancisco": ("San Francisco", "US"),
105
+ "sandiego": ("San Diego", "US"), "minneapolis": ("Minneapolis", "US"),
106
+ "stlouis": ("St. Louis", "US"), "kansascity": ("Kansas City", "US"), "detroit": ("Detroit", "US"),
107
+ "cleveland": ("Cleveland", "US"), "columbus": ("Columbus", "US"),
108
+ "saltlakecity": ("Salt Lake City", "US"), "lasvegas": ("Las Vegas", "US"),
109
+ "nashville": ("Nashville", "US"), "charlotte": ("Charlotte", "US"), "raleigh": ("Raleigh", "US"),
110
+ "tampa": ("Tampa", "US"), "orlando": ("Orlando", "US"), "jacksonville": ("Jacksonville", "US"),
111
+ "neworleans": ("New Orleans", "US"), "memphis": ("Memphis", "US"),
112
+ "sanantonio": ("San Antonio", "US"), "austin": ("Austin", "US"), "albuquerque": ("Albuquerque", "US"),
113
+ "honolulu": ("Honolulu", "US"), "pittsburgh": ("Pittsburgh", "US"), "baltimore": ("Baltimore", "US"),
114
+ "richmond": ("Richmond", "US"), "omaha": ("Omaha", "US"), "indianapolis": ("Indianapolis", "US"),
115
+ "milwaukee": ("Milwaukee", "US"), "sacramento": ("Sacramento", "US"), "buffalo": ("Buffalo", "US"),
116
+ "portland": ("Portland", ""), "toronto": ("Toronto", "CA"), "montreal": ("Montreal", "CA"),
117
+ "vancouver": ("Vancouver", "CA"), "london": ("London", "GB"), "paris": ("Paris", "FR"),
118
+ "frankfurt": ("Frankfurt", "DE"), "amsterdam": ("Amsterdam", "NL"), "brussels": ("Brussels", "BE"),
119
+ "madrid": ("Madrid", "ES"), "milan": ("Milan", "IT"), "zurich": ("Zurich", "CH"),
120
+ "vienna": ("Vienna", "AT"), "stockholm": ("Stockholm", "SE"), "oslo": ("Oslo", "NO"),
121
+ "copenhagen": ("Copenhagen", "DK"), "helsinki": ("Helsinki", "FI"), "warsaw": ("Warsaw", "PL"),
122
+ "prague": ("Prague", "CZ"), "dublin": ("Dublin", "IE"), "marseille": ("Marseille", "FR"),
123
+ "tokyo": ("Tokyo", "JP"), "osaka": ("Osaka", "JP"), "seoul": ("Seoul", "KR"),
124
+ "singapore": ("Singapore", "SG"), "hongkong": ("Hong Kong", "HK"), "sydney": ("Sydney", "AU"),
125
+ "melbourne": ("Melbourne", "AU"), "mumbai": ("Mumbai", "IN"), "chennai": ("Chennai", "IN"),
126
+ "johannesburg": ("Johannesburg", "ZA"), "saopaulo": ("Sao Paulo", "BR"),
127
+ }
128
+
129
+ _TOKEN = re.compile(r"^([a-z]+)\d*[a-z]?$") # "lax1", "dfw01", "chcgil09", "dallas1", "ord2a"
130
+ # A full CLLI code: six letters of place, then building/equipment characters
131
+ # ("chcgilcpj91", "nycmnyzrjp1", "chrlncm1j41"), as some carriers write it whole.
132
+ _CLLI_FULL = re.compile(r"^([a-z]{6})[a-z0-9]{2}[a-z0-9]{0,3}$")
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class Place:
137
+ city: str
138
+ country: str
139
+ clue: str # the part of the name it came from
140
+
141
+ def __str__(self) -> str:
142
+ return f"{self.city}, {self.country}" if self.country else self.city
143
+
144
+
145
+ def from_name(hostname: Optional[str]) -> Optional[Place]:
146
+ """The place a router's name points to, or None.
147
+
148
+ Only the labels in front of the domain are read (``…cogentco.com`` names
149
+ no city), and a whole word must match: a code is never found inside a
150
+ longer token."""
151
+ if not hostname:
152
+ return None
153
+ labels = hostname.lower().rstrip(".").split(".")
154
+ if len(labels) < 3:
155
+ return None
156
+ for label in labels[:-2]:
157
+ # "newyork.ny" comes as one label per word; "new-york" and "new_york"
158
+ # as one label, so try the label whole (dashes dropped) before its parts.
159
+ joined = re.sub(r"[-_]", "", label)
160
+ m = _TOKEN.match(joined)
161
+ if m and m.group(1) in NAMES:
162
+ city, cc = NAMES[m.group(1)]
163
+ return Place(city, cc, label)
164
+ for part in re.split(r"[-_]", label):
165
+ full = _CLLI_FULL.match(part)
166
+ if full and full.group(1) in CLLI:
167
+ city, cc = CLLI[full.group(1)]
168
+ return Place(city, cc, part)
169
+ m = _TOKEN.match(part)
170
+ if not m:
171
+ continue
172
+ word = m.group(1)
173
+ if len(word) == 6 and word in CLLI:
174
+ city, cc = CLLI[word]
175
+ return Place(city, cc, part)
176
+ if word in NAMES:
177
+ city, cc = NAMES[word]
178
+ return Place(city, cc, part)
179
+ if len(word) == 3 and word in CODES:
180
+ city, cc = CODES[word]
181
+ return Place(city, cc, part)
182
+ return None
183
+
184
+
185
+ # Where those cities are (lat, lon; city centres, two decimals), so the map
186
+ # can draw a router where its name says it is. "Portland" alone is ambiguous
187
+ # and has none.
188
+ COORDS = {
189
+ "Chicago": (41.88, -87.63), "New York": (40.71, -74.01), "Newark": (40.74, -74.17),
190
+ "Dallas": (32.78, -96.80), "Houston": (29.76, -95.37), "San Antonio": (29.42, -98.49),
191
+ "Austin": (30.27, -97.74), "Los Angeles": (34.05, -118.24), "San Jose": (37.34, -121.89),
192
+ "Santa Clara": (37.35, -121.96), "Palo Alto": (37.44, -122.14), "San Francisco": (37.77, -122.42),
193
+ "San Diego": (32.72, -117.16), "Seattle": (47.61, -122.33), "Portland, Oregon": (45.52, -122.68),
194
+ "Denver": (39.74, -104.99), "Phoenix": (33.45, -112.07), "Tucson": (32.22, -110.97),
195
+ "Albuquerque": (35.08, -106.65), "Salt Lake City": (40.76, -111.89), "Atlanta": (33.75, -84.39),
196
+ "Miami": (25.76, -80.19), "Tampa": (27.95, -82.46), "Orlando": (28.54, -81.38),
197
+ "Jacksonville": (30.33, -81.66), "Ashburn": (39.04, -77.49), "Richmond": (37.54, -77.44),
198
+ "Washington": (38.91, -77.04), "Baltimore": (39.29, -76.61), "Philadelphia": (39.95, -75.17),
199
+ "Pittsburgh": (40.44, -79.99), "Boston": (42.36, -71.06), "Portland, Maine": (43.66, -70.26),
200
+ "Manchester, New Hampshire": (42.99, -71.46), "Cleveland": (41.50, -81.69),
201
+ "Columbus": (39.96, -83.00), "Detroit": (42.33, -83.05), "Minneapolis": (44.98, -93.27),
202
+ "St. Louis": (38.63, -90.20), "Kansas City": (39.10, -94.58), "Omaha": (41.26, -95.93),
203
+ "Nashville": (36.16, -86.78), "Memphis": (35.15, -90.05), "Charlotte": (35.23, -80.84),
204
+ "Raleigh": (35.78, -78.64), "New Orleans": (29.95, -90.07), "Honolulu": (21.31, -157.86),
205
+ "Milwaukee": (43.04, -87.91), "Las Vegas": (36.17, -115.14), "Indianapolis": (39.77, -86.16),
206
+ "Sacramento": (38.58, -121.49), "Buffalo": (42.89, -78.88),
207
+ "Montreal": (45.50, -73.57), "Vancouver": (49.28, -123.12), "Toronto": (43.65, -79.38),
208
+ "Calgary": (51.05, -114.07), "Ottawa": (45.42, -75.70), "Quebec City": (46.81, -71.21),
209
+ "Des Moines": (41.59, -93.62), "Cheyenne": (41.14, -104.82), "Mexico City": (19.43, -99.13),
210
+ "Queretaro": (20.59, -100.39),
211
+ "Amsterdam": (52.37, 4.90), "Stockholm": (59.33, 18.07), "Athens": (37.98, 23.73),
212
+ "Barcelona": (41.39, 2.17), "Brussels": (50.85, 4.35), "Budapest": (47.50, 19.04),
213
+ "Paris": (48.86, 2.35), "Copenhagen": (55.68, 12.57), "Dublin": (53.35, -6.26),
214
+ "Frankfurt": (50.11, 8.68), "Rome": (41.90, 12.50), "Helsinki": (60.17, 24.94),
215
+ "Hamburg": (53.55, 9.99), "Istanbul": (41.01, 28.98), "London": (51.51, -0.13),
216
+ "Lisbon": (38.72, -9.14), "Madrid": (40.42, -3.70), "Marseille": (43.30, 5.37),
217
+ "Milan": (45.46, 9.19), "Munich": (48.14, 11.58), "Oslo": (59.91, 10.75),
218
+ "Bucharest": (44.43, 26.10), "Prague": (50.08, 14.44), "Sofia": (42.70, 23.32),
219
+ "Vienna": (48.21, 16.37), "Warsaw": (52.23, 21.01), "Zurich": (47.38, 8.54),
220
+ "Dusseldorf": (51.23, 6.77),
221
+ "Auckland": (-36.85, 174.76), "Bangkok": (13.76, 100.50), "Mumbai": (19.08, 72.88),
222
+ "Jakarta": (-6.21, 106.85), "Dubai": (25.20, 55.27), "Hong Kong": (22.32, 114.17),
223
+ "Seoul": (37.57, 126.98), "Johannesburg": (-26.20, 28.05), "Osaka": (34.69, 135.50),
224
+ "Kuala Lumpur": (3.14, 101.69), "Chennai": (13.08, 80.27), "Manila": (14.60, 120.98),
225
+ "Tokyo": (35.68, 139.69), "Singapore": (1.35, 103.82), "Sydney": (-33.87, 151.21),
226
+ "Melbourne": (-37.81, 144.96), "Taipei": (25.03, 121.57), "Sao Paulo": (-23.55, -46.63),
227
+ "Buenos Aires": (-34.60, -58.38), "Santiago": (-33.45, -70.67), "Bogota": (4.71, -74.07),
228
+ "Lima": (-12.05, -77.04), "Cape Town": (-33.92, 18.42), "Nairobi": (-1.29, 36.82),
229
+ "Doha": (25.29, 51.53),
230
+ }
231
+
232
+
233
+ # The tables' country codes by the names the IP database gives (ipwho.is
234
+ # spells them out, in a few variants), so a place reads the same whichever
235
+ # witness placed it: "Boston, US" both times, not "Boston, United States"
236
+ # from the database in the row under a router's name's "Boston, US".
237
+ COUNTRY_CODES = {
238
+ "United States": "US", "United States of America": "US", "Canada": "CA", "Mexico": "MX",
239
+ "Netherlands": "NL", "The Netherlands": "NL", "Sweden": "SE", "Greece": "GR", "Spain": "ES",
240
+ "Belgium": "BE", "Hungary": "HU", "France": "FR", "Denmark": "DK", "Ireland": "IE",
241
+ "Germany": "DE", "Italy": "IT", "Finland": "FI", "Turkey": "TR", "Türkiye": "TR",
242
+ "United Kingdom": "GB", "Portugal": "PT", "Norway": "NO", "Romania": "RO", "Czechia": "CZ",
243
+ "Czech Republic": "CZ", "Bulgaria": "BG", "Austria": "AT", "Poland": "PL", "Switzerland": "CH",
244
+ "New Zealand": "NZ", "Thailand": "TH", "India": "IN", "Indonesia": "ID",
245
+ "United Arab Emirates": "AE", "Hong Kong": "HK", "South Korea": "KR", "Korea, Republic of": "KR",
246
+ "Republic of Korea": "KR", "South Africa": "ZA", "Japan": "JP", "Malaysia": "MY",
247
+ "Philippines": "PH", "Singapore": "SG", "Australia": "AU", "Taiwan": "TW", "Brazil": "BR",
248
+ "Argentina": "AR", "Chile": "CL", "Colombia": "CO", "Peru": "PE", "Kenya": "KE", "Qatar": "QA",
249
+ }
250
+
251
+
252
+ def country_code(name: str) -> str:
253
+ """The code for a country the tables use, or the name as given."""
254
+ return COUNTRY_CODES.get(name, name)
255
+
256
+
257
+ def coords(place: Optional[Place]) -> Optional[tuple]:
258
+ """(lat, lon) for a place read from a name, or None."""
259
+ return COORDS.get(place.city) if place is not None else None
pingerplot/routes.py ADDED
@@ -0,0 +1,112 @@
1
+ """Route changes worth reporting, told apart from load balancing.
2
+
3
+ Every round is a full traceroute, so which router answers at each hop is
4
+ known every few seconds. Until 1.5 any difference from the previous round was
5
+ logged as "Hop 7: path changed A -> B". On a path through routers that spread
6
+ traffic over parallel links (ECMP), hop 7 alternates between two routers for
7
+ as long as you watch, so that event fired every round or two and buried the
8
+ reroutes it existed to report.
9
+
10
+ The rule here: a router new to a hop is on probation. If a router already
11
+ known at that hop answers again before ``confirm`` answering rounds have
12
+ passed, the hop is load-balanced and the newcomer joins its known set (said
13
+ once). If only newcomers answer for ``confirm`` rounds in a row, the path
14
+ really moved: the hop's known set is replaced, and hops that moved in the
15
+ same round are reported together. Rounds in which a hop doesn't answer count
16
+ for neither, so a lossy hop can't fake a reroute or hide one.
17
+
18
+ Pure logic, no sockets and no Tk: the engine feeds it each round, and the
19
+ tests feed it scripted rounds.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass, field
24
+ from typing import Dict, List, Optional, Set
25
+
26
+ CONFIRM_ROUNDS = 3
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Change:
31
+ kind: str # "reroute" | "balanced"
32
+ ttls: List[int]
33
+ before: List[List[str]] = field(default_factory=list) # per ttl, sorted
34
+ after: List[List[str]] = field(default_factory=list)
35
+
36
+ @property
37
+ def text(self) -> str:
38
+ if self.kind == "balanced":
39
+ (ttl,), (now,) = self.ttls, self.after
40
+ return f"Hop {ttl} is load-balanced across {', '.join(now)}"
41
+ parts = [f"{' / '.join(b) or '*'} -> {' / '.join(a)}" for b, a in zip(self.before, self.after)]
42
+ if len(self.ttls) == 1:
43
+ return f"Route changed at hop {self.ttls[0]}: {parts[0]}"
44
+ detail = "; ".join(f"hop {t}: {p}" for t, p in zip(self.ttls, parts))
45
+ return f"Route changed at hops {self.ttls[0]}-{self.ttls[-1]}: {detail}"
46
+
47
+
48
+ def compatible(a: List[List[str]], b: List[List[str]]) -> bool:
49
+ """Whether two recorded routes are the same path: as long as each other,
50
+ and at every hop either one side was silent or they share a router. Load
51
+ balancing makes the sets grow over time; sharing a router is enough."""
52
+ if len(a) != len(b):
53
+ return False
54
+ return all(not x or not y or set(x) & set(y) for x, y in zip(a, b))
55
+
56
+
57
+ class RouteTracker:
58
+ def __init__(self, confirm: int = CONFIRM_ROUNDS) -> None:
59
+ self.confirm = max(1, int(confirm))
60
+ self.known: Dict[int, Set[str]] = {}
61
+ self._pending: Dict[int, Set[str]] = {} # ttl -> newcomers on probation
62
+ self._streak: Dict[int, int] = {} # ttl -> rounds only newcomers answered
63
+
64
+ def reset(self) -> None:
65
+ self.known.clear()
66
+ self._pending.clear()
67
+ self._streak.clear()
68
+
69
+ def trim(self, route_len: int) -> None:
70
+ """Forget hops past the end of a route that got shorter."""
71
+ for d in (self.known, self._pending, self._streak):
72
+ for ttl in [t for t in d if t > route_len]:
73
+ del d[ttl]
74
+
75
+ def signature(self, route_len: int) -> List[List[str]]:
76
+ """The route as recorded: each hop's known routers, [] for silent."""
77
+ return [sorted(self.known.get(ttl, ())) for ttl in range(1, route_len + 1)]
78
+
79
+ def observe(self, responders: Dict[int, Optional[str]]) -> List[Change]:
80
+ """One round's responders by TTL (None = no reply). Returns what
81
+ changed: at most one reroute (the hops that moved this round,
82
+ together) and a "balanced" note per hop found to be load-balanced."""
83
+ moved: List[tuple] = []
84
+ changes: List[Change] = []
85
+ for ttl in sorted(responders):
86
+ addr = responders[ttl]
87
+ if not addr:
88
+ continue
89
+ known = self.known.get(ttl)
90
+ if not known:
91
+ # A hop that was silent (or never seen) starts answering:
92
+ # that's discovery, not a change of path.
93
+ self.known[ttl] = {addr}
94
+ continue
95
+ if addr in known:
96
+ newcomers = self._pending.pop(ttl, None)
97
+ self._streak.pop(ttl, None)
98
+ if newcomers:
99
+ known |= newcomers
100
+ changes.append(Change("balanced", [ttl], after=[sorted(known)]))
101
+ continue
102
+ self._pending.setdefault(ttl, set()).add(addr)
103
+ self._streak[ttl] = self._streak.get(ttl, 0) + 1
104
+ if self._streak[ttl] >= self.confirm:
105
+ before = sorted(known)
106
+ self.known[ttl] = self._pending.pop(ttl)
107
+ del self._streak[ttl]
108
+ moved.append((ttl, before, sorted(self.known[ttl])))
109
+ if moved:
110
+ changes.insert(0, Change("reroute", [m[0] for m in moved],
111
+ [m[1] for m in moved], [m[2] for m in moved]))
112
+ return changes
@@ -0,0 +1,97 @@
1
+ """``PingerPlot --self-test``: what a build runs to prove it works, unattended.
2
+
3
+ The installer and the portable zip are checked by running the built program
4
+ with ``--self-test`` (and ``PINGERPLOT_DATA_DIR`` pointing at an empty folder,
5
+ so nothing real is touched). It builds the real window, round-trips the
6
+ settings file, sends one ICMP probe to loopback and makes the tray icons, then
7
+ writes what it found to ``self-test.txt`` in the data folder -- the windowed
8
+ executable has no console to print to -- and exits 0 only if all of it passed.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import sys
13
+ import time
14
+ from typing import Callable, List, Optional
15
+
16
+ from . import __version__
17
+
18
+
19
+ def run() -> int:
20
+ from . import appicon, icmp, settings, tray, winplatform
21
+
22
+ lines: List[str] = []
23
+ failed = False
24
+
25
+ def check(name: str, fn: Callable[[], Optional[str]]) -> None:
26
+ nonlocal failed
27
+ try:
28
+ lines.append(f"PASS {name}: {fn() or 'ok'}")
29
+ except Exception as exc: # a self-test reports every failure, never stops at one
30
+ failed = True
31
+ lines.append(f"FAIL {name}: {exc!r}")
32
+
33
+ def version() -> str:
34
+ kind = "frozen" if getattr(sys, "frozen", False) else "source"
35
+ return f"PingerPlot {__version__} ({kind}, Python {sys.version.split()[0]}, {sys.platform})"
36
+
37
+ def data_folder() -> str:
38
+ marker = {"self_test": time.time()}
39
+ if not settings.save(marker):
40
+ raise OSError(f"cannot write {settings.config_path()}")
41
+ if settings.load().get("self_test") != marker["self_test"]:
42
+ raise ValueError("settings did not read back")
43
+ portable = " (portable)" if settings.portable_dir() is not None else ""
44
+ return f"{settings.config_dir()}{portable}"
45
+
46
+ def window() -> str:
47
+ import tkinter as tk
48
+ from . import gui
49
+ root = tk.Tk()
50
+ root.withdraw()
51
+ try:
52
+ app = gui.App(root)
53
+ for after_id in root.tk.call("after", "info"):
54
+ root.after_cancel(after_id)
55
+ app._refresh_once()
56
+ styles = len(app.look.style.element_names())
57
+ app._quit()
58
+ except BaseException:
59
+ root.destroy()
60
+ raise
61
+ return f"built, {styles} theme elements"
62
+
63
+ def probe() -> str:
64
+ if not icmp.is_available():
65
+ raise OSError(icmp.unavailable_reason())
66
+ r = icmp.ping("127.0.0.1", 64, 2000)
67
+ if not r.reached:
68
+ raise OSError(f"no reply from 127.0.0.1 ({icmp.status_text(r.status)})")
69
+ return f"127.0.0.1 answered in {r.rtt_ms:.1f} ms"
70
+
71
+ def tray_icons() -> str:
72
+ if not tray.AVAILABLE:
73
+ return "no notification area on this platform"
74
+ for state in appicon.STATES:
75
+ h = tray.hicon_from_png(appicon.png_bytes(16, state), 16)
76
+ if not h:
77
+ raise OSError(f"could not make the {state} icon")
78
+ tray._u32.DestroyIcon(h)
79
+ return f"{len(appicon.STATES)} states"
80
+
81
+ check("version", version)
82
+ check("data folder", data_folder)
83
+ check("window", window)
84
+ check("icmp", probe)
85
+ check("tray icons", tray_icons)
86
+ if winplatform.IS_WINDOWS:
87
+ lines.append(f"INFO start with windows: {'on' if winplatform.autostart_enabled() else 'off'}")
88
+
89
+ report = "\n".join(lines + ["", "FAILED" if failed else "PASSED"]) + "\n"
90
+ try:
91
+ settings.config_dir().mkdir(parents=True, exist_ok=True)
92
+ (settings.config_dir() / "self-test.txt").write_text(report, encoding="utf-8")
93
+ except OSError:
94
+ failed = True
95
+ if sys.stdout is not None: # None in a windowed exe
96
+ print(report, end="")
97
+ return 1 if failed else 0
pingerplot/selftest.py ADDED
@@ -0,0 +1,76 @@
1
+ """Headless trace + monitor, printed to the console.
2
+
3
+ Useful for verifying the ICMP backend without launching the GUI:
4
+
5
+ python -m pingerplot.selftest 8.8.8.8
6
+ python -m pingerplot.selftest cloudflare.com --rounds 5 --interval 1
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import time
12
+
13
+ from . import icmp
14
+ from .monitor import Monitor
15
+
16
+
17
+ def _ms(v):
18
+ return " *" if v is None else f"{v:6.0f}"
19
+
20
+
21
+ def _print_table(views):
22
+ print(f"\n{'Hop':>3} {'IP':<16} {'Loss':>5} {'Sent':>4} {'Cur':>6} {'Avg':>6} {'Min':>6} {'Max':>6} Host")
23
+ print("-" * 86)
24
+ for v in views:
25
+ print(
26
+ f"{v.ttl:>3} {(v.address or '*'):<16} {v.loss_pct:>4.0f}% {v.sent:>4} "
27
+ f"{_ms(v.current)} {_ms(v.avg)} {_ms(v.best)} {_ms(v.worst)} {v.hostname or ''}"
28
+ )
29
+
30
+
31
+ def main() -> int:
32
+ ap = argparse.ArgumentParser(description="Headless PingerPlot trace/monitor.")
33
+ ap.add_argument("target", help="hostname or IPv4 address")
34
+ ap.add_argument("--rounds", type=int, default=3, help="monitor rounds to run (default 3)")
35
+ ap.add_argument("--interval", type=float, default=1.0, help="seconds between rounds")
36
+ ap.add_argument("--max-hops", type=int, default=30)
37
+ ap.add_argument("--no-resolve", action="store_true", help="skip reverse DNS")
38
+ args = ap.parse_args()
39
+
40
+ if not icmp.is_available():
41
+ print(f"No usable ICMP backend: {icmp.unavailable_reason()}")
42
+ return 2
43
+
44
+ mon = Monitor()
45
+ mon.start(
46
+ args.target,
47
+ interval=args.interval,
48
+ max_hops=args.max_hops,
49
+ resolve_names=not args.no_resolve,
50
+ )
51
+
52
+ # Wait for the trace to finish (status flips to "Monitoring …" or stops).
53
+ while mon.running and not mon.status.startswith("Monitoring"):
54
+ time.sleep(0.1)
55
+ if not mon.running:
56
+ print(mon.status)
57
+ return 1
58
+ print(mon.status)
59
+
60
+ deadline = time.perf_counter() + args.rounds * args.interval + 2
61
+ seen = -1
62
+ while mon.running and time.perf_counter() < deadline:
63
+ views, *_ = mon.snapshot()
64
+ if views and views[0].sent != seen:
65
+ seen = views[0].sent
66
+ _print_table(views)
67
+ if seen >= args.rounds + 1: # +1 for the trace probe
68
+ break
69
+ time.sleep(0.2)
70
+
71
+ mon.shutdown()
72
+ return 0
73
+
74
+
75
+ if __name__ == "__main__":
76
+ raise SystemExit(main())
pingerplot/settings.py ADDED
@@ -0,0 +1,98 @@
1
+ """Persisted UI / engine / alert settings (pure standard library).
2
+
3
+ Stored as JSON under ``%APPDATA%\\PingerPlot`` on Windows (XDG/home fallback
4
+ elsewhere), so the theme, engine options, alert thresholds, and the target list
5
+ survive a restart instead of resetting every launch.
6
+
7
+ Convenience, not critical state: a missing or unreadable file yields ``{}`` and
8
+ a save failure is swallowed — the app must never fail to start (or to close)
9
+ because of settings. Writes are atomic (temp file + ``os.replace``).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ APP_NAME = "PingerPlot"
19
+ FILE_NAME = "settings.json"
20
+
21
+
22
+ PORTABLE_MARKER = "portable.txt"
23
+
24
+
25
+ def portable_dir() -> "Path | None":
26
+ """The program's own folder, when it's a portable copy: a frozen build
27
+ with ``portable.txt`` beside it keeps its settings there, so a copy on a
28
+ USB stick carries them along. Running from source never is."""
29
+ if not getattr(sys, "frozen", False):
30
+ return None
31
+ here = Path(sys.executable).resolve().parent
32
+ return here if (here / PORTABLE_MARKER).exists() else None
33
+
34
+
35
+ def config_dir() -> Path:
36
+ """Where PingerPlot keeps its settings: PINGERPLOT_DATA_DIR if set (the
37
+ self-test and the demo point it at a scratch folder), a portable copy's
38
+ own folder, or the per-user config directory."""
39
+ override = os.environ.get("PINGERPLOT_DATA_DIR")
40
+ if override:
41
+ return Path(override)
42
+ portable = portable_dir()
43
+ if portable is not None:
44
+ return portable
45
+ if sys.platform == "win32":
46
+ base = os.environ.get("APPDATA") or str(Path.home())
47
+ return Path(base) / APP_NAME
48
+ base = os.environ.get("XDG_CONFIG_HOME")
49
+ return (Path(base) if base else Path.home() / ".config") / APP_NAME
50
+
51
+
52
+ def config_path() -> Path:
53
+ return config_dir() / FILE_NAME
54
+
55
+
56
+ def load() -> dict:
57
+ """Return the saved settings, or ``{}`` if absent/unreadable/not a dict."""
58
+ try:
59
+ with open(config_dir() / FILE_NAME, "r", encoding="utf-8-sig") as fh:
60
+ data = json.load(fh)
61
+ return data if isinstance(data, dict) else {}
62
+ except (OSError, ValueError):
63
+ return {}
64
+
65
+
66
+ def save(data: dict) -> bool:
67
+ """Atomically write ``data``. Returns False on failure, and never raises.
68
+
69
+ TypeError and ValueError are caught alongside OSError because json.dump
70
+ raises them for a value it cannot encode and for a circular reference —
71
+ not I/O errors, but just as fatal here. The GUI calls this from its
72
+ window-close handler, so an escaping exception means the app throws on the
73
+ way out, after the window has already been asked to close.
74
+
75
+ A failed write is a no-op: the temp file is removed rather than left behind
76
+ forever, and os.replace never runs, so the previous settings survive.
77
+ """
78
+ tmp = None
79
+ try:
80
+ d = config_dir()
81
+ # Yours alone on Linux and macOS (Windows ignores these modes; the
82
+ # profile folder is already private): a webhook URL in here can be a
83
+ # Slack, Teams or ntfy secret, and the default mode let every local
84
+ # user read it.
85
+ d.mkdir(mode=0o700, parents=True, exist_ok=True)
86
+ tmp = d / (FILE_NAME + ".tmp")
87
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
88
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
89
+ json.dump(data, fh, indent=2)
90
+ os.replace(tmp, d / FILE_NAME)
91
+ return True
92
+ except (OSError, TypeError, ValueError):
93
+ if tmp is not None:
94
+ try:
95
+ tmp.unlink()
96
+ except OSError:
97
+ pass
98
+ return False