Files

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

70 lines
2.0 KiB
PHP
Raw Permalink Normal View History

2021-03-07 20:26:44 +01:00
<?php
use LibreNMS\Exceptions\JsonAppException;
use LibreNMS\Exceptions\JsonAppMissingKeysException;
use LibreNMS\RRD\RrdDefinition;
$name = 'docker';
$output = 'OK';
function convertToBytes(string $from): ?int
{
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
$number = substr($from, 0, -3);
$suffix = substr($from, -3);
//B or no suffix
if (is_numeric(substr($suffix, 0, 1))) {
return (int) $from;
}
$exponent = array_flip($units)[$suffix] ?? null;
if ($exponent === null) {
return null;
}
2021-05-25 08:30:50 -05:00
return (int) ($number * (1024 ** $exponent));
2021-03-07 20:26:44 +01:00
}
try {
$docker_data = json_app_get($device, $name, 1)['data'];
} catch (JsonAppMissingKeysException $e) {
$docker_data = $e->getParsedJson();
} catch (JsonAppException $e) {
echo PHP_EOL . $name . ':' . $e->getCode() . ':' . $e->getMessage() . PHP_EOL;
update_application($app, $e->getCode() . ':' . $e->getMessage(), []); // Set empty metrics and error message
return;
}
$rrd_name = ['app', $name, $app->app_id];
2021-03-07 20:26:44 +01:00
$rrd_def = RrdDefinition::make()
->addDataset('cpu_usage', 'GAUGE', 0, 100)
->addDataset('pids', 'GAUGE', 0)
->addDataset('mem_perc', 'GAUGE', 0, 100)
->addDataset('mem_used', 'GAUGE', 0)
->addDataset('mem_limit', 'GAUGE', 0);
$metrics = [];
$containerNames = [];
2021-03-07 20:26:44 +01:00
foreach ($docker_data as $data) {
$containerNames[] = $container = $data['container'];
2021-03-07 20:26:44 +01:00
$rrd_name = ['app', $name, $app->app_id, $container];
2021-03-07 20:26:44 +01:00
$fields = [
2021-03-12 18:10:14 -06:00
'cpu_usage' => (float) $data['cpu'],
2021-03-07 20:26:44 +01:00
'pids' => $data['pids'],
2021-03-12 18:10:14 -06:00
'mem_perc' => (float) $data['memory']['perc'],
2022-07-15 16:12:20 +02:00
'mem_used' => convertToBytes($data['memory']['used']),
'mem_limit' => convertToBytes($data['memory']['limit']),
2021-03-07 20:26:44 +01:00
];
$metrics[$container] = $fields;
$tags = ['name' => $container, 'app_id' => $app->app_id, 'rrd_def' => $rrd_def, 'rrd_name' => $rrd_name];
2021-03-07 20:26:44 +01:00
data_update($device, 'app', $tags, $fields);
}
$app->data = ['containers' => $containerNames];
2021-03-07 20:26:44 +01:00
update_application($app, $output, $metrics);