Files
webgui/plugins/dynamix/scripts/wg_poller
2021-05-08 00:05:05 +02:00

52 lines
1.8 KiB
PHP
Executable File

#!/usr/bin/php -q
<?PHP
/* Copyright 2005-2021, Lime Technology
* Copyright 2012-2021, Bergware International.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
?>
<?
function curl_socket($socket, $url, $postdata = NULL) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_UNIX_SOCKET_PATH, $socket);
if ($postdata !== NULL) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
}
function publish($endpoint, $message) {
curl_socket("/var/run/nginx.socket", "http://localhost/pub/$endpoint?buffer_length=1", $message);
}
function my_scale($value, &$unit) {
$units = [' ','Ki','Mi','Gi','Ti','Pi','Ei','Zi','Yi'];
$size = count($units);
$base = $value ? floor(log($value, 1024)) : 0;
if ($base>$size) $base = $size-1;
$value /= pow(1024, $base);
$decimals = $value>=100 ? 0 : ($value>=10 ? 1 : (round($value*100)%100===0 ? 0 : 2));
if (round($value,-1)==1000) {$value = 1; $base++;}
$unit = $units[$base].'B';
return number_format($value, $decimals, '.', $value>9999 ? ',':'');
}
while (true) {
$now = time(); $i = 0;
unset($dump); $vtun = [];
exec('wg show all dump',$dump);
foreach ($dump as $row) {
$row = preg_split('/\s+/',$row);
if (count($row)>5) $vtun[] = $row[0].';'.($row[5] ? $now - $row[5] : 0).';'.my_scale($row[6],$unit)." $unit;".my_scale($row[7],$unit)." $unit";
}
publish('wireguard', implode("\0",$vtun));
sleep(1);
}
?>