|
| 1 | +<?php |
| 2 | +# php -S 127.0.0.1:8080 lrpm-prometheus-metrics.php |
| 3 | + |
| 4 | +$program = __DIR__ . '/bin/lrpmctl'; |
| 5 | +$request = 'jsonstatus'; |
| 6 | +$json = shell_exec("$program $request"); |
| 7 | +$status = json_decode($json, true); |
| 8 | +$output = lrpm_status_to_prometheus_metrics($status); |
| 9 | +echo($output); |
| 10 | + |
| 11 | +function lrpm_status_to_prometheus_metrics(array $status): string |
| 12 | +{ |
| 13 | + $taskCount = count($status); |
| 14 | + $activeTaskCount = get_number_of_active_tasks($status); |
| 15 | + $inactiveTaskCount = $taskCount - $activeTaskCount; |
| 16 | + $output = "lrpm_task_count $taskCount" . PHP_EOL; |
| 17 | + $output .= "lrpm_inactive_task_count $inactiveTaskCount" . PHP_EOL; |
| 18 | + |
| 19 | + foreach ($status as $jobId => $jobStatus) { |
| 20 | + $config = $jobStatus['config']; |
| 21 | + $state = $jobStatus['state']; |
| 22 | + $name = $config['name']; |
| 23 | + $workerClass = $config['workerClass']; |
| 24 | + $mtime = $config['mtime']; |
| 25 | + if (isset($state['restartAt']) && $state['restartAt'] > $state['startedAt']) { |
| 26 | + $backoffDuration = $state['restartAt'] - $state['startedAt']; |
| 27 | + $metric = serialize_prometheus_metric('lrpm_task_backoff', ['id' => $jobId, 'name' => $name], $backoffDuration); |
| 28 | + $output .= $metric . PHP_EOL; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return $output; |
| 33 | +} |
| 34 | + |
| 35 | +function get_number_of_active_tasks(array $status) |
| 36 | +{ |
| 37 | + $active_tasks = array_filter($status, function ($task) { |
| 38 | + return isset($task['state']['pid']) && is_int($task['state']['pid']); |
| 39 | + }); |
| 40 | + return count($active_tasks); |
| 41 | +} |
| 42 | + |
| 43 | +function serialize_prometheus_metric(string $name, array $labels, $value, $timestamp = null): string |
| 44 | +{ |
| 45 | + $output = $name; |
| 46 | + if (!empty($labels)) { |
| 47 | + $output .= '{'; |
| 48 | + $sep = ''; |
| 49 | + foreach ($labels as $labelName => $labelValue) { |
| 50 | + $output .= $sep . $labelName . '=' . $labelValue; |
| 51 | + $sep = ','; |
| 52 | + } |
| 53 | + $output .= '}'; |
| 54 | + } |
| 55 | + $output .= ' ' . $value; |
| 56 | + if (isset($timestamp)) $output .= ' ' . $timestamp; |
| 57 | + return $output; |
| 58 | +} |
0 commit comments