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) {