Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,10 @@ ttl = 86400
# When true, the robot's id, its signature and its request headers are sent to Roborock, along with this server's IP.
[matter]
key_proxy = false

# [metrics]
# Optional Prometheus exposition on GET /metrics (disabled by default).
# When enabled, scrapers must send Authorization: Bearer <token>.
# enabled = false
# bearer_token = "replace-with-a-long-random-token"
# bearer_token_file = "/run/secrets/metrics_token"
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ If you want to support this project, next time you buy a Roborock, use one of my
- [Mobile App Options](roborock_app.md)
- [Updating](updating.md)
- [Tested vacuums](tested_vacuums.md)
- [Prometheus metrics](metrics.md)
- [Reverse proxy](reverse_proxy.md)
- [Custom MQTT](custom_mqtt.md)
- [Custom certificate management](custom_cert_management.md)
Expand Down
70 changes: 70 additions & 0 deletions docs/metrics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Prometheus Metrics

The stack can expose an opt-in `GET /metrics` endpoint in Prometheus text format on the same HTTPS listener as the Roborock protocol (`network.https_port`). It is **disabled by default**.

## When to use it

Use this when you want alerts such as “vacuum X has not sent MQTT traffic for 15 minutes” without putting the admin password into your monitoring stack or scraping JSON endpoints that include secrets (`local_key`, session material).

The route works with `--core-only` (standalone admin routes are not required).

## Configuration

```toml
[metrics]
enabled = true
bearer_token_file = "/run/secrets/metrics_token"
```

Or set `bearer_token` inline. If both are set, the inline value wins. `load_config` requires a token when `enabled = true`.

Scrapers must send:

```http
Authorization: Bearer <your-token>
```

### Prometheus scrape example

```yaml
scrape_configs:
- job_name: roborock-local-server
scheme: https
tls_config:
insecure_skip_verify: false
authorization:
type: Bearer
credentials: your-metrics-token
metrics_path: /metrics
static_configs:
- targets: ["api-roborock.example.com:555"]
```

Behind a reverse proxy on port 443, point at the public hostname/port; the server still listens on `https_port` internally.

## Metrics overview

Device identity (`duid`, `did`, `name`, `model`) is exported. **Never** exported: `local_key`, protocol auth data, client IPs, or MQTT payload previews.

| Metric | Notes |
|--------|--------|
| `roborock_device_connected{duid}` | MQTT session flag, or recent MQTT within 180s |
| `roborock_device_last_mqtt_timestamp_seconds{duid}` | Omitted until first MQTT message |
| `roborock_service_up{service}` | Supervisor `running` flags for enabled services |
| `roborock_tls_certificate_expiry_timestamp_seconds` | Only when `listener_mode = "local_tls"` |

## Suggested alert

Silence-based MQTT alert (more reliable than `connected` immediately after restart):

```promql
time() - roborock_device_last_mqtt_timestamp_seconds{duid="your-inventory-duid"} > 900
```

Vacuums that never sent MQTT have no `last_mqtt` series; use `roborock_device_info` or `absent()` for those cases.

## Limitations

- `roborock_device_last_mqtt_disconnect_timestamp_seconds` is not persisted across server restarts.
- With `listener_mode = "external_tls"`, the TLS certificate expiry metric is omitted (the proxy holds the certificate).
- `roborock_service_up{service="https_server"}` is 1 on any successful scrape, because the HTTP listener responded.
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ nav:
- Matter: matter.md
- Reference:
- Log Retention: logging.md
- Prometheus Metrics: metrics.md
- Last-Known State: last_known_state.md
- Known Limitations: known_limitations.md
- Schedule Support (Experimental): schedules.md
Expand Down
9 changes: 9 additions & 0 deletions src/roborock_local_server/certs.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ class CertificatePaths:
_FilesSignature = tuple[tuple[int, int, int], tuple[int, int, int]]


def certificate_expiry_unix_seconds(cert_file: Path) -> float | None:
"""Return not_valid_after_utc as a Unix timestamp, or None if the file cannot be parsed."""
try:
cert = x509.load_pem_x509_certificate(cert_file.read_bytes())
except Exception:
return None
return cert.not_valid_after_utc.timestamp()


def validate_certificate_pair(cert_file: Path, key_file: Path) -> None:
"""Raise if the key does not belong to the certificate or either file cannot be parsed."""
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
Expand Down
28 changes: 28 additions & 0 deletions src/roborock_local_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,15 @@ class MatterConfig:
key_proxy: bool = False


@dataclass(frozen=True)
class MetricsConfig:
"""Optional Prometheus text exposition on GET /metrics."""

enabled: bool = False
bearer_token: str = ""
bearer_token_file: str = ""


@dataclass(frozen=True)
class AppConfig:
network: NetworkConfig
Expand All @@ -122,6 +131,7 @@ class AppConfig:
turn: TurnConfig = TurnConfig()
logging: LoggingConfig = LoggingConfig()
matter: MatterConfig = MatterConfig()
metrics: MetricsConfig = MetricsConfig()


@dataclass(frozen=True)
Expand All @@ -142,6 +152,7 @@ class AppPaths:
cloudflare_token_file: Path
acme_eab_kid_file: Path
acme_eab_hmac_key_file: Path
metrics_bearer_token_file: Path
cert_file: Path
key_file: Path

Expand Down Expand Up @@ -280,6 +291,7 @@ def load_config(path: str | Path) -> AppConfig:
admin = _get_section(parsed, "admin")
turn = _get_section(parsed, "turn")
matter = _get_section(parsed, "matter")
metrics = _get_section(parsed, "metrics")
turn_mode = str(turn.get("mode", "external" if _as_bool(turn.get("enabled"), False) else "disabled")).strip().lower()
broker_mode = str(broker.get("mode", "embedded")).strip().lower()
if broker_mode not in {"embedded", "external"}:
Expand Down Expand Up @@ -389,8 +401,20 @@ def load_config(path: str | Path) -> AppConfig:
realm=str(turn.get("realm", "") or turn.get("host", "")).strip(),
ttl=_as_int(turn.get("ttl"), "turn.ttl", 86400),
),
metrics=MetricsConfig(
enabled=_as_bool(metrics.get("enabled"), False),
bearer_token=str(metrics.get("bearer_token", "")).strip(),
bearer_token_file=str(metrics.get("bearer_token_file", "")).strip(),
),
)

if config.metrics.enabled and not (
config.metrics.bearer_token or config.metrics.bearer_token_file
):
raise ValueError(
"metrics.enabled requires metrics.bearer_token or metrics.bearer_token_file"
)

if len(config.admin.session_secret) < 24:
raise ValueError("admin.session_secret must be at least 24 characters")
if "@" not in config.admin.protocol_login_email:
Expand Down Expand Up @@ -474,6 +498,9 @@ def resolve_paths(config_file: str | Path, config: AppConfig) -> AppPaths:
acme_eab_hmac_key_file = Path(config.tls.acme_eab_hmac_key_file or state_dir / "acme_eab_hmac_key")
if not acme_eab_hmac_key_file.is_absolute():
acme_eab_hmac_key_file = (config_root / acme_eab_hmac_key_file).resolve()
metrics_bearer_token_file = Path(config.metrics.bearer_token_file or state_dir / "metrics_token")
if not metrics_bearer_token_file.is_absolute():
metrics_bearer_token_file = (config_root / metrics_bearer_token_file).resolve()

return AppPaths(
config_file=config_path,
Expand All @@ -492,6 +519,7 @@ def resolve_paths(config_file: str | Path, config: AppConfig) -> AppPaths:
cloudflare_token_file=cloudflare_token_file,
acme_eab_kid_file=acme_eab_kid_file,
acme_eab_hmac_key_file=acme_eab_hmac_key_file,
metrics_bearer_token_file=metrics_bearer_token_file,
cert_file=cert_file,
key_file=key_file,
)
170 changes: 170 additions & 0 deletions src/roborock_local_server/metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""Prometheus text exposition for stack health and device state."""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime, timezone
import secrets


def _iso_to_unix(value: str | None) -> float | None:
if not isinstance(value, str) or not value.strip():
return None
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
return parsed.astimezone(timezone.utc).timestamp()


def _escape_label(value: str) -> str:
escaped: list[str] = []
for character in str(value or ""):
if character == "\\":
escaped.append("\\\\")
elif character == '"':
escaped.append('\\"')
elif character == "\n":
escaped.append("\\n")
else:
escaped.append(character)
return "".join(escaped)


def _label_set(labels: dict[str, str]) -> str:
if not labels:
return ""
parts = [f'{key}="{_escape_label(val)}"' for key, val in sorted(labels.items())]
return "{" + ",".join(parts) + "}"


def parse_authorization_bearer(header_value: str | None) -> str | None:
raw = str(header_value or "").strip()
if not raw:
return None
parts = raw.split(None, 1)
if len(parts) != 2 or parts[0].lower() != "bearer":
return None
token = parts[1].strip()
return token or None


def bearer_token_valid(provided: str | None, expected: str) -> bool:
expected_clean = str(expected or "").strip()
if not expected_clean:
return False
if provided is None:
return False
provided_clean = provided.strip()
return secrets.compare_digest(
provided_clean.encode("utf-8"),
expected_clean.encode("utf-8"),
)


@dataclass(frozen=True)
class MetricsDeviceRow:
duid: str
did: str
name: str
model: str
connected: bool
public_key_ready: bool
last_mqtt_at: str = ""
last_disconnect_at: str = ""
last_http_at: str = ""


@dataclass
class MetricsSnapshot:
version: str
services: list[dict[str, object]] = field(default_factory=list)
active_mqtt_connections: int = 0
new_connections_enabled: bool = True
protocol_auth_enabled: bool = True
devices_pending_mqtt_recovery: int = 0
tls_certificate_expiry_timestamp_seconds: float | None = None
devices: list[MetricsDeviceRow] = field(default_factory=list)


def _line(metric: str, value: int | float, labels: dict[str, str] | None = None) -> str:
suffix = _label_set(labels or {})
if isinstance(value, float) and value.is_integer():
value = int(value)
return f"{metric}{suffix} {value}"


def render_prometheus(snap: MetricsSnapshot) -> str:
lines: list[str] = []

def add_family(help_text: str, metric_type: str, metric_name: str) -> None:
lines.append(f"# HELP {metric_name} {help_text}")
lines.append(f"# TYPE {metric_name} {metric_type}")

add_family("Build version", "gauge", "roborock_build_info")
lines.append(_line("roborock_build_info", 1, {"version": snap.version}))

add_family("Whether a stack service is running (enabled services only)", "gauge", "roborock_service_up")
for service in snap.services:
if not service.get("enabled"):
continue
name = str(service.get("name") or "").strip()
if not name:
continue
running = 1 if service.get("running") else 0
lines.append(_line("roborock_service_up", running, {"service": name}))

add_family("Active MQTT TLS proxy connections", "gauge", "roborock_mqtt_active_connections")
lines.append(_line("roborock_mqtt_active_connections", snap.active_mqtt_connections))

add_family("Whether new vacuum connections are allowed", "gauge", "roborock_new_connections_enabled")
lines.append(_line("roborock_new_connections_enabled", 1 if snap.new_connections_enabled else 0))

add_family("Whether protocol login auth is required", "gauge", "roborock_protocol_auth_enabled")
lines.append(_line("roborock_protocol_auth_enabled", 1 if snap.protocol_auth_enabled else 0))

add_family("Devices with known MQTT username but no stored password", "gauge", "roborock_devices_pending_mqtt_recovery")
lines.append(_line("roborock_devices_pending_mqtt_recovery", snap.devices_pending_mqtt_recovery))

if snap.tls_certificate_expiry_timestamp_seconds is not None:
add_family("TLS certificate notAfter (local TLS listener only)", "gauge", "roborock_tls_certificate_expiry_timestamp_seconds")
lines.append(
_line(
"roborock_tls_certificate_expiry_timestamp_seconds",
snap.tls_certificate_expiry_timestamp_seconds,
)
)

add_family("Device identity labels", "gauge", "roborock_device_info")
add_family("MQTT session or recent MQTT activity", "gauge", "roborock_device_connected")
add_family("Last MQTT message time", "gauge", "roborock_device_last_mqtt_timestamp_seconds")
add_family("Last MQTT disconnect time", "gauge", "roborock_device_last_mqtt_disconnect_timestamp_seconds")
add_family("Last HTTP request time", "gauge", "roborock_device_last_http_timestamp_seconds")
add_family("Onboarding public key ready", "gauge", "roborock_device_public_key_ready")

for device in snap.devices:
duid = str(device.duid or "").strip()
if not duid:
continue
duid_label = {"duid": duid}
info_labels = {
"duid": duid,
"did": str(device.did or "").strip(),
"name": str(device.name or "").strip(),
"model": str(device.model or "").strip(),
}
lines.append(_line("roborock_device_info", 1, info_labels))
lines.append(_line("roborock_device_connected", 1 if device.connected else 0, duid_label))
lines.append(_line("roborock_device_public_key_ready", 1 if device.public_key_ready else 0, duid_label))

last_mqtt = _iso_to_unix(device.last_mqtt_at)
if last_mqtt is not None:
lines.append(_line("roborock_device_last_mqtt_timestamp_seconds", last_mqtt, duid_label))
last_disconnect = _iso_to_unix(device.last_disconnect_at)
if last_disconnect is not None:
lines.append(_line("roborock_device_last_mqtt_disconnect_timestamp_seconds", last_disconnect, duid_label))
last_http = _iso_to_unix(device.last_http_at)
if last_http is not None:
lines.append(_line("roborock_device_last_http_timestamp_seconds", last_http, duid_label))

return "\n".join(lines) + "\n"
Loading