From 127def18b337a5b12986a9414426e3d5d3ca0965 Mon Sep 17 00:00:00 2001 From: Dirk Heilig Date: Mon, 9 Sep 2024 19:03:43 +0200 Subject: [PATCH] add validity time parameter --- Readme.md | 1 + mqtt2prom/run | 21 +++++++++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e062ddb..ba71d6e 100644 --- a/Readme.md +++ b/Readme.md @@ -24,6 +24,7 @@ The payload needs to be an object containing only the following keys: - `name` (string): the name of the metric - `value` (number): the value of the metric - `labels` (object, optional): an object containing the labels for the metric (key-value pairs of strings) +- `valid_seconds` (number, optional, defaults to 60): the number of seconds the metric is valid. After this time, the metric will be removed from the export. (which will results in a gap in prometheus) According to prometheus conventions, the metric name and the label names need to be a lower or upper case letter or a underscore followed by all case leters, numbers or underscores. diff --git a/mqtt2prom/run b/mqtt2prom/run index d817853..09b6738 100755 --- a/mqtt2prom/run +++ b/mqtt2prom/run @@ -173,8 +173,25 @@ function precheck(Message $message): bool return false; } } + + if(!isset($payload["valid_seconds"])){ + $payload["valid_seconds"] = 60; + } + if(!is_numeric($payload["valid_seconds"])){ + error("valid_seconds must be a number"); + return false; + } + if($payload["valid_seconds"] < 1){ + error("valid_seconds must be at least 1"); + return false; + } + if($payload["valid_seconds"] >60*60*48){ + error("valid_seconds must be at most 48 hours"); + return false; + } + foreach (array_keys($payload) as $key) { - if (!in_array($key, ["name", "value", "labels"])) { + if (!in_array($key, ["name", "value", "labels","valid_until"])) { error("Unknown key: $key"); return false; } @@ -307,7 +324,7 @@ function filter(): void { global $data, $stats; $data = array_filter($data, function ($entry) { - return $entry["timestamp"] > time() - 60; + return $entry["timestamp"] > time() - $entry["valid_seconds"]; }); // remove stats older than 24h foreach ($stats as $key => $values) {