Repository navigation
Add optional Prometheus metrics for client operations - #901
Conversation
gijzelaerr
left a comment
There was a problem hiding this comment.
Thanks for following up on #843 so quickly — having operation metrics available from the client is useful, and it fits alongside the existing OperationLogger, rate limiter and connection callbacks. Tests, mypy and pre-commit all pass locally. A few things I'd like to see changed before merging:
1. Avoid re-indenting read_area / write_area. Wrapping the whole body in with self._instrumented(...) shifts ~100 lines, which makes the diff hard to review, pollutes git blame, and will conflict with every future change to these methods. A decorator (e.g. @_instrumented("read_area")) gives the same behaviour without touching the body.
2. Keep the HTTP server out of the library. I'd rather not ship a hand-rolled HTTP server in a PLC communication library. Preferably the client exposes a small generic hook — something like on_operation(name: str, seconds: float, error: bool) — so users can feed prometheus_client, OpenTelemetry or anything else. MetricsRegistry + MetricsServer would then make a nice example/ script rather than part of the package API.
3. If a server stays anywhere, don't bind 0.0.0.0 by default. In OT networks this publishes PLC addresses on every interface; 127.0.0.1 is the safer default.
4. Duration metric type. snap7_operation_duration_seconds_sum is declared as a standalone counter. The Prometheus convention is a summary (or histogram) named snap7_operation_duration_seconds exposing _sum and _count.
5. Connected gauge keying. The gauge is keyed only by host, so two clients to the same PLC (different rack/slot/port) overwrite each other. Also, calling disconnect() on a client that never connected emits snap7_client_connected{plc=""} 0:
r = MetricsRegistry(); Client(metrics=r).disconnect()
# -> snap7_client_connected{plc=""} 06. Async parity and coverage. We keep Client and AsyncClient at parity, so AsyncClient should accept the same option. Multi-var reads/writes and block upload/download are currently not instrumented either.
7. Please add a short docs section and a CHANGES.md entry under "Unreleased".
Happy to look again once it's slimmed down — the hook-based approach in (1)+(2) would also make most of (3)–(5) go away.
81d7483 to
6d81fb9
Compare
|
Reworked along these lines:
|
gijzelaerr
left a comment
There was a problem hiding this comment.
Thanks, this is much better. The hook API is what I had in mind, and client.py barely changes now. A few things are left, mostly small:
1. Python 3.14 deprecation. asyncio.iscoroutinefunction is deprecated in 3.14 (removal in 3.16), and _instrumented calls it while the module is imported. So on 3.14 every import snap7 emits a DeprecationWarning. Please use inspect.iscoroutinefunction instead.
2. Nested calls are counted twice. AsyncClient.read_multi_vars / write_multi_vars loop over self.read_area / self.write_area, and the sync read_multi_vars does the same on its dict-items path. One multi-var read of 5 items then reports one read_multi_vars plus five read_area operations, and the time is counted twice in the totals. The sync and async clients also report differently for the same call. The simplest fix is to report only the outermost operation, e.g. a per-client depth counter (or a ContextVar for async) that skips reporting while an instrumented call is already in progress. A test for it would be good.
3. Duplication in the decorator. The sync and async wrappers repeat the timing and callback logic. Moving the try: self._on_operation(...) except: logger.debug(...) part into one small helper (e.g. _report_operation(self, operation, started, error)) would leave only the await as the difference.
4. Rebase. CHANGES.md conflicts with master, which already has an Unreleased section. Please add your entry there instead of a second heading.
5. PR description. It still describes snap7/metrics.py, metrics=, and tests/test_metrics.py. Please update it to the hook design, since it ends up in the squash commit.
After that I think this is ready to merge.
6d81fb9 to
9b95404
Compare
|
Thanks, all addressed:
Added two tests ( |
gijzelaerr
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround — all points addressed, and the depth tracking with tests for both clients is exactly what I had in mind. Merging.
Adds an
on_operationcallback to the synchronous and asynchronous clients, following up on #843: invoked after each PLC operation with its name, duration, and whether it raised — same shape as the existingon_disconnect/on_reconnectcallbacks.Instrumentation sits in
read_area/write_area/read_multi_vars/write_multi_vars/upload/downloadvia a decorator inclient_base.py(shared byClientandAsyncClient), so these methods keep their original body. A nested instrumented call runs normally but isn't reported on its own, so one logical operation isn't counted and timed twice.example/prometheus_metrics.pyshows building a Prometheus registry andGET /metricsHTTP server on top of this hook plus the existingon_disconnect/on_reconnectcallbacks — separate from the exporter described in #623.14 tests in
tests/test_operation_hook.py. Full suite passes; ruff (check + format), mypy, and the Sphinx build (-W) are clean.