netscope 0.19.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.
Files changed (76) hide show
  1. netscope/__init__.py +0 -0
  2. netscope/adapters/__init__.py +19 -0
  3. netscope/adapters/discovery/__init__.py +8 -0
  4. netscope/adapters/discovery/gateway_detector.py +143 -0
  5. netscope/adapters/discovery/hostname_resolver.py +78 -0
  6. netscope/adapters/discovery/network_discovery.py +85 -0
  7. netscope/adapters/discovery/network_type_classifier.py +74 -0
  8. netscope/adapters/geoip.py +630 -0
  9. netscope/adapters/lookups.py +205 -0
  10. netscope/adapters/probes/__init__.py +11 -0
  11. netscope/adapters/probes/bandwidth_adapter.py +28 -0
  12. netscope/adapters/probes/dns_adapter.py +78 -0
  13. netscope/adapters/probes/http_adapter.py +36 -0
  14. netscope/adapters/probes/icmp_adapter.py +70 -0
  15. netscope/adapters/probes/registry.py +100 -0
  16. netscope/adapters/probes/tcp_adapter.py +47 -0
  17. netscope/adapters/probes/tls_adapter.py +31 -0
  18. netscope/adapters/probes/traceroute_adapter.py +30 -0
  19. netscope/app/__init__.py +23 -0
  20. netscope/app/config.py +144 -0
  21. netscope/app/container.py +235 -0
  22. netscope/app/gateway.py +58 -0
  23. netscope/app/monitoring.py +120 -0
  24. netscope/app/reports.py +1079 -0
  25. netscope/app/use_cases.py +1208 -0
  26. netscope/core/__init__.py +0 -0
  27. netscope/core/asn.py +122 -0
  28. netscope/core/baseline.py +186 -0
  29. netscope/core/diagnosis.py +467 -0
  30. netscope/core/discovery.py +42 -0
  31. netscope/core/drift.py +562 -0
  32. netscope/core/geo.py +166 -0
  33. netscope/core/incidents.py +241 -0
  34. netscope/core/loss.py +152 -0
  35. netscope/core/models.py +476 -0
  36. netscope/core/ports.py +348 -0
  37. netscope/core/routing.py +197 -0
  38. netscope/core/scoring.py +223 -0
  39. netscope/explanation/__init__.py +0 -0
  40. netscope/explanation/explainer.py +61 -0
  41. netscope/persistence/__init__.py +0 -0
  42. netscope/persistence/baseline_repository.py +152 -0
  43. netscope/persistence/measurement_repository.py +265 -0
  44. netscope/persistence/route_repository.py +198 -0
  45. netscope/persistence/schema.py +364 -0
  46. netscope/persistence/service_repository.py +166 -0
  47. netscope/probes/__init__.py +0 -0
  48. netscope/probes/bandwidth_probe.py +243 -0
  49. netscope/probes/dns_probe.py +72 -0
  50. netscope/probes/http_probe.py +127 -0
  51. netscope/probes/icmp_probe.py +69 -0
  52. netscope/probes/tcp_probe.py +143 -0
  53. netscope/probes/tls_probe.py +160 -0
  54. netscope/probes/traceroute_probe.py +124 -0
  55. netscope/py.typed +0 -0
  56. netscope/ui/__init__.py +0 -0
  57. netscope/ui/cli.py +1211 -0
  58. netscope/ui/completions.py +341 -0
  59. netscope/ui/man.py +160 -0
  60. netscope/ui/render.py +438 -0
  61. netscope/ui/tui/__init__.py +0 -0
  62. netscope/ui/tui/app.py +250 -0
  63. netscope/ui/tui/screens/__init__.py +31 -0
  64. netscope/ui/tui/screens/dashboard.py +291 -0
  65. netscope/ui/tui/screens/diagnostics.py +170 -0
  66. netscope/ui/tui/screens/history.py +171 -0
  67. netscope/ui/tui/screens/network.py +256 -0
  68. netscope/ui/tui/screens/route.py +189 -0
  69. netscope/ui/tui/screens/services.py +293 -0
  70. netscope-0.19.0.dist-info/METADATA +320 -0
  71. netscope-0.19.0.dist-info/RECORD +76 -0
  72. netscope-0.19.0.dist-info/WHEEL +5 -0
  73. netscope-0.19.0.dist-info/entry_points.txt +2 -0
  74. netscope-0.19.0.dist-info/licenses/LICENSE +21 -0
  75. netscope-0.19.0.dist-info/licenses/NOTICE +43 -0
  76. netscope-0.19.0.dist-info/top_level.txt +1 -0
netscope/__init__.py ADDED
File without changes
@@ -0,0 +1,19 @@
1
+ """
2
+ netscope.adapters
3
+
4
+ Everything NetScope talks to the outside world (network, OS) through
5
+ lives here: probe implementations wrapping third-party libraries
6
+ (icmplib, dnspython, httpx, stdlib socket/ssl), and OS-level discovery
7
+ (gateway, interfaces).
8
+
9
+ This package is a placeholder for now. Per docs/architecture/adr-002-
10
+ probe-adapter-strategy.md and future-roadmap.md, existing probes
11
+ (src/netscope/probes/) and any discovery logic are relocated here in
12
+ later, separately-scoped tasks (TASK-014 through TASK-018 for probes,
13
+ TASK-010 through TASK-012 for discovery) -- not in TASK-005.
14
+
15
+ Rule this package must always follow: it may depend on core (to
16
+ construct/return core.models types) and third-party libraries, but it
17
+ must never be depended on by core, and it must never contain diagnosis-
18
+ shaped judgments -- it only measures and returns.
19
+ """
@@ -0,0 +1,8 @@
1
+ """
2
+ netscope.adapters.discovery
3
+
4
+ Adapter implementations of netscope.core.discovery.DiscoveryProvider.
5
+ Contains all OS/psutil-facing network interface enumeration logic --
6
+ nothing here is imported by core, per the one-way dependency direction
7
+ established for netscope.adapters generally.
8
+ """
@@ -0,0 +1,143 @@
1
+ """
2
+ netscope.adapters.discovery.gateway_detector
3
+
4
+ Default-gateway detection adapter -- best-effort, cross-platform.
5
+
6
+ WHY THIS EXISTS
7
+ ---------------
8
+ `netscope diagnose --gateway` localizes problems (local Wi-Fi/router vs.
9
+ ISP vs. destination), but until now the user had to know and type their
10
+ router's IP on every run. Most users don't. This adapter answers the
11
+ "what's my default gateway?" question automatically so the CLI can ask
12
+ it by default (see `ui/cli.py`'s `--gateway auto` handling and
13
+ app/gateway.py's auto-resolution policy).
14
+
15
+ PLATFORM STRATEGIES (first success wins, then cached)
16
+ ------------------------------------------------------
17
+ - Linux: parse `/proc/net/route` -- the row whose destination column is
18
+ 00000000 carries the gateway as a little-endian hex address. Pure
19
+ file read, no subprocess, no permissions needed.
20
+ - macOS: `route -n get default` -- parse the `gateway:` line.
21
+ - Windows: `route print 0.0.0.0` -- parse the `0.0.0.0 0.0.0.0
22
+ <gateway> ...` active-route row. The regex tolerates the variable
23
+ whitespace/columns Windows uses across versions/locales.
24
+
25
+ CONTRACT
26
+ --------
27
+ - Never raises: any failure (unknown platform, missing tool, parse
28
+ mismatch, timeout) returns None -- gateway detection is an
29
+ optimization, and the diagnose pipeline already handles "no gateway
30
+ measured" honestly (Hypothesis.INSUFFICIENT_EVIDENCE rather than a
31
+ fabricated healthy local result).
32
+ - No hostname resolution, no network I/O to the gateway itself -- pure
33
+ local OS introspection. ICMP-probing the gateway remains the probe
34
+ layer's job.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import re
40
+ import shutil
41
+ import subprocess
42
+ import sys
43
+ from pathlib import Path
44
+
45
+ _PROC_NET_ROUTE = Path("/proc/net/route")
46
+
47
+
48
+ def _detect_linux() -> str | None:
49
+ """Linux: read the default route from /proc/net/route."""
50
+ try:
51
+ lines = _PROC_NET_ROUTE.read_text(encoding="utf-8").splitlines()
52
+ except OSError:
53
+ return None
54
+ for line in lines[1:]: # first line is the header
55
+ parts = line.split()
56
+ if len(parts) < 3:
57
+ continue
58
+ _iface, destination, gateway = parts[0], parts[1], parts[2]
59
+ if destination != "00000000" or gateway == "00000000":
60
+ continue
61
+ try:
62
+ packed = bytes.fromhex(gateway)
63
+ # /proc/net/route stores the address little-endian
64
+ addr = ".".join(str(b) for b in reversed(packed))
65
+ except ValueError:
66
+ continue
67
+ if addr.count(".") == 3 and not addr.startswith("0.0.0.0"):
68
+ return addr
69
+ return None
70
+
71
+
72
+ def _detect_macos() -> str | None:
73
+ """macOS: parse `route -n get default`."""
74
+ if shutil.which("route") is None:
75
+ return None
76
+ try:
77
+ out = subprocess.run(
78
+ ["route", "-n", "get", "default"],
79
+ capture_output=True,
80
+ text=True,
81
+ timeout=5,
82
+ check=False,
83
+ ).stdout
84
+ except (OSError, subprocess.TimeoutExpired):
85
+ return None
86
+ match = re.search(r"^\s*gateway:\s*(\d{1,3}(?:\.\d{1,3}){3})\s*$", out, re.MULTILINE)
87
+ return match.group(1) if match else None
88
+
89
+
90
+ def _detect_windows() -> str | None:
91
+ """Windows: parse the active default route from `route print`."""
92
+ if shutil.which("route") is None:
93
+ return None
94
+ try:
95
+ out = subprocess.run(
96
+ ["route", "print", "0.0.0.0"],
97
+ capture_output=True,
98
+ text=True,
99
+ timeout=5,
100
+ check=False,
101
+ ).stdout
102
+ except (OSError, subprocess.TimeoutExpired):
103
+ return None
104
+ # The active-route table row: destination 0.0.0.0, netmask 0.0.0.0, then gateway.
105
+ for line in out.splitlines():
106
+ if "0.0.0.0" not in line:
107
+ continue
108
+ match = re.search(
109
+ r"0\.0\.0\.0\s+0\.0\.0\.0\s+(\d{1,3}(?:\.\d{1,3}){3})",
110
+ line,
111
+ )
112
+ if match:
113
+ return match.group(1)
114
+ return None
115
+
116
+
117
+ class GatewayDetector:
118
+ """Detects the local default gateway, best-effort, per platform.
119
+
120
+ `strategy` is injectable for tests (e.g. a lambda returning a fixed
121
+ address); production code uses `detect_default_gateway()`, which
122
+ picks the right platform strategy automatically.
123
+ """
124
+
125
+ def __init__(self, strategy=None):
126
+ self._strategy = strategy
127
+
128
+ def detect(self) -> str | None:
129
+ if self._strategy is not None:
130
+ return self._strategy()
131
+ return detect_default_gateway()
132
+
133
+
134
+ def detect_default_gateway() -> str | None:
135
+ """Best-effort default gateway address, or None if it can't be
136
+ determined. Never raises."""
137
+ if sys.platform.startswith("linux"):
138
+ return _detect_linux()
139
+ if sys.platform == "darwin":
140
+ return _detect_macos()
141
+ if sys.platform == "win32":
142
+ return _detect_windows()
143
+ return None
@@ -0,0 +1,78 @@
1
+ """
2
+ netscope.adapters.discovery.hostname_resolver
3
+
4
+ Reverse-DNS hostname resolution for traceroute hops -- best-effort,
5
+ bounded-time, off the hot path.
6
+
7
+ WHY THIS EXISTS
8
+ ---------------
9
+ `netscope route` prints hop addresses; hostnames make routes humanly
10
+ readable ("one.hundredgige...-ix.lax1.att-gw.net" says far more than
11
+ "12.122.128.1"). The traceroute probe itself deliberately does NOT
12
+ resolve hostnames (icmplib doesn't, and resolution shouldn't slow or
13
+ complicate the measurement itself), so resolution is a separate,
14
+ optional enrichment the route-analysis use case applies when asked.
15
+
16
+ DESIGN
17
+ ------
18
+ - ThreadPoolExecutor so the per-hop resolution happens concurrently:
19
+ a 15-hop route resolves in the time of its slowest hop, not their
20
+ sum.
21
+ - `socket.gethostbyaddr` inside a daemon-thread pool; the pool is
22
+ shut down with a bounded wait (`timeout`), so one pathological
23
+ resolver can only delay the command by the configured timeout, not
24
+ hang it.
25
+ - Never raises: any failure per hop (NXDOMAIN, timeout, no reverse
26
+ record) simply leaves that hop's hostname as None.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import socket
32
+ from concurrent.futures import ThreadPoolExecutor
33
+
34
+
35
+ def _resolve_one(address: str) -> str | None:
36
+ """Single reverse-DNS lookup. Returns the canonical hostname, or
37
+ None if the address has none. Never raises."""
38
+ try:
39
+ hostname, _, _ = socket.gethostbyaddr(address)
40
+ return hostname.rstrip(".") or None
41
+ except (socket.herror, socket.gaierror, OSError, UnicodeError):
42
+ return None
43
+
44
+
45
+ class HostnameResolver:
46
+ """Concurrent, bounded-time reverse-DNS resolution for hop
47
+ addresses. `timeout` bounds the *entire* batch wait, not per-hop
48
+ DNS timeout (stdlib gethostbyaddr has no timeout parameter; the
49
+ executor-level deadline is the practical bound)."""
50
+
51
+ def __init__(self, timeout: float = 4.0, max_workers: int = 16):
52
+ self._timeout = timeout
53
+ self._max_workers = max_workers
54
+
55
+ def resolve_all(self, addresses: list[str | None]) -> dict[str, str | None]:
56
+ """Resolve every non-None address in `addresses` concurrently.
57
+
58
+ Returns a mapping address -> hostname (or None where no
59
+ hostname exists / resolution failed / the batch deadline
60
+ passed). Deterministic output: every requested address gets a
61
+ key.
62
+ """
63
+ unique = list(dict.fromkeys(a for a in addresses if a))
64
+ if not unique:
65
+ return {}
66
+
67
+ results: dict[str, str | None] = dict.fromkeys(unique)
68
+ try:
69
+ with ThreadPoolExecutor(max_workers=self._max_workers) as pool:
70
+ futures = {pool.submit(_resolve_one, addr): addr for addr in unique}
71
+ for future, addr in futures.items():
72
+ try:
73
+ results[addr] = future.result(timeout=self._timeout)
74
+ except Exception: # noqa: BLE001 -- enrichment must never propagate
75
+ results[addr] = None
76
+ except Exception: # noqa: BLE001 -- a dead pool must not kill a route command
77
+ return dict.fromkeys(unique)
78
+ return results
@@ -0,0 +1,85 @@
1
+ """
2
+ Adapter implementing netscope.core.discovery.DiscoveryProvider using
3
+ psutil (BSD-3-Clause) -- see adr-010-network-discovery.md for why
4
+ psutil, previously an unused dependency (per implementation-audit.md),
5
+ is used here.
6
+
7
+ Uses psutil.net_if_addrs() and psutil.net_if_stats() to enumerate local
8
+ interfaces and their up/down state, and translates the result into
9
+ NetworkInterface/NetworkSnapshot -- the existing domain models. Contains
10
+ no probing/measurement logic of its own, and (like the probe adapters
11
+ in adapters/probes/) is a thin translation layer, not a reimplementation
12
+ of what psutil already does. Interface-name-based network type
13
+ classification (TASK-012) is delegated entirely to the isolated, pure
14
+ network_type_classifier module, not implemented here.
15
+
16
+ discover_context() (TASK-013) is a thin, additive wrapper assembling
17
+ the result of discover() into a NetworkContext -- see NetworkContext's
18
+ own docstring in core/models.py for why it exists as a separate type.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from netscope.adapters.discovery.network_type_classifier import classify_network_type
24
+ from netscope.core.models import NetworkContext, NetworkInterface, NetworkSnapshot, utcnow
25
+
26
+ try:
27
+ import psutil
28
+
29
+ _PSUTIL_AVAILABLE = True
30
+ except ImportError:
31
+ _PSUTIL_AVAILABLE = False
32
+
33
+
34
+ class PsutilNetworkDiscovery:
35
+ """Satisfies netscope.core.discovery.DiscoveryProvider by wrapping
36
+ psutil.net_if_addrs() / psutil.net_if_stats()."""
37
+
38
+ def discover(self) -> NetworkSnapshot:
39
+ if not _PSUTIL_AVAILABLE:
40
+ # Defined, explicit empty-result behavior rather than raising --
41
+ # mirrors icmp_probe.py's pattern of returning a well-formed,
42
+ # empty/unsuccessful result when its library isn't installed,
43
+ # instead of letting an ImportError propagate to the caller.
44
+ return NetworkSnapshot(timestamp=utcnow(), interfaces=[])
45
+
46
+ addrs_by_interface = psutil.net_if_addrs()
47
+ stats_by_interface = psutil.net_if_stats()
48
+
49
+ interfaces: list[NetworkInterface] = []
50
+ for name, addr_list in addrs_by_interface.items():
51
+ stats = stats_by_interface.get(name)
52
+ is_up = stats.isup if stats is not None else False
53
+
54
+ # AF_LINK entries are MAC/link-layer addresses, not IP
55
+ # addresses -- excluded here since NetworkInterface.addresses
56
+ # represents IP addresses. psutil.AF_LINK is used (rather
57
+ # than importing the stdlib `socket` module for AF_INET/
58
+ # AF_INET6) to keep this adapter's family-filtering logic
59
+ # working directly off what psutil already reports.
60
+ addresses = [a.address for a in addr_list if a.family != psutil.AF_LINK and a.address]
61
+
62
+ interfaces.append(
63
+ NetworkInterface(
64
+ name=name,
65
+ is_up=is_up,
66
+ addresses=addresses,
67
+ is_loopback="loopback" in (stats.flags if stats else "").split(","),
68
+ network_type=classify_network_type(name),
69
+ )
70
+ )
71
+
72
+ return NetworkSnapshot(timestamp=utcnow(), interfaces=interfaces)
73
+
74
+ def discover_context(self) -> NetworkContext:
75
+ """Additive convenience method (TASK-013, "Network metadata"):
76
+ assembles this adapter's NetworkSnapshot into a NetworkContext.
77
+
78
+ discover() itself is completely unchanged by this method's
79
+ addition -- this simply calls it and wraps the result, so
80
+ existing callers of discover() (and the DiscoveryProvider
81
+ Protocol in core/discovery.py, not modified by this task) keep
82
+ working exactly as before. This method is additive surface, not
83
+ a replacement.
84
+ """
85
+ return NetworkContext.from_snapshot(self.discover())
@@ -0,0 +1,74 @@
1
+ """
2
+ netscope.adapters.discovery.network_type_classifier
3
+
4
+ Best-effort classification of a network interface's connection type
5
+ (Wi-Fi, Ethernet, or Cellular) from its interface name alone.
6
+
7
+ WHY THIS IS BEST-EFFORT, NOT RELIABLE
8
+ ----------------------------------------
9
+ There is no single, universally reliable way to determine an
10
+ interface's physical connection type from userspace across Windows,
11
+ Linux, and macOS without OS-specific APIs this project's dependency
12
+ policy doesn't currently justify adding (dependency-strategy.md). What
13
+ IS reasonably consistent, though never guaranteed, is naming
14
+ convention:
15
+
16
+ - Linux's systemd predictable network interface naming scheme uses
17
+ "wl*" for wireless LAN (wlan0, wlp2s0), "ww*" for WWAN/cellular
18
+ modems (wwan0, wwp0s20u), and "en*" for Ethernet (enp0s3, eno1,
19
+ ens33), alongside the older, still-common "eth*"/"wlan*" naming.
20
+ - Windows and macOS commonly expose human-readable adapter names
21
+ ("Wi-Fi", "Ethernet", "Cellular") via the same libraries/APIs this
22
+ project already uses (psutil), rather than only raw device names.
23
+
24
+ This module matches against both conventions, case-insensitively.
25
+ Any interface name that doesn't match a known pattern -- including
26
+ loopback ("lo"), virtual/container interfaces (Docker's "docker0",
27
+ "veth*"), bridges, tunnels ("tun*"/"tap*"), and simply unrecognized
28
+ names -- classifies as NetworkType.UNKNOWN. This is a deliberate,
29
+ safe default, not a failure: TASK-012 explicitly does not introduce a
30
+ fourth physical network type to avoid this uncertainty, and callers
31
+ must not treat UNKNOWN as an error.
32
+
33
+ This classification never depends on having an active connection, DNS
34
+ resolution, or any network I/O -- it is a pure, deterministic function
35
+ of the interface name string, kept isolated here specifically so it is
36
+ easy to unit test without psutil or any other adapter dependency.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ from netscope.core.models import NetworkType
42
+
43
+ # Checked in this order deliberately: cellular's "ww" prefix is checked
44
+ # before wifi's "wl" prefix (both start with "w", but "ww" is more
45
+ # specific and must win), and ethernet's "en"/"eth" prefixes are
46
+ # checked last since they're the least likely to collide with the
47
+ # others.
48
+ _CELLULAR_MARKERS = ("wwan", "cellular", "mobile", "rmnet", "ppp")
49
+ _WIFI_MARKERS = ("wifi", "wi-fi", "wireless", "airport")
50
+ _ETHERNET_MARKERS = ("ethernet",)
51
+
52
+
53
+ def classify_network_type(interface_name: str | None) -> NetworkType:
54
+ """Best-effort classification of `interface_name` into Wi-Fi,
55
+ Ethernet, Cellular, or Unknown. Never raises -- missing, empty, or
56
+ unrecognized input all safely classify as NetworkType.UNKNOWN."""
57
+
58
+ if not interface_name:
59
+ return NetworkType.UNKNOWN
60
+
61
+ name = interface_name.strip().lower()
62
+ if not name:
63
+ return NetworkType.UNKNOWN
64
+
65
+ if name.startswith("ww") or any(marker in name for marker in _CELLULAR_MARKERS):
66
+ return NetworkType.CELLULAR
67
+
68
+ if name.startswith("wl") or any(marker in name for marker in _WIFI_MARKERS):
69
+ return NetworkType.WIFI
70
+
71
+ if name.startswith(("en", "eth")) or any(marker in name for marker in _ETHERNET_MARKERS):
72
+ return NetworkType.ETHERNET
73
+
74
+ return NetworkType.UNKNOWN