custom-prometheus-exporter/index.php
Jeroen De Meerleer 41f2ddea37
Reorder conditional for CLI check, then URI comparison.
- Reordered the condition to first check for CLI mode before URI comparison.
2024-06-03 23:41:42 +02:00

71 lines
2.3 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 => &$c) {
if(isset($c['command'])) {
$output=null;
$retval=null;
exec($c['command'], $output, $retval);
$output = implode("\n", $output);
} elseif(isset($c['http'])) {
$client = new GuzzleHttp\Client();
$options = [];
$output = NULL;
if (isset($c['http']['proxy'])) {
$options['proxy'] = $c['http']['proxy'];
}
if (isset($c['http']['data']) && $c['http']['data'] == 'responsetime') {
$options['on_stats'] = function (GuzzleHttp\TransferStats $stats) use (&$output) {
$output = $stats->getTransferTime();
};
}
$hasresponse = NULL;
try{
$res = $client->request('GET', $c['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($c['http']['data']) && $c['http']['data'] == 'responsebody') {
$output = $res->getBody()->getContents();
} elseif (isset($c['http']['data']) && $c['http']['data'] == 'hasresponse') {
$output = (int)$hasresponse;
}
}
if(isset($c['jsonelem'])) {
$c['value'] = getArrayValue($c['jsonelem'], json_decode($output, true));
} else {
$c['value'] = $output;
}
if(is_bool($c['value'])) $c['value'] = $c['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;
}