2015-06-18 22:20:50 +01:00
< ? php
2011-04-13 14:00:12 +00:00
2020-04-17 17:37:56 -05:00
use Illuminate\Support\Str ;
2023-08-05 12:12:36 -05:00
use LibreNMS\Enum\Severity ;
2022-10-21 10:05:49 -05:00
use LibreNMS\Exceptions\JsonAppBase64DecodeException ;
2018-05-25 21:16:16 -05:00
use LibreNMS\Exceptions\JsonAppBlankJsonException ;
2020-05-30 17:42:50 -05:00
use LibreNMS\Exceptions\JsonAppExtendErroredException ;
2022-10-21 10:05:49 -05:00
use LibreNMS\Exceptions\JsonAppGzipDecodeException ;
2018-05-25 21:16:16 -05:00
use LibreNMS\Exceptions\JsonAppMissingKeysException ;
2020-05-30 17:42:50 -05:00
use LibreNMS\Exceptions\JsonAppParsingFailedException ;
use LibreNMS\Exceptions\JsonAppPollingFailedException ;
2018-05-25 21:16:16 -05:00
use LibreNMS\Exceptions\JsonAppWrongVersionException ;
2020-05-30 17:42:50 -05:00
use LibreNMS\RRD\RrdDefinition ;
2022-10-21 10:05:49 -05:00
use LibreNMS\Util\Debug ;
2023-03-10 14:50:56 +01:00
use LibreNMS\Util\Number ;
use LibreNMS\Util\UserFuncHelper ;
2017-02-23 22:45:50 +00:00
2016-10-11 17:34:09 +01:00
function bulk_sensor_snmpget ( $device , $sensors )
{
$oid_per_pdu = get_device_oid_limit ( $device );
$sensors = array_chunk ( $sensors , $oid_per_pdu );
$cache = [];
foreach ( $sensors as $chunk ) {
$oids = array_map ( function ( $data ) {
return $data [ 'sensor_oid' ];
}, $chunk );
$oids = implode ( ' ' , $oids );
2022-07-22 07:59:41 -05:00
$multi_response = snmp_get_multi_oid ( $device , $oids , '-OUQntea' );
2016-10-11 17:34:09 +01:00
$cache = array_merge ( $cache , $multi_response );
}
2020-09-21 15:43:38 +02:00
2016-10-11 17:34:09 +01:00
return $cache ;
}
2017-01-18 08:48:33 +00:00
/**
2023-06-13 13:35:00 +02:00
* @ param $device
2021-09-08 23:35:56 +02:00
* @ param string $type type / class of sensor
2017-01-18 08:48:33 +00:00
* @ return array
*/
2017-08-28 12:57:23 -05:00
function sensor_precache ( $device , $type )
2017-01-18 08:48:33 +00:00
{
2017-08-28 12:57:23 -05:00
$sensor_cache = [];
2017-01-18 08:48:33 +00:00
if ( file_exists ( 'includes/polling/sensors/pre-cache/' . $device [ 'os' ] . '.inc.php' )) {
include 'includes/polling/sensors/pre-cache/' . $device [ 'os' ] . '.inc.php' ;
}
2020-09-21 15:43:38 +02:00
2017-08-28 12:57:23 -05:00
return $sensor_cache ;
2017-01-18 08:48:33 +00:00
}
2017-02-08 04:54:30 +00:00
function poll_sensor ( $device , $class )
2016-08-28 12:32:58 -05:00
{
2019-06-23 00:29:12 -05:00
global $agent_sensors ;
2015-07-13 20:10:26 +02:00
2016-10-11 17:34:09 +01:00
$sensors = [];
$misc_sensors = [];
$all_sensors = [];
2017-01-18 08:48:33 +00:00
2017-02-17 09:51:48 +01:00
foreach ( dbFetchRows ( 'SELECT * FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ?' , [ $class , $device [ 'device_id' ]]) as $sensor ) {
2016-10-11 17:34:09 +01:00
if ( $sensor [ 'poller_type' ] == 'agent' ) {
2017-02-24 01:25:05 +00:00
// Agent sensors are polled in the unix-agent
2016-10-11 17:34:09 +01:00
} elseif ( $sensor [ 'poller_type' ] == 'ipmi' ) {
$misc_sensors [] = $sensor ;
} else {
$sensors [] = $sensor ;
}
}
$snmp_data = bulk_sensor_snmpget ( $device , $sensors );
2017-08-28 12:57:23 -05:00
$sensor_cache = sensor_precache ( $device , $class );
2017-01-18 08:48:33 +00:00
2016-10-11 17:34:09 +01:00
foreach ( $sensors as $sensor ) {
echo 'Checking (' . $sensor [ 'poller_type' ] . " ) $class " . $sensor [ 'sensor_descr' ] . '... ' . PHP_EOL ;
2015-07-13 20:10:26 +02:00
2012-05-20 18:23:40 +00:00
if ( $sensor [ 'poller_type' ] == 'snmp' ) {
2016-09-28 08:19:28 -05:00
$mibdir = null ;
2016-08-07 11:40:37 +02:00
2022-10-25 19:27:28 +02:00
$sensor_value = trim ( str_replace ( '"' , '' , $snmp_data [ $sensor [ 'sensor_oid' ]] ? ? '' ));
2016-12-07 00:30:56 +00:00
2016-10-11 17:34:09 +01:00
if ( file_exists ( 'includes/polling/sensors/' . $class . '/' . $device [ 'os' ] . '.inc.php' )) {
2017-01-18 08:48:33 +00:00
require 'includes/polling/sensors/' . $class . '/' . $device [ 'os' ] . '.inc.php' ;
2022-07-22 07:59:41 -05:00
} elseif ( isset ( $device [ 'os_group' ]) && file_exists ( 'includes/polling/sensors/' . $class . '/' . $device [ 'os_group' ] . '.inc.php' )) {
2019-03-06 16:58:14 -08:00
require 'includes/polling/sensors/' . $class . '/' . $device [ 'os_group' ] . '.inc.php' ;
2015-05-11 22:01:26 +01:00
}
2012-05-20 18:23:40 +00:00
2022-08-07 21:49:38 +02:00
if ( $class == 'state' ) {
2016-04-23 20:14:22 -05:00
if ( ! is_numeric ( $sensor_value )) {
2016-10-11 17:34:09 +01:00
$state_value = dbFetchCell (
2018-11-22 09:05:38 -06:00
' SELECT `state_value`
FROM `state_translations` LEFT JOIN `sensors_to_state_indexes`
ON `state_translations` . `state_index_id` = `sensors_to_state_indexes` . `state_index_id`
WHERE `sensors_to_state_indexes` . `sensor_id` = ?
2016-10-11 17:34:09 +01:00
AND `state_translations` . `state_descr` LIKE ? ' ,
[ $sensor [ 'sensor_id' ], $sensor_value ]
);
2016-04-23 20:14:22 -05:00
d_echo ( 'State value of ' . $sensor_value . ' is ' . $state_value . " \n " );
if ( is_numeric ( $state_value )) {
$sensor_value = $state_value ;
}
}
2015-07-13 20:10:26 +02:00
} //end if
2015-04-21 15:53:53 +01:00
unset ( $mib );
2016-08-07 11:40:37 +02:00
unset ( $mibdir );
2016-10-11 17:34:09 +01:00
$sensor [ 'new_value' ] = $sensor_value ;
$all_sensors [] = $sensor ;
}
}
foreach ( $misc_sensors as $sensor ) {
if ( $sensor [ 'poller_type' ] == 'agent' ) {
2015-05-04 09:16:48 +01:00
if ( isset ( $agent_sensors )) {
$sensor_value = $agent_sensors [ $class ][ $sensor [ 'sensor_type' ]][ $sensor [ 'sensor_index' ]][ 'current' ];
2016-10-11 17:34:09 +01:00
$sensor [ 'new_value' ] = $sensor_value ;
$all_sensors [] = $sensor ;
2016-08-28 12:32:58 -05:00
} else {
2015-05-04 09:16:48 +01:00
echo " no agent data! \n " ;
2012-05-21 10:15:00 +00:00
continue ;
2015-07-13 20:10:26 +02:00
}
2016-08-28 12:32:58 -05:00
} elseif ( $sensor [ 'poller_type' ] == 'ipmi' ) {
2015-05-04 09:16:48 +01:00
echo " already polled. \n " ;
// ipmi should probably move here from the ipmi poller file (FIXME)
2012-05-21 10:15:00 +00:00
continue ;
2016-08-28 12:32:58 -05:00
} else {
2015-05-04 09:16:48 +01:00
echo " unknown poller type! \n " ;
2012-05-21 10:15:00 +00:00
continue ;
2015-07-13 20:10:26 +02:00
} //end if
2016-10-11 17:34:09 +01:00
}
2017-02-24 01:25:05 +00:00
record_sensor_data ( $device , $all_sensors );
} //end poll_sensor()
/**
2023-06-13 13:35:00 +02:00
* @ param $device
* @ param $all_sensors
2017-02-24 01:25:05 +00:00
*/
function record_sensor_data ( $device , $all_sensors )
{
$supported_sensors = [
2023-08-13 11:43:52 -05:00
'airflow' => 'cfm' ,
'ber' => '' ,
'bitrate' => 'bps' ,
'charge' => '%' ,
'chromatic_dispersion' => 'ps/nm' ,
'cooling' => 'W' ,
'count' => '' ,
'current' => 'A' ,
'delay' => 's' ,
'dbm' => 'dBm' ,
'eer' => 'eer' ,
'fanspeed' => 'rpm' ,
'frequency' => 'Hz' ,
'humidity' => '%' ,
'load' => '%' ,
'loss' => '%' ,
'percent' => '%' ,
'power' => 'W' ,
'power_consumed' => 'kWh' ,
'power_factor' => '' ,
'pressure' => 'kPa' ,
'quality_factor' => 'dB' ,
'runtime' => 'Min' ,
'signal' => 'dBm' ,
'snr' => 'SNR' ,
'state' => '#' ,
'temperature' => 'C' ,
'tv_signal' => 'dBmV' ,
'voltage' => 'V' ,
'waterflow' => 'l/m' ,
2017-02-24 01:25:05 +00:00
];
2015-07-13 20:10:26 +02:00
2016-10-11 17:34:09 +01:00
foreach ( $all_sensors as $sensor ) {
2017-07-06 02:27:02 -05:00
$class = ucfirst ( $sensor [ 'sensor_class' ]);
2021-04-22 17:59:23 -05:00
$unit = $supported_sensors [ $sensor [ 'sensor_class' ]];
2023-03-10 14:50:56 +01:00
$sensor_value = Number :: extract ( $sensor [ 'new_value' ]);
2017-07-06 02:27:02 -05:00
$prev_sensor_value = $sensor [ 'sensor_current' ];
2020-06-09 13:51:36 -04:00
if ( $sensor_value == - 32768 || is_nan ( $sensor_value )) {
echo 'Invalid (-32768 or NaN)' ;
2011-09-20 14:22:34 +00:00
$sensor_value = 0 ;
2015-04-11 19:47:56 +01:00
}
2011-04-13 14:00:12 +00:00
2016-02-09 14:20:36 -06:00
if ( $sensor [ 'sensor_divisor' ] && $sensor_value !== 0 ) {
2011-09-20 14:22:34 +00:00
$sensor_value = ( $sensor_value / $sensor [ 'sensor_divisor' ]);
}
2011-09-18 15:38:05 +00:00
2011-04-13 14:00:12 +00:00
if ( $sensor [ 'sensor_multiplier' ]) {
$sensor_value = ( $sensor_value * $sensor [ 'sensor_multiplier' ]);
}
2023-03-10 14:50:56 +01:00
if ( isset ( $sensor [ 'user_func' ])) {
if ( is_callable ( $sensor [ 'user_func' ])) {
$sensor_value = $sensor [ 'user_func' ]( $sensor_value );
} else {
$sensor_value = ( new UserFuncHelper ( $sensor_value , $sensor [ 'new_value' ], $sensor )) -> { $sensor [ 'user_func' ]}();
}
2018-03-29 07:22:17 +02:00
}
2016-07-08 22:58:36 -05:00
$rrd_name = get_sensor_rrd_name ( $device , $sensor );
2017-12-13 03:27:10 +01:00
2022-10-25 15:31:02 +02:00
$rrd_def = RrdDefinition :: make () -> addDataset ( 'sensor' , $sensor [ 'rrd_type' ]);
2011-04-13 14:00:12 +00:00
echo " $sensor_value $unit\n " ;
2015-08-18 16:26:55 +00:00
$fields = [
'sensor' => $sensor_value ,
];
2016-07-07 01:33:43 -05:00
$tags = [
'sensor_class' => $sensor [ 'sensor_class' ],
'sensor_type' => $sensor [ 'sensor_type' ],
'sensor_descr' => $sensor [ 'sensor_descr' ],
'sensor_index' => $sensor [ 'sensor_index' ],
'rrd_name' => $rrd_name ,
'rrd_def' => $rrd_def ,
];
2016-08-28 12:32:58 -05:00
data_update ( $device , 'sensor' , $tags , $fields );
2015-08-19 20:58:02 +00:00
2017-02-24 01:25:05 +00:00
// FIXME also warn when crossing WARN level!
2017-07-06 02:27:02 -05:00
if ( $sensor [ 'sensor_limit_low' ] != '' && $prev_sensor_value > $sensor [ 'sensor_limit_low' ] && $sensor_value < $sensor [ 'sensor_limit_low' ] && $sensor [ 'sensor_alert' ] == 1 ) {
2011-04-13 14:00:12 +00:00
echo 'Alerting for ' . $device [ 'hostname' ] . ' ' . $sensor [ 'sensor_descr' ] . " \n " ;
2020-04-19 19:57:49 +02:00
log_event ( " $class under threshold: $sensor_value $unit (< { $sensor [ 'sensor_limit_low' ] } $unit ) " , $device , $sensor [ 'sensor_class' ], 4 , $sensor [ 'sensor_id' ]);
2017-07-06 02:27:02 -05:00
} elseif ( $sensor [ 'sensor_limit' ] != '' && $prev_sensor_value < $sensor [ 'sensor_limit' ] && $sensor_value > $sensor [ 'sensor_limit' ] && $sensor [ 'sensor_alert' ] == 1 ) {
2011-04-13 14:00:12 +00:00
echo 'Alerting for ' . $device [ 'hostname' ] . ' ' . $sensor [ 'sensor_descr' ] . " \n " ;
2020-04-19 19:57:49 +02:00
log_event ( " $class above threshold: $sensor_value $unit (> { $sensor [ 'sensor_limit' ] } $unit ) " , $device , $sensor [ 'sensor_class' ], 4 , $sensor [ 'sensor_id' ]);
2011-04-13 14:00:12 +00:00
}
2017-07-06 02:27:02 -05:00
if ( $sensor [ 'sensor_class' ] == 'state' && $prev_sensor_value != $sensor_value ) {
$trans = array_column (
dbFetchRows (
2018-08-26 07:42:21 -05:00
'SELECT `state_translations`.`state_value`, `state_translations`.`state_descr` FROM `sensors_to_state_indexes` LEFT JOIN `state_translations` USING (`state_index_id`) WHERE `sensors_to_state_indexes`.`sensor_id`=? AND `state_translations`.`state_value` IN (?,?)' ,
[ $sensor [ 'sensor_id' ], $sensor_value , $prev_sensor_value ]
2017-07-06 02:27:02 -05:00
),
'state_descr' ,
'state_value'
);
2017-07-07 12:15:53 -05:00
log_event ( " $class sensor { $sensor [ 'sensor_descr' ] } has changed from { $trans [ $prev_sensor_value ] } ( $prev_sensor_value ) to { $trans [ $sensor_value ] } ( $sensor_value ) " , $device , $class , 3 , $sensor [ 'sensor_id' ]);
2016-02-27 15:29:11 +01:00
}
2017-11-20 18:37:02 +00:00
if ( $sensor_value != $prev_sensor_value ) {
2021-04-22 17:59:23 -05:00
dbUpdate ([ 'sensor_current' => $sensor_value , 'sensor_prev' => $prev_sensor_value , 'lastupdate' => [ 'NOW()' ]], 'sensors' , '`sensor_class` = ? AND `sensor_id` = ?' , [ $sensor [ 'sensor_class' ], $sensor [ 'sensor_id' ]]);
2017-11-20 18:37:02 +00:00
}
2016-10-11 17:34:09 +01:00
}
2017-02-24 01:25:05 +00:00
}
2011-04-13 14:00:12 +00:00
2017-03-11 14:39:32 +00:00
/**
* Update the application status and output in the database .
*
2017-12-06 16:13:10 -06:00
* Metric values should have key for of the matching name .
* If you have multiple groups of metrics , you can group them with multiple sub arrays
* The group name ( key ) will be prepended to each metric in that group , separated by an underscore
* The special group " none " will not be prefixed .
*
2022-07-22 16:01:55 -05:00
* @ param \App\Models\Application $app app from the db , including app_id
2021-09-08 23:35:56 +02:00
* @ param string $response This should be the return state of Application polling
* @ param array $metrics an array of additional metrics to store in the database for alerting
* @ param string $status This is the current value for alerting
2017-03-11 14:39:32 +00:00
*/
2017-12-06 16:13:10 -06:00
function update_application ( $app , $response , $metrics = [], $status = '' )
2017-03-11 14:39:32 +00:00
{
2022-07-22 16:01:55 -05:00
if ( ! $app ) {
d_echo ( '$app does not exist, could not update' );
2020-09-21 15:43:38 +02:00
2017-03-11 14:39:32 +00:00
return ;
}
2022-07-22 16:01:55 -05:00
$app -> app_state = 'UNKNOWN' ;
$app -> app_status = $status ;
$app -> timestamp = DB :: raw ( 'NOW()' );
2017-03-11 14:39:32 +00:00
if ( $response != '' && $response !== false ) {
2022-06-10 23:22:41 +02:00
// if the response indicates an error, set it and set app_status to the raw response
2020-04-17 17:37:56 -05:00
if ( Str :: contains ( $response , [
2017-03-11 14:39:32 +00:00
'Traceback (most recent call last):' ,
])) {
2022-07-22 16:01:55 -05:00
$app -> app_state = 'ERROR' ;
$app -> app_status = $response ;
2022-06-10 23:22:41 +02:00
} elseif ( preg_match ( '/^(ERROR|LEGACY|UNSUPPORTED)/' , $response , $matches )) {
2022-07-22 16:01:55 -05:00
$app -> app_state = $matches [ 1 ];
$app -> app_status = $response ;
2017-03-11 14:39:32 +00:00
} else {
2020-05-20 02:21:02 +02:00
// should maybe be 'unknown' as state
2022-07-22 16:01:55 -05:00
$app -> app_state = 'OK' ;
2017-03-11 14:39:32 +00:00
}
}
2022-07-22 16:01:55 -05:00
if ( $app -> isDirty ( 'app_state' )) {
$app -> app_state_prev = $app -> getOriginal ( 'app_state' );
2020-05-20 02:21:02 +02:00
2022-07-22 16:01:55 -05:00
switch ( $app -> app_state ) {
2020-05-20 02:21:02 +02:00
case 'OK' :
2023-08-05 12:12:36 -05:00
$severity = Severity :: Ok ;
2020-05-20 02:21:02 +02:00
$event_msg = 'changed to OK' ;
break ;
case 'ERROR' :
2023-08-05 12:12:36 -05:00
$severity = Severity :: Error ;
2020-05-20 02:21:02 +02:00
$event_msg = 'ends with ERROR' ;
break ;
case 'LEGACY' :
2023-08-05 12:12:36 -05:00
$severity = Severity :: Warning ;
2020-05-20 02:21:02 +02:00
$event_msg = 'Client Agent is deprecated' ;
break ;
case 'UNSUPPORTED' :
2023-08-05 12:12:36 -05:00
$severity = Severity :: Error ;
2020-05-20 02:21:02 +02:00
$event_msg = 'Client Agent Version is not supported' ;
break ;
default :
2023-08-05 12:12:36 -05:00
$severity = Severity :: Unknown ;
2020-05-20 02:21:02 +02:00
$event_msg = 'has UNKNOWN state' ;
break ;
}
2022-11-09 09:47:19 +01:00
\App\Models\Eventlog :: log ( 'Application ' . $app -> displayName () . ' ' . $event_msg , DeviceCache :: getPrimary (), 'application' , $severity );
2017-03-11 14:39:32 +00:00
}
2022-07-22 16:01:55 -05:00
$app -> save ();
2017-12-01 01:53:26 -06:00
// update metrics
if ( ! empty ( $metrics )) {
$db_metrics = dbFetchRows ( 'SELECT * FROM `application_metrics` WHERE app_id=?' , [ $app [ 'app_id' ]]);
$db_metrics = array_by_column ( $db_metrics , 'metric' );
2017-12-06 16:13:10 -06:00
// allow two level metrics arrays, flatten them and prepend the group name
if ( is_array ( current ( $metrics ))) {
$metrics = array_reduce (
array_keys ( $metrics ),
function ( $carry , $metric_group ) use ( $metrics ) {
if ( $metric_group == 'none' ) {
$prefix = '' ;
} else {
$prefix = $metric_group . '_' ;
}
foreach ( $metrics [ $metric_group ] as $metric_name => $value ) {
$carry [ $prefix . $metric_name ] = $value ;
}
2020-09-21 15:43:38 +02:00
2017-12-06 16:13:10 -06:00
return $carry ;
},
2020-09-21 15:43:38 +02:00
[]
2017-12-06 16:13:10 -06:00
);
}
2017-12-01 01:53:26 -06:00
echo ': ' ;
foreach ( $metrics as $metric_name => $value ) {
2021-10-23 11:26:41 -05:00
$value = ( float ) $value ; // cast
2017-12-01 01:53:26 -06:00
if ( ! isset ( $db_metrics [ $metric_name ])) {
// insert new metric
dbInsert (
2020-09-21 15:43:38 +02:00
[
2017-12-01 01:53:26 -06:00
'app_id' => $app [ 'app_id' ],
'metric' => $metric_name ,
2018-08-19 17:44:11 -05:00
'value' => $value ,
2017-12-01 01:53:26 -06:00
],
'application_metrics'
);
echo '+' ;
2018-08-19 17:44:11 -05:00
} elseif ( $value != $db_metrics [ $metric_name ][ 'value' ]) {
2017-12-01 01:53:26 -06:00
dbUpdate (
2020-09-21 15:43:38 +02:00
[
2018-08-19 17:44:11 -05:00
'value' => $value ,
2017-12-01 01:53:26 -06:00
'value_prev' => $db_metrics [ $metric_name ][ 'value' ],
],
'application_metrics' ,
'app_id=? && metric=?' ,
[ $app [ 'app_id' ], $metric_name ]
);
echo 'U' ;
} else {
echo '.' ;
}
unset ( $db_metrics [ $metric_name ]);
}
// remove no longer existing metrics (generally should not happen
foreach ( $db_metrics as $db_metric ) {
dbDelete (
'application_metrics' ,
'app_id=? && metric=?' ,
[ $app [ 'app_id' ], $db_metric [ 'metric' ]]
);
echo '-' ;
}
2017-12-06 16:13:10 -06:00
echo PHP_EOL ;
2017-12-01 01:53:26 -06:00
}
2017-03-11 14:39:32 +00:00
}
2017-05-17 22:41:53 +01:00
2018-05-25 21:16:16 -05:00
/**
* This is to make it easier polling apps . Also to help standardize around JSON .
*
2022-10-21 10:05:49 -05:00
* If the data has is in base64 , it will be converted and then gunzipped .
* https :// github . com / librenms / librenms - agent / blob / master / utils / lnms_return_optimizer
* May be used to convert output from extends to that via piping it through it .
*
2018-05-25 21:16:16 -05:00
* The required keys for the returned JSON are as below .
* version - The version of the snmp extend script . Should be numeric and at least 1.
* error - Error code from the snmp extend script . Should be > 0 ( 0 will be ignored and negatives are reserved )
* errorString - Text to describe the error .
* data - An key with an array with the data to be used .
*
* If the app returns an error , an exception will be raised .
* Positive numbers will be errors returned by the extend script .
*
* Possible parsing related errors :
* - 2 : Failed to fetch data from the device
* - 3 : Could not decode the JSON .
* - 4 : Empty JSON parsed , meaning blank JSON was returned .
* - 5 : Valid json , but missing required keys
* - 6 : Returned version is less than the min version .
2022-10-21 10:05:49 -05:00
* - 7 : Base64 decode failure .
* - 8 : Gzip decode failure .
2018-05-25 21:16:16 -05:00
*
* Error checking may also be done via checking the exceptions listed below .
2022-10-21 10:05:49 -05:00
* JsonAppPollingFailedException , - 2 : Empty return from SNMP .
* JsonAppParsingFailedException , - 3 : Could not parse the JSON .
* JsonAppBlankJsonException , - 4 : Blank JSON .
* JsonAppMissingKeysException , - 5 : Missing required keys .
* JsonAppWrongVersionException , - 6 : Older version than supported .
* JsonAppExtendErroredException : Polling and parsing was good , but the returned data has an error set .
* This may be checked via $e -> getParsedJson () and then checking the
* keys error and errorString .
* JsonAppPollingBase64DecodeException , - 7 : Base64 decoding failed .
* JsonAppPollingGzipDecodeException , - 8 : Gzip decoding failed .
2018-05-25 21:16:16 -05:00
* The error value can be accessed via $e -> getCode ()
* The output can be accessed via $ -> getOutput () Only returned for code - 3 or lower .
* The parsed JSON can be access via $e -> getParsedJson ()
*
* All of the exceptions extend JsonAppException .
*
* If the error is less than - 1 , you can assume it is a legacy snmp extend script .
*
2021-09-08 23:35:56 +02:00
* @ param array $device
* @ param string $extend the extend name . For example , if 'zfs' is passed it will be converted to 'nsExtendOutputFull.3.122.102.115' .
* @ param int $min_version the minimum version to accept for the returned JSON . default : 1
2018-05-25 21:16:16 -05:00
* @ return array The json output data parsed into an array
2021-09-10 20:09:53 +02:00
*
2018-08-19 17:44:11 -05:00
* @ throws JsonAppBlankJsonException
* @ throws JsonAppExtendErroredException
* @ throws JsonAppMissingKeysException
* @ throws JsonAppParsingFailedException
2018-05-25 21:16:16 -05:00
* @ throws JsonAppPollingFailedException
2018-08-19 17:44:11 -05:00
* @ throws JsonAppWrongVersionException
2018-05-25 21:16:16 -05:00
*/
function json_app_get ( $device , $extend , $min_version = 1 )
{
2023-10-05 01:29:22 -05:00
$output = snmp_get ( $device , 'nsExtendOutputFull.' . \LibreNMS\Util\Oid :: ofString ( $extend ), '-Oqv' , 'NET-SNMP-EXTEND-MIB' );
2018-05-25 21:16:16 -05:00
2022-10-21 10:05:49 -05:00
// save for returning if not JSON
$orig_output = $output ;
2018-05-25 21:16:16 -05:00
// make sure we actually get something back
if ( empty ( $output )) {
throw new JsonAppPollingFailedException ( 'Empty return from snmp_get.' , - 2 );
}
2022-10-21 10:05:49 -05:00
// checks for base64 decoding and converts it to non-base64 so it can gunzip
if ( preg_match ( '/^[A-Za-z0-9\/\+\n]+\=*\n*$/' , $output ) && ! preg_match ( '/^[0-9]+\n/' , $output )) {
$output = base64_decode ( $output );
if ( ! $output ) {
if ( Debug :: isEnabled ()) {
echo " Decoding Base64 Failed... \n \n " ;
}
throw new JsonAppBase64DecodeException ( 'Base64 decode failed.' , $orig_output , - 7 );
}
$output = gzdecode ( $output );
if ( ! $output ) {
if ( Debug :: isEnabled ()) {
echo " Decoding GZip failed... \n \n " ;
}
throw new JsonAppGzipDecodeException ( 'Gzip decode failed.' , $orig_output , - 8 );
}
if ( Debug :: isVerbose ()) {
echo 'Decoded Base64+GZip Output: ' . $output . " \n \n " ;
}
}
2018-05-25 21:16:16 -05:00
// turn the JSON into a array
$parsed_json = json_decode ( stripslashes ( $output ), true );
// improper JSON or something else was returned. Populate the variable with an error.
if ( json_last_error () !== JSON_ERROR_NONE ) {
2022-10-21 10:05:49 -05:00
throw new JsonAppParsingFailedException ( 'Invalid JSON' , $orig_output , - 3 );
2018-05-25 21:16:16 -05:00
}
// There no keys in the array, meaning '{}' was was returned
if ( empty ( $parsed_json )) {
throw new JsonAppBlankJsonException ( 'Blank JSON returned.' , $output , - 4 );
}
// It is a legacy JSON app extend, meaning these are not set
if ( ! isset ( $parsed_json [ 'error' ], $parsed_json [ 'data' ], $parsed_json [ 'errorString' ], $parsed_json [ 'version' ])) {
throw new JsonAppMissingKeysException ( 'Legacy script or extend error, missing one or more required keys.' , $output , $parsed_json , - 5 );
}
if ( $parsed_json [ 'version' ] < $min_version ) {
throw new JsonAppWrongVersionException ( " Script,' " . $parsed_json [ 'version' ] . " ', older than required version of ' $min_version ' " , $output , $parsed_json , - 6 );
}
if ( $parsed_json [ 'error' ] != 0 ) {
throw new JsonAppExtendErroredException ( " Script returned exception: { $parsed_json [ 'errorString' ] } " , $output , $parsed_json , $parsed_json [ 'error' ]);
}
return $parsed_json ;
}
2018-11-22 09:05:38 -06:00
/**
* Some data arrays returned with json_app_get are deeper than
* update_application likes . This recurses through the array
* and flattens it out so it can nicely be inserted into the
* database .
*
* One argument is taken and that is the array to flatten .
*
2021-09-08 23:35:56 +02:00
* @ param array $array
* @ param string $prefix What to prefix to the name . Defaults to '' , nothing .
* @ param string $joiner The string to join the prefix , if set to something other
* than '' , and array keys with .
2018-11-22 09:05:38 -06:00
* @ return array The flattened array .
*/
function data_flatten ( $array , $prefix = '' , $joiner = '_' )
{
$return = [];
foreach ( $array as $key => $value ) {
if ( is_array ( $value )) {
if ( strcmp ( $prefix , '' )) {
$key = $prefix . $joiner . $key ;
}
$return = array_merge ( $return , data_flatten ( $value , $key , $joiner ));
} else {
if ( strcmp ( $prefix , '' )) {
$key = $prefix . $joiner . $key ;
}
$return [ $key ] = $value ;
}
}
return $return ;
}