custom-prometheus-exporter/index.php
Jeroen De Meerleer fd8a67c23c
Refactor conditional logic for response handling
- Adjusted code to handle different scenarios when processing responses.
2024-06-04 13:22:16 +02:00

91 lines
3.5 KiB
PHP

<?php
require 'vendor/autoload.php';
require 'config.php';
if(php_sapi_name() == 'cli' || $_SERVER["REQUEST_URI"] == '/metrics') {
header('Content-Type: text/plain; version=0.0.4');
foreach ($config as $key => &$metric) {
if (!isset($metric['submetrics'])) {
$metric['submetrics'] = [$metric];
}
foreach ($metric['submetrics'] as $key => &$submetric) {
if (isset($submetric['command'])) {
$output = null;
$retval = null;
try {
exec($submetric['command'], $output, $retval);
$output = implode("\n", $output);
} catch (Exception $e) {
$output = '';
}
} elseif (isset($submetric['http'])) {
$client = new GuzzleHttp\Client();
$options = [];
$output = NULL;
if (isset($submetric['http']['proxy'])) {
$options['proxy'] = $submetric['http']['proxy'];
}
if (isset($submetric['http']['data']) && $submetric['http']['data'] == 'responsetime') {
$options['on_stats'] = function (GuzzleHttp\TransferStats $stats) use (&$output) {
$output = $stats->getTransferTime();
};
}
$hasresponse = NULL;
try {
$res = $client->request('GET', $submetric['http']['url'], $options);
$hasresponse = true;
} catch (GuzzleHttp\Exception\GuzzleException $e) {
if (method_exists($e, 'getResponse')) {
$res = $e->getResponse();
$hasresponse = true;
} else {
$hasresponse = false;
}
}
if (isset($submetric['http']['data']) && $submetric['http']['data'] == 'responsebody') {
if ($hasresponse) {
$output = $res->getBody()->getContents();
} else {
$output = '';
}
} elseif ((isset($submetric['http']['statuscode'])) && (isset($submetric['http']['data']) && $submetric['http']['data'] == 'hasresponse')) {
if ($hasresponse) {
$output = $output = (int)in_array($res->getStatusCode(), $submetric['http']['statuscode']);;
} else {
$output = 0;
}
} elseif (isset($submetric['http']['data']) && $submetric['http']['data'] == 'hasresponse') {
$output = (int)$hasresponse;
}
}
if (isset($submetric['jsonelem'])) {
$submetric['value'] = getArrayValue($submetric['jsonelem'], json_decode($output, true));
} else {
$submetric['value'] = $output;
}
if (is_bool($submetric['value'])) $submetric['value'] = $submetric['value'] ? 1 : 0;
}
}
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [
'cache' => 'twig_cache',
]);
echo $twig->render('metrics.twig', ['config' => $config]);
}
function getArrayValue($elem, $array) {
$elem = explode('.', $elem);
$new_array = $array;
foreach ($elem as $i) {
$new_array = $new_array[$i];
}
return $new_array;
}