pyinternetbox 0.1.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 (49) hide show
  1. internetbox_client/__init__.py +14 -0
  2. internetbox_client/cli.py +296 -0
  3. internetbox_client/client.py +85 -0
  4. internetbox_client/exporter.py +220 -0
  5. internetbox_client/metrics.py +479 -0
  6. internetbox_client/resources/__init__.py +73 -0
  7. internetbox_client/resources/ap_services.py +26 -0
  8. internetbox_client/resources/carddav.py +10 -0
  9. internetbox_client/resources/debug.py +15 -0
  10. internetbox_client/resources/dect.py +60 -0
  11. internetbox_client/resources/devices.py +68 -0
  12. internetbox_client/resources/dhcp.py +42 -0
  13. internetbox_client/resources/dns.py +35 -0
  14. internetbox_client/resources/dyndns.py +20 -0
  15. internetbox_client/resources/events.py +182 -0
  16. internetbox_client/resources/firewall.py +25 -0
  17. internetbox_client/resources/genlog.py +25 -0
  18. internetbox_client/resources/history.py +15 -0
  19. internetbox_client/resources/http_service.py +10 -0
  20. internetbox_client/resources/lan.py +63 -0
  21. internetbox_client/resources/led.py +172 -0
  22. internetbox_client/resources/mitigation.py +10 -0
  23. internetbox_client/resources/mst.py +38 -0
  24. internetbox_client/resources/nmc.py +50 -0
  25. internetbox_client/resources/oops_tracker.py +15 -0
  26. internetbox_client/resources/password_recovery.py +10 -0
  27. internetbox_client/resources/phonebook.py +23 -0
  28. internetbox_client/resources/power_management.py +10 -0
  29. internetbox_client/resources/scheduler.py +14 -0
  30. internetbox_client/resources/security.py +20 -0
  31. internetbox_client/resources/speedtest.py +52 -0
  32. internetbox_client/resources/static.py +15 -0
  33. internetbox_client/resources/sysbus.py +70 -0
  34. internetbox_client/resources/temperature.py +10 -0
  35. internetbox_client/resources/user_management.py +10 -0
  36. internetbox_client/resources/voice.py +35 -0
  37. internetbox_client/resources/vpn.py +15 -0
  38. internetbox_client/resources/webui.py +15 -0
  39. internetbox_client/resources/wifi.py +157 -0
  40. internetbox_client/resources/wireguard.py +29 -0
  41. internetbox_client/resources/wwan.py +25 -0
  42. internetbox_client/utils/APIClient.py +223 -0
  43. internetbox_client/utils/__init__.py +0 -0
  44. internetbox_client/utils/helpers.py +41 -0
  45. pyinternetbox-0.1.0.dist-info/METADATA +390 -0
  46. pyinternetbox-0.1.0.dist-info/RECORD +49 -0
  47. pyinternetbox-0.1.0.dist-info/WHEEL +4 -0
  48. pyinternetbox-0.1.0.dist-info/entry_points.txt +2 -0
  49. pyinternetbox-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,14 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from internetbox_client.client import InternetBoxClient
4
+ from internetbox_client.utils.APIClient import APIClient, SessionManager
5
+
6
+ try:
7
+ __version__ = version("pyinternetbox")
8
+ except PackageNotFoundError: # running from a source tree that was never installed
9
+ __version__ = "0.0.0"
10
+
11
+ PROJECT_NAME = "pyinternetbox"
12
+ PROJECT_URL = "https://github.com/oregonpillow/pyinternetbox"
13
+
14
+ __all__ = ["PROJECT_NAME", "PROJECT_URL", "APIClient", "InternetBoxClient", "SessionManager", "__version__"]
@@ -0,0 +1,296 @@
1
+ """Typer CLI for the Internet Box Client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import json
7
+ import threading
8
+ import typing
9
+ from typing import TYPE_CHECKING, Annotated, Optional
10
+
11
+ import typer
12
+
13
+ from internetbox_client import PROJECT_NAME, PROJECT_URL, __version__
14
+ from internetbox_client.utils.APIClient import APIClient
15
+
16
+ if TYPE_CHECKING:
17
+ from internetbox_client import InternetBoxClient
18
+
19
+ app = typer.Typer(name="internetbox", help="CLI for the Swisscom Internet Box API.")
20
+
21
+ # ── Global state set by the callback ──────────────────────────────────
22
+ _hostname: str = "https://internetbox.swisscom.ch"
23
+ _password: str = ""
24
+ _username: str = "admin"
25
+ _insecure: bool = False
26
+
27
+
28
+ def _version_callback(value: bool) -> None:
29
+ if value:
30
+ typer.echo(f"{PROJECT_NAME} {__version__}")
31
+ raise typer.Exit()
32
+
33
+
34
+ @app.callback()
35
+ def main(
36
+ hostname: Annotated[
37
+ str, typer.Option("--host", "-H", envvar="IB_HOSTNAME", help="Router hostname or IP.")
38
+ ] = "https://internetbox.swisscom.ch",
39
+ password: Annotated[str, typer.Option("--password", "-p", envvar="IB_PASSWORD", help="Router admin password.")] = "",
40
+ username: Annotated[str, typer.Option("--username", "-u", envvar="IB_USERNAME", help="Router admin username.")] = "admin",
41
+ insecure: Annotated[
42
+ bool, typer.Option("--insecure", "-k", help="Skip SSL certificate verification (done automatically when --host is an IP address).")
43
+ ] = False,
44
+ version: Annotated[
45
+ bool, typer.Option("--version", "-V", callback=_version_callback, is_eager=True, help="Show the version and exit.")
46
+ ] = False,
47
+ ):
48
+ global _hostname, _password, _username, _insecure
49
+ _hostname = hostname
50
+ _password = password
51
+ _username = username
52
+ _insecure = insecure
53
+
54
+
55
+ def _output(raw: str) -> None:
56
+ """Pretty-print a JSON response to stdout (valid JSON, jq-compatible)."""
57
+ try:
58
+ data = json.loads(raw)
59
+ typer.echo(json.dumps(data, indent=2, ensure_ascii=False))
60
+ except (json.JSONDecodeError, ValueError):
61
+ typer.echo(raw)
62
+
63
+
64
+ def _make_client() -> InternetBoxClient:
65
+ from internetbox_client import InternetBoxClient
66
+
67
+ return InternetBoxClient(hostname=_hostname, password=_password, username=_username, ssl_verify=False if _insecure else None)
68
+
69
+
70
+ # ── Dynamic CLI generation ────────────────────────────────────────────
71
+
72
+
73
+ def _typer_annotation(param: inspect.Parameter) -> type:
74
+ """Map a resource-method parameter annotation to a Typer-friendly type."""
75
+ ann = param.annotation
76
+ if ann in (int, float, str, bool):
77
+ return ann
78
+ # dict, list, Literal, and anything else → accept as string on the CLI
79
+ return str
80
+
81
+
82
+ def _typer_help(pname: str, param: inspect.Parameter) -> str:
83
+ """Build a short help string for a CLI parameter."""
84
+ ann = param.annotation
85
+ help_str = pname.replace("_", " ").title()
86
+ if ann is list:
87
+ help_str += " (comma-separated or JSON array)"
88
+ elif getattr(ann, "__origin__", None) is typing.Literal:
89
+ help_str += f" (choices: {list(ann.__args__)})"
90
+ return help_str
91
+
92
+
93
+ def _coerce_value(val: str, ann: type) -> object:
94
+ """Coerce a CLI string value to the target annotation type."""
95
+ if ann in (dict, list):
96
+ return json.loads(val)
97
+ if ann is list:
98
+ try:
99
+ return json.loads(val)
100
+ except (json.JSONDecodeError, ValueError):
101
+ return [v.strip() for v in val.split(",") if v.strip()]
102
+ if ann in (int, float):
103
+ return ann(val)
104
+ if getattr(ann, "__origin__", None) is typing.Literal:
105
+ return type(ann.__args__[0])(val)
106
+ return val
107
+
108
+
109
+ def _build_command_func(attr_name: str, method_name: str, params: list[tuple[str, inspect.Parameter]]):
110
+ """Return a function with an explicit signature matching *params*.
111
+
112
+ Typer introspects function signatures to generate CLI arguments/options.
113
+ We dynamically create a function whose parameter names, defaults and
114
+ ``Annotated`` type hints match the resource method so that Typer can
115
+ generate proper ``--option`` / ``ARGUMENT`` entries.
116
+ """
117
+ # Build the function source with the correct signature
118
+ sig_parts: list[str] = []
119
+ for pname, param in params:
120
+ ann_type = _typer_annotation(param)
121
+ help_str = _typer_help(pname, param)
122
+ has_default = param.default is not inspect.Parameter.empty
123
+
124
+ if has_default:
125
+ # Typer Option
126
+ sig_parts.append(
127
+ f"{pname}: Annotated[Optional[{ann_type.__name__}], "
128
+ f'typer.Option("--{pname.replace("_", "-")}", help={help_str!r}, show_default=True)] = {param.default!r}'
129
+ )
130
+ else:
131
+ # Typer Argument
132
+ sig_parts.append(f"{pname}: Annotated[{ann_type.__name__}, typer.Argument(help={help_str!r})]")
133
+
134
+ sig = ", ".join(sig_parts)
135
+ func_src = f"def cmd({sig}):\n _invoke({attr_name!r}, {method_name!r}, locals())\n"
136
+
137
+ # Namespace for exec
138
+ ns: dict[str, object] = {
139
+ "Annotated": Annotated,
140
+ "Optional": Optional,
141
+ "typer": typer,
142
+ "_invoke": None, # placeholder, set below
143
+ }
144
+ for pname, param in params:
145
+ ns[_typer_annotation(param).__name__] = _typer_annotation(param)
146
+
147
+ exec(func_src, ns) # noqa: S102
148
+ cmd = ns["cmd"]
149
+
150
+ # Wire up the actual invocation logic (closure, not exec'd)
151
+ def _invoke(a: str, m: str, local_values: dict) -> None:
152
+ with _make_client() as client:
153
+ resource = getattr(client, a)
154
+ call_kwargs = {}
155
+ for pname, param in params:
156
+ val = local_values.get(pname)
157
+ if val is not None:
158
+ val = _coerce_value(val, param.annotation)
159
+ call_kwargs[pname] = val
160
+ _output(getattr(resource, m)(**call_kwargs))
161
+
162
+ ns["_invoke"] = _invoke
163
+ return cmd
164
+
165
+
166
+ def _register_command(
167
+ group: typer.Typer, attr_name: str, method_name: str, params: list[tuple[str, inspect.Parameter]], help_text: str
168
+ ) -> None:
169
+ """Register a single CLI command, with or without parameters."""
170
+ cli_name = method_name.replace("_", "-")
171
+
172
+ if not params:
173
+
174
+ def _make_no_param_cmd(a: str = attr_name, m: str = method_name):
175
+ @group.command(name=cli_name, help=help_text)
176
+ def cmd():
177
+ with _make_client() as client:
178
+ _output(getattr(getattr(client, a), m)())
179
+
180
+ _make_no_param_cmd()
181
+ else:
182
+ cmd = _build_command_func(attr_name, method_name, params)
183
+ group.command(name=cli_name, help=help_text)(cmd)
184
+
185
+
186
+ def _build_cli() -> None:
187
+ """Introspect InternetBoxClient and register all sub-commands."""
188
+ import internetbox_client.resources as ibc_module
189
+ from internetbox_client import InternetBoxClient
190
+
191
+ # Discover all APIClient subclasses in the module
192
+ resource_classes: dict[str, type] = {}
193
+ for name, obj in inspect.getmembers(ibc_module, inspect.isclass):
194
+ if issubclass(obj, APIClient) and obj is not APIClient:
195
+ resource_classes[name] = obj
196
+
197
+ # Map attr names → classes by parsing __init__ source lines
198
+ init_source = inspect.getsource(InternetBoxClient.__init__)
199
+ attr_to_class: dict[str, type] = {}
200
+ for line in init_source.splitlines():
201
+ line = line.strip()
202
+ if line.startswith("self.") and "session_manager=" in line and not line.startswith("self._"):
203
+ attr_name = line.split("=")[0].replace("self.", "").strip()
204
+ cls_name = line.split("=", 1)[1].strip().split("(")[0].strip()
205
+ if cls_name in resource_classes:
206
+ attr_to_class[attr_name] = resource_classes[cls_name]
207
+
208
+ # Only skip methods that are defined directly on APIClient (the HTTP helpers),
209
+ # not methods that a subclass has overridden with domain logic (e.g. Devices.get).
210
+ api_client_methods = set(APIClient.__dict__)
211
+
212
+ for attr_name, cls in attr_to_class.items():
213
+ group = typer.Typer(help=cls.__doc__ or f"{attr_name} commands")
214
+
215
+ for method_name, method in inspect.getmembers(cls, predicate=inspect.isfunction):
216
+ if method_name.startswith("_") or (method_name in api_client_methods and method_name not in cls.__dict__):
217
+ continue
218
+
219
+ sig = inspect.signature(method)
220
+ doc = (method.__doc__ or "").strip().split("\n")[0] # Use first line of docstring as command help
221
+ # doc = inspect.cleandoc(method.__doc__ or "") # Use full cleaned docstring as command help
222
+ params = [(n, p) for n, p in sig.parameters.items() if n != "self"]
223
+
224
+ _register_command(group, attr_name, method_name, params, doc)
225
+
226
+ app.add_typer(group, name=attr_name.replace("_", "-"))
227
+
228
+
229
+ _build_cli()
230
+
231
+
232
+ # ── Prometheus exporter ──────────────────────────────────────────────
233
+
234
+
235
+ @app.command()
236
+ def export(
237
+ port: Annotated[int, typer.Option("--port", "-P", envvar="IB_EXPORTER_PORT", help="TCP port the /metrics endpoint listens on.")] = 9101,
238
+ interval: Annotated[
239
+ int, typer.Option("--interval", "-i", envvar="IB_EXPORTER_INTERVAL", help="Seconds between data collection cycles.")
240
+ ] = 30,
241
+ ) -> None:
242
+ """Start a Prometheus /metrics exporter for the Internet Box.
243
+
244
+ Opens a single authenticated session and keeps it alive for the lifetime
245
+ of the process. User-defined collection callbacks are called every
246
+ INTERVAL seconds in a background thread; the resulting Gauge metrics are
247
+ served at http://0.0.0.0:PORT/metrics.
248
+
249
+ Register collection callbacks via InternetBoxCollector.register_collector
250
+ before the export loop starts. Each callback receives the collector
251
+ instance and should call update_gauge() to publish values.
252
+
253
+ Connection credentials are taken from --host / --password / --username
254
+ (or the IB_HOSTNAME / IB_PASSWORD / IB_USERNAME environment variables)
255
+ supplied before the 'export' sub-command.
256
+ """
257
+ import signal
258
+
259
+ import prometheus_client
260
+
261
+ from internetbox_client.exporter import InternetBoxCollector
262
+ from internetbox_client.metrics import register_metrics
263
+
264
+ typer.echo(f"{PROJECT_NAME} {__version__} | {PROJECT_URL}")
265
+
266
+ client = _make_client()
267
+ # Use a distinct application name so the exporter session does not
268
+ # collide with an active browser session on the router.
269
+ client._sm.application_name = "prometheus-exporter"
270
+
271
+ collector = InternetBoxCollector(client, interval=interval)
272
+ register_metrics(collector, client)
273
+ collector.start()
274
+
275
+ prometheus_client.REGISTRY.register(collector)
276
+ prometheus_client.start_http_server(port)
277
+
278
+ typer.echo(f"Prometheus exporter listening on http://0.0.0.0:{port}/metrics")
279
+ typer.echo(f"Collection interval: {interval}s | Press Ctrl-C to stop.")
280
+
281
+ _shutdown = threading.Event()
282
+ signal.signal(signal.SIGTERM, lambda _sig, _frame: _shutdown.set())
283
+
284
+ try:
285
+ while not _shutdown.wait(timeout=1):
286
+ pass
287
+ except KeyboardInterrupt:
288
+ pass
289
+ finally:
290
+ typer.echo("Stopping exporter...")
291
+ collector.stop()
292
+ client.close()
293
+
294
+
295
+ if __name__ == "__main__":
296
+ app()
@@ -0,0 +1,85 @@
1
+ """Unified InternetBoxClient bundling all resource groups."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import TracebackType
6
+ from typing import Any
7
+
8
+ from internetbox_client.resources import * # noqa: F403
9
+ from internetbox_client.utils.APIClient import SessionManager
10
+
11
+
12
+ class InternetBoxClient:
13
+ """Unified client for the Internet Box API.
14
+
15
+ Initializes a single authenticated session and exposes all resource
16
+ groups as attributes. Use as a context manager for automatic cleanup::
17
+
18
+ with InternetBoxClient(password="secret") as client:
19
+ print(client.devices.info())
20
+ print(client.vpn.status())
21
+
22
+ Connection parameters fall back to the ``IB_HOSTNAME``, ``IB_PASSWORD``,
23
+ and ``IB_USERNAME`` environment variables when not provided explicitly.
24
+ """
25
+
26
+ def __init__(
27
+ self, hostname: str | None = None, password: str | None = None, username: str | None = None, ssl_verify: bool | None = None
28
+ ) -> None:
29
+ kwargs: dict[str, Any] = {}
30
+ if hostname is not None:
31
+ kwargs["hostname"] = hostname
32
+ if password is not None:
33
+ kwargs["password"] = password
34
+ if username is not None:
35
+ kwargs["username"] = username
36
+ if ssl_verify is not None:
37
+ kwargs["ssl_verify"] = ssl_verify
38
+ self._sm = SessionManager(**kwargs)
39
+
40
+ self.devices = Devices(session_manager=self._sm)
41
+ self.sysbus = Sysbus(session_manager=self._sm)
42
+ self.mitigation = Mitigation(session_manager=self._sm)
43
+ self.nmc = NMC(session_manager=self._sm)
44
+ self.voice = Voice(session_manager=self._sm)
45
+ self.password_recovery = PasswordRecovery(session_manager=self._sm)
46
+ self.dns = DNS(session_manager=self._sm)
47
+ self.wifi = Wifi(session_manager=self._sm)
48
+ self.lan = LAN(session_manager=self._sm)
49
+ self.events = Events(session_manager=self._sm)
50
+ self.wwan = WWAN(session_manager=self._sm)
51
+ self.static = Static(session_manager=self._sm)
52
+ self.wireguard = Wireguard(session_manager=self._sm)
53
+ self.firewall = Firewall(session_manager=self._sm)
54
+ self.security = Security(session_manager=self._sm)
55
+ self.debug = Debug(session_manager=self._sm)
56
+ self.led = LED(session_manager=self._sm)
57
+ self.dect = DECT(session_manager=self._sm)
58
+ self.dhcp = DHCP(session_manager=self._sm)
59
+ self.dyndns = DynDNS(session_manager=self._sm)
60
+ self.carddav = CardDav(session_manager=self._sm)
61
+ self.genlog = GenLog(session_manager=self._sm)
62
+ self.http_service = HTTPService(session_manager=self._sm)
63
+ self.history = History(session_manager=self._sm)
64
+ self.phonebook = Phonebook(session_manager=self._sm)
65
+ self.power_management = PowerManagement(session_manager=self._sm)
66
+ self.scheduler = Scheduler(session_manager=self._sm)
67
+ self.temperature = Temperature(session_manager=self._sm)
68
+ self.mst = MST(session_manager=self._sm)
69
+ self.oops_tracker = OopsTracker(session_manager=self._sm)
70
+ self.user_management = UserManagement(session_manager=self._sm)
71
+ self.vpn = VPN(session_manager=self._sm)
72
+ self.webui = WebUI(session_manager=self._sm)
73
+ self.speedtest = SpeedTest(session_manager=self._sm)
74
+ self.ap_services = APServices(session_manager=self._sm)
75
+
76
+ def close(self) -> None:
77
+ """Log out and close the session."""
78
+ self._sm.close()
79
+
80
+ def __enter__(self) -> InternetBoxClient:
81
+ return self
82
+
83
+ def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> bool:
84
+ self.close()
85
+ return False
@@ -0,0 +1,220 @@
1
+ """Prometheus exporter for the Internet Box.
2
+
3
+ Provides `InternetBoxCollector`, a custom Prometheus Collector that polls
4
+ the router on a background thread. Metrics are published by registering
5
+ collection callbacks that call `InternetBoxCollector.update_gauge` (or
6
+ `InternetBoxCollector.update_counter`).
7
+
8
+ Samples that a callback stops reporting (e.g. a device that disconnected) are
9
+ dropped after the callback's next successful run, so stale label sets do not
10
+ linger until the exporter restarts.
11
+
12
+ The session authenticates lazily and re-authenticates automatically if a
13
+ 401 is received mid-scrape.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import threading
20
+ from collections.abc import Callable
21
+ from typing import TYPE_CHECKING
22
+
23
+ from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily
24
+ from prometheus_client.registry import Collector
25
+
26
+ if TYPE_CHECKING:
27
+ from internetbox_client import InternetBoxClient
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class _GaugeMetric:
33
+ """Internal representation of a single named Gauge (or Counter) metric.
34
+
35
+ Stores one sample per unique label-value combination, together with the
36
+ collection cycle in which it was last set.
37
+ """
38
+
39
+ __slots__ = ("name", "description", "label_names", "kind", "owner", "_samples", "_cycles")
40
+
41
+ def __init__(self, name: str, description: str, label_names: list[str], kind: str = "gauge", owner: object = None) -> None:
42
+ self.name = name
43
+ self.description = description
44
+ self.label_names = list(label_names)
45
+ self.kind = kind
46
+ # Callback that created this metric; its samples are pruned after that callback runs
47
+ self.owner = owner
48
+ # Map of label-value tuple -> float sample
49
+ self._samples: dict[tuple[str, ...], float] = {}
50
+ # Map of label-value tuple -> collection cycle in which the sample was last set
51
+ self._cycles: dict[tuple[str, ...], int] = {}
52
+
53
+ def set(self, value: float, labels: dict[str, str] | None, cycle: int = 0) -> None:
54
+ key = tuple((labels or {}).get(k, "") for k in self.label_names)
55
+ self._samples[key] = float(value)
56
+ self._cycles[key] = cycle
57
+
58
+ def prune(self, cycle: int) -> None:
59
+ """Drop samples that were not set during *cycle*."""
60
+ for key in [k for k, c in self._cycles.items() if c != cycle]:
61
+ del self._samples[key]
62
+ del self._cycles[key]
63
+
64
+ def to_prometheus(self) -> GaugeMetricFamily | CounterMetricFamily:
65
+ family = CounterMetricFamily if self.kind == "counter" else GaugeMetricFamily
66
+ mf = family(self.name, self.description, labels=self.label_names if self.label_names else None)
67
+ for label_vals, value in self._samples.items():
68
+ mf.add_metric(list(label_vals), value)
69
+ return mf
70
+
71
+
72
+ class InternetBoxCollector(Collector):
73
+ """Prometheus custom collector for the Internet Box.
74
+
75
+ Maintains a thread-safe Gauge registry. Registered callbacks are invoked
76
+ every `interval` seconds on a background thread so scrapes always see
77
+ fresh data.
78
+
79
+ Args:
80
+ client: An `InternetBoxClient` instance. The collector does not manage
81
+ its lifecycle — callers must call `client.close()` on shutdown.
82
+ interval: Seconds between collection cycles. Defaults to 30.
83
+ """
84
+
85
+ def __init__(self, client: InternetBoxClient, interval: int = 30) -> None:
86
+ self._client = client
87
+ self._interval = interval
88
+ self._lock = threading.Lock()
89
+ self._gauges: dict[str, _GaugeMetric] = {}
90
+ self._callbacks: list[Callable[[InternetBoxCollector], None]] = []
91
+ self._stop_event = threading.Event()
92
+ self._thread = threading.Thread(target=self._run, name="ib-exporter", daemon=True)
93
+ self._cycle = 0
94
+ self._current_callback: Callable[[InternetBoxCollector], None] | None = None
95
+ self.default_labels: dict[str, str] = {}
96
+
97
+ # ── Metric registration ──────────────────────────────────────────
98
+
99
+ def register_collector(self, fn: Callable[[InternetBoxCollector], None]) -> Callable[[InternetBoxCollector], None]:
100
+ """Register a collection callback (also usable as a decorator).
101
+
102
+ The callback receives this collector as its only argument and should
103
+ call `update_gauge` to publish values. Exceptions are caught and
104
+ logged so the collection loop continues.
105
+
106
+ Args:
107
+ fn: Callable that accepts this `InternetBoxCollector` instance.
108
+
109
+ Returns:
110
+ The original function, unchanged.
111
+
112
+ Example::
113
+
114
+ @collector.register_collector
115
+ def my_metrics(col):
116
+ col.update_gauge("my_metric", 42.0)
117
+ """
118
+ self._callbacks.append(fn)
119
+ return fn
120
+
121
+ # ── Metric update API ────────────────────────────────────────────
122
+
123
+ def update_gauge(self, name: str, value: float, labels: dict[str, str] | None = None, description: str = "") -> None:
124
+ """Create or update a Gauge metric sample.
125
+
126
+ Args:
127
+ name: Prometheus metric name (e.g. ``internetbox_wifi_noise_dbm``).
128
+ Must be stable across calls for the same logical metric.
129
+ value: Current numeric value.
130
+ labels: Optional label name → value mapping. Label names are fixed
131
+ on first call; only values may change on subsequent calls.
132
+ description: Help string shown in ``/metrics`` output. Only used
133
+ on first registration; later values are ignored.
134
+ """
135
+ self._update(name, value, labels, description, kind="gauge")
136
+
137
+ def update_counter(self, name: str, value: float, labels: dict[str, str] | None = None, description: str = "") -> None:
138
+ """Create or update a Counter metric sample.
139
+
140
+ Use for values that only ever increase (e.g. cumulative byte counts read
141
+ from the router). Pass *name* without the ``_total`` suffix; it is added
142
+ automatically in the ``/metrics`` output.
143
+
144
+ Args:
145
+ name: Prometheus metric name (e.g. ``internetbox_wan_rx_bytes``).
146
+ value: Current cumulative value.
147
+ labels: Optional label name → value mapping.
148
+ description: Help string shown in ``/metrics`` output.
149
+ """
150
+ self._update(name, value, labels, description, kind="counter")
151
+
152
+ def _update(self, name: str, value: float, labels: dict[str, str] | None, description: str, kind: str) -> None:
153
+ merged = {**self.default_labels, **(labels or {})}
154
+ label_names = sorted(merged.keys()) if merged else []
155
+ with self._lock:
156
+ if name not in self._gauges:
157
+ self._gauges[name] = _GaugeMetric(name, description, label_names, kind=kind, owner=self._current_callback)
158
+ self._gauges[name].set(value, merged, cycle=self._cycle)
159
+
160
+ # ── Prometheus Collector protocol ────────────────────────────────
161
+
162
+ def describe(self) -> list: # type: ignore[override]
163
+ # Returning an empty list tells the registry not to validate metric
164
+ # names ahead of time, which avoids issues when metrics are registered
165
+ # dynamically after the collector is added to the registry.
166
+ return []
167
+
168
+ def collect(self): # type: ignore[override]
169
+ """Yield current :class:`GaugeMetricFamily` objects for every metric."""
170
+ with self._lock:
171
+ families = [gauge.to_prometheus() for gauge in self._gauges.values()]
172
+ yield from families
173
+
174
+ # ── Background collection loop ───────────────────────────────────
175
+
176
+ def _run_callbacks(self) -> None:
177
+ """Invoke all registered callbacks, logging (not raising) errors.
178
+
179
+ After a callback succeeds, samples it did not report this cycle are
180
+ removed. If a callback fails, its previous samples are kept.
181
+ """
182
+ with self._lock:
183
+ self._cycle += 1
184
+ for cb in self._callbacks:
185
+ self._current_callback = cb
186
+ try:
187
+ cb(self)
188
+ with self._lock:
189
+ for gauge in self._gauges.values():
190
+ if gauge.owner is cb:
191
+ gauge.prune(self._cycle)
192
+ except Exception: # noqa: BLE001
193
+ logger.exception("Error in collection callback %r — will retry next cycle.", cb.__name__ if hasattr(cb, "__name__") else cb)
194
+ # If the session was invalidated (HTTP 401), reset the context
195
+ # so the next cycle triggers automatic re-authentication.
196
+ try:
197
+ self._client._sm.context_id = None # type: ignore[attr-defined]
198
+ except AttributeError:
199
+ pass
200
+ finally:
201
+ self._current_callback = None
202
+
203
+ def _run(self) -> None:
204
+ """Background thread: collect immediately, then repeat every interval."""
205
+ self._run_callbacks()
206
+ while not self._stop_event.wait(self._interval):
207
+ self._run_callbacks()
208
+
209
+ def start(self) -> None:
210
+ """Start the background collection thread.
211
+
212
+ Call after all callbacks are registered so the first cycle runs
213
+ with the complete set.
214
+ """
215
+ self._thread.start()
216
+
217
+ def stop(self) -> None:
218
+ """Signal the background thread to stop and wait for it to exit."""
219
+ self._stop_event.set()
220
+ self._thread.join(timeout=max(self._interval, 10))