Source code for fleetmesh_node.metrics.adapters

"""Rendering readings for whoever is asking.

An adapter turns `Monitors.read()` into one wire format. They are separate
from the registry for the reason the log's backends are separate from the
channels: what a compartment measures is not a decision about who scrapes it,
and a second consumer must not mean a second set of declarations.

    prometheus   the text exposition format, which is also OpenMetrics-
                 compatible enough for a Prometheus server to scrape
    json         the same readings as data, for the control socket and the
                 health block

`relayserver` already accepts a `metrics_provider` callable and nothing ever
passed one, so `provider(monitors)` is the function to hand it. The relay
face's hand-written exposition then becomes the fallback it already is rather
than the only path.
"""
from __future__ import annotations

from typing import Callable, Mapping, Sequence, TypedDict

from . import HISTOGRAM, Monitors, Reading, RegistryState


[docs]class Exposition(TypedDict): """The readings as data: what the control socket and the health block get. A named record for the reason check-dicts.py enforces it - this is a row an operator reads by field name. """ metrics: list[Reading] registry: RegistryState
def _escape(v: str) -> str: """A label value, escaped as the exposition format requires. Backslash first, or the escapes introduced after it get escaped again. """ return v.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') def _labels(labels: Mapping[str, str], extra: Sequence[tuple[str, str]] = ()) -> str: items = [(k, str(v)) for k, v in labels.items() if v != ''] + list(extra) if not items: return '' return '{%s}' % ','.join('%s="%s"' % (k, _escape(v)) for k, v in items)
[docs]def prometheus(monitors: Monitors) -> str: """The text exposition format. HELP and TYPE are emitted once per metric name and before its samples, which the format requires: a repeated TYPE line makes a scrape fail, and a scrape that fails is monitoring that is absent rather than wrong. """ readings = monitors.read() by_name: dict[str, list[Reading]] = {} for r in readings: by_name.setdefault(r['exposed'], []).append(r) out: list[str] = [] for exposed, rows in by_name.items(): m = monitors.metrics.get(exposed) if m is None: continue help_text = m.description.replace('\\', '\\\\').replace('\n', ' ') out.append('# HELP %s %s' % (exposed, help_text)) out.append('# TYPE %s %s' % (exposed, m.kind)) for r in rows: if m.kind == HISTOGRAM: for le, n in (r.get('buckets') or {}).items(): out.append('%s_bucket%s %d' % ( exposed, _labels(r.get('labels', {}), [('le', le)]), n)) out.append('%s_sum%s %g' % (exposed, _labels(r.get('labels', {})), r.get('sum', 0.0))) out.append('%s_count%s %d' % (exposed, _labels(r.get('labels', {})), r.get('count', 0))) else: out.append('%s%s %g' % (exposed, _labels(r.get('labels', {})), r.get('value', 0.0))) return '\n'.join(out) + ('\n' if out else '')
[docs]def json_readings(monitors: Monitors) -> 'Exposition': """The readings as data, for the control socket and the health block. The same readings the exposition is built from, so a dashboard reading the socket and a Prometheus server scraping the face cannot see different numbers - which is the failure the log had before Channel. """ return {'metrics': monitors.read(), 'registry': monitors.state()}
[docs]def provider(monitors: Monitors) -> Callable[[], str]: """The callable `relayserver(metrics_provider=...)` has always wanted.""" def render() -> str: return prometheus(monitors) return render
__all__ = ['prometheus', 'json_readings', 'provider', 'Exposition']