Apply fixes from StyleCI (#12121)

This commit is contained in:
Jellyfrog
2020-09-21 15:43:38 +02:00
committed by GitHub
parent 82f43cb98d
commit 2fc3a21211
338 changed files with 2895 additions and 2969 deletions

View File

@@ -16,7 +16,7 @@ function bulk_sensor_snmpget($device, $sensors)
{
$oid_per_pdu = get_device_oid_limit($device);
$sensors = array_chunk($sensors, $oid_per_pdu);
$cache = array();
$cache = [];
foreach ($sensors as $chunk) {
$oids = array_map(function ($data) {
return $data['sensor_oid'];
@@ -25,6 +25,7 @@ function bulk_sensor_snmpget($device, $sensors)
$multi_response = snmp_get_multi_oid($device, $oids, '-OUQnte');
$cache = array_merge($cache, $multi_response);
}
return $cache;
}
@@ -35,10 +36,11 @@ function bulk_sensor_snmpget($device, $sensors)
*/
function sensor_precache($device, $type)
{
$sensor_cache = array();
if (file_exists('includes/polling/sensors/pre-cache/'. $device['os'] .'.inc.php')) {
include 'includes/polling/sensors/pre-cache/'. $device['os'] .'.inc.php';
$sensor_cache = [];
if (file_exists('includes/polling/sensors/pre-cache/' . $device['os'] . '.inc.php')) {
include 'includes/polling/sensors/pre-cache/' . $device['os'] . '.inc.php';
}
return $sensor_cache;
}
@@ -46,11 +48,11 @@ function poll_sensor($device, $class)
{
global $agent_sensors;
$sensors = array();
$misc_sensors = array();
$all_sensors = array();
$sensors = [];
$misc_sensors = [];
$all_sensors = [];
foreach (dbFetchRows("SELECT * FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ?", array($class, $device['device_id'])) as $sensor) {
foreach (dbFetchRows("SELECT * FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ?", [$class, $device['device_id']]) as $sensor) {
if ($sensor['poller_type'] == 'agent') {
// Agent sensors are polled in the unix-agent
} elseif ($sensor['poller_type'] == 'ipmi') {
@@ -65,33 +67,33 @@ function poll_sensor($device, $class)
$sensor_cache = sensor_precache($device, $class);
foreach ($sensors as $sensor) {
echo 'Checking (' . $sensor['poller_type'] . ") $class " . $sensor['sensor_descr'] . '... '.PHP_EOL;
echo 'Checking (' . $sensor['poller_type'] . ") $class " . $sensor['sensor_descr'] . '... ' . PHP_EOL;
if ($sensor['poller_type'] == 'snmp') {
$mibdir = null;
$sensor_value = trim(str_replace('"', '', $snmp_data[$sensor['sensor_oid']]));
if (file_exists('includes/polling/sensors/'. $class .'/'. $device['os'] .'.inc.php')) {
require 'includes/polling/sensors/'. $class .'/'. $device['os'] .'.inc.php';
} elseif (file_exists('includes/polling/sensors/'. $class .'/'. $device['os_group'] .'.inc.php')) {
require 'includes/polling/sensors/'. $class .'/'. $device['os_group'] .'.inc.php';
if (file_exists('includes/polling/sensors/' . $class . '/' . $device['os'] . '.inc.php')) {
require 'includes/polling/sensors/' . $class . '/' . $device['os'] . '.inc.php';
} elseif (file_exists('includes/polling/sensors/' . $class . '/' . $device['os_group'] . '.inc.php')) {
require 'includes/polling/sensors/' . $class . '/' . $device['os_group'] . '.inc.php';
}
if ($class == 'temperature') {
preg_match('/[\d\.\-]+/', $sensor_value, $temp_response);
if (!empty($temp_response[0])) {
if (! empty($temp_response[0])) {
$sensor_value = $temp_response[0];
}
} elseif ($class == 'state') {
if (!is_numeric($sensor_value)) {
if (! is_numeric($sensor_value)) {
$state_value = dbFetchCell(
'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` = ?
AND `state_translations`.`state_descr` LIKE ?',
array($sensor['sensor_id'], $sensor_value)
[$sensor['sensor_id'], $sensor_value]
);
d_echo('State value of ' . $sensor_value . ' is ' . $state_value . "\n");
if (is_numeric($state_value)) {
@@ -134,7 +136,7 @@ function poll_sensor($device, $class)
*/
function record_sensor_data($device, $all_sensors)
{
$supported_sensors = array(
$supported_sensors = [
'current' => 'A',
'frequency' => 'Hz',
'runtime' => 'Min',
@@ -152,12 +154,12 @@ function record_sensor_data($device, $all_sensors)
'snr' => 'SNR',
'pressure' => 'kPa',
'cooling' => 'W',
);
];
foreach ($all_sensors as $sensor) {
$class = ucfirst($sensor['sensor_class']);
$unit = $supported_sensors[$class];
$sensor_value = $sensor['new_value'];
$class = ucfirst($sensor['sensor_class']);
$unit = $supported_sensors[$class];
$sensor_value = $sensor['new_value'];
$prev_sensor_value = $sensor['sensor_current'];
if ($sensor_value == -32768 || is_nan($sensor_value)) {
@@ -183,26 +185,26 @@ function record_sensor_data($device, $all_sensors)
echo "$sensor_value $unit\n";
$fields = array(
$fields = [
'sensor' => $sensor_value,
);
];
$tags = array(
$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
);
'rrd_def' => $rrd_def,
];
data_update($device, 'sensor', $tags, $fields);
// FIXME also warn when crossing WARN level!
if ($sensor['sensor_limit_low'] != '' && $prev_sensor_value > $sensor['sensor_limit_low'] && $sensor_value < $sensor['sensor_limit_low'] && $sensor['sensor_alert'] == 1) {
echo 'Alerting for '.$device['hostname'].' '.$sensor['sensor_descr']."\n";
echo 'Alerting for ' . $device['hostname'] . ' ' . $sensor['sensor_descr'] . "\n";
log_event("$class under threshold: $sensor_value $unit (< {$sensor['sensor_limit_low']} $unit)", $device, $sensor['sensor_class'], 4, $sensor['sensor_id']);
} elseif ($sensor['sensor_limit'] != '' && $prev_sensor_value < $sensor['sensor_limit'] && $sensor_value > $sensor['sensor_limit'] && $sensor['sensor_alert'] == 1) {
echo 'Alerting for '.$device['hostname'].' '.$sensor['sensor_descr']."\n";
echo 'Alerting for ' . $device['hostname'] . ' ' . $sensor['sensor_descr'] . "\n";
log_event("$class above threshold: $sensor_value $unit (> {$sensor['sensor_limit']} $unit)", $device, $sensor['sensor_class'], 4, $sensor['sensor_id']);
}
if ($sensor['sensor_class'] == 'state' && $prev_sensor_value != $sensor_value) {
@@ -218,7 +220,7 @@ function record_sensor_data($device, $all_sensors)
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']);
}
if ($sensor_value != $prev_sensor_value) {
dbUpdate(array('sensor_current' => $sensor_value, 'sensor_prev' => $prev_sensor_value, 'lastupdate' => array('NOW()')), 'sensors', "`sensor_class` = ? AND `sensor_id` = ?", array($class, $sensor['sensor_id']));
dbUpdate(['sensor_current' => $sensor_value, 'sensor_prev' => $prev_sensor_value, 'lastupdate' => ['NOW()']], 'sensors', "`sensor_class` = ? AND `sensor_id` = ?", [$class, $sensor['sensor_id']]);
}
}
}
@@ -254,35 +256,35 @@ function poll_device($device, $force_module = false)
}
$db_ip = null;
if (!empty($ip)) {
if (! empty($ip)) {
if (empty($device['overwrite_ip'])) {
echo 'Resolved IP: '.$ip.PHP_EOL;
echo 'Resolved IP: ' . $ip . PHP_EOL;
} else {
echo 'Assigned IP: '.$ip.PHP_EOL;
echo 'Assigned IP: ' . $ip . PHP_EOL;
}
$db_ip = inet_pton($ip);
}
if (!empty($db_ip) && inet6_ntop($db_ip) != inet6_ntop($device['ip'])) {
if (! empty($db_ip) && inet6_ntop($db_ip) != inet6_ntop($device['ip'])) {
log_event('Device IP changed to ' . $ip, $device, 'system', 3);
dbUpdate(array('ip' => $db_ip), 'devices', 'device_id=?', array($device['device_id']));
dbUpdate(['ip' => $db_ip], 'devices', 'device_id=?', [$device['device_id']]);
}
if ($os_group = Config::get("os.{$device['os']}.group")) {
$device['os_group'] = $os_group;
echo ' ('.$device['os_group'].')';
echo ' (' . $device['os_group'] . ')';
}
echo PHP_EOL.PHP_EOL;
echo PHP_EOL . PHP_EOL;
unset($poll_update);
unset($poll_update_query);
unset($poll_separator);
$poll_update_array = array();
$update_array = array();
$poll_update_array = [];
$update_array = [];
$host_rrd = rrd_name($device['hostname'], '', '');
if (Config::get('norrd') !== true && !is_dir($host_rrd)) {
if (Config::get('norrd') !== true && ! is_dir($host_rrd)) {
mkdir($host_rrd);
echo "Created directory : $host_rrd\n";
}
@@ -304,9 +306,9 @@ function poll_device($device, $force_module = false)
d_echo("OS" . (isset($os_module_status) ? ($os_module_status ? '+ ' : '- ') : ' '));
d_echo("Device" . (isset($attribs['poll_' . $module]) ? ($attribs['poll_' . $module] ? '+ ' : '- ') : ' '));
if ($force_module === true ||
$attribs['poll_'.$module] ||
($os_module_status && !isset($attribs['poll_'.$module])) ||
($module_status && !isset($os_module_status) && !isset($attribs['poll_' . $module]))) {
$attribs['poll_' . $module] ||
($os_module_status && ! isset($attribs['poll_' . $module])) ||
($module_status && ! isset($os_module_status) && ! isset($attribs['poll_' . $module]))) {
$start_memory = memory_get_usage();
$module_start = microtime(true);
echo "\n#### Load poller module $module ####\n";
@@ -315,36 +317,36 @@ function poll_device($device, $force_module = false)
include "includes/polling/$module.inc.php";
} catch (Exception $e) {
// isolate module exceptions so they don't disrupt the polling process
echo $e->getTraceAsString() .PHP_EOL;
echo $e->getTraceAsString() . PHP_EOL;
c_echo("%rError in $module module.%n " . $e->getMessage() . PHP_EOL);
logfile("Error in $module module. " . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL);
}
$module_time = microtime(true) - $module_start;
$module_mem = (memory_get_usage() - $start_memory);
$module_mem = (memory_get_usage() - $start_memory);
printf("\n>> Runtime for poller module '%s': %.4f seconds with %s bytes\n", $module, $module_time, $module_mem);
printChangedStats();
echo "#### Unload poller module $module ####\n\n";
// save per-module poller stats
$tags = array(
$tags = [
'module' => $module,
'rrd_def' => RrdDefinition::make()->addDataset('poller', 'GAUGE', 0),
'rrd_name' => array('poller-perf', $module),
);
$fields = array(
'rrd_name' => ['poller-perf', $module],
];
$fields = [
'poller' => $module_time,
);
];
data_update($device, 'poller-perf', $tags, $fields);
$os->enableGraph('poller_perf');
// remove old rrd
$oldrrd = rrd_name($device['hostname'], array('poller', $module, 'perf'));
$oldrrd = rrd_name($device['hostname'], ['poller', $module, 'perf']);
if (is_file($oldrrd)) {
unlink($oldrrd);
}
unset($tags, $fields, $oldrrd);
} elseif (isset($attribs['poll_'.$module]) && $attribs['poll_'.$module] == '0') {
} elseif (isset($attribs['poll_' . $module]) && $attribs['poll_' . $module] == '0') {
echo "Module [ $module ] disabled on host.\n\n";
} elseif (isset($os_module_status) && $os_module_status == '0') {
echo "Module [ $module ] disabled on os.\n\n";
@@ -354,40 +356,40 @@ function poll_device($device, $force_module = false)
}
// Ping response
if (can_ping_device($attribs) === true && !empty($response['ping_time'])) {
$tags = array(
if (can_ping_device($attribs) === true && ! empty($response['ping_time'])) {
$tags = [
'rrd_def' => RrdDefinition::make()->addDataset('ping', 'GAUGE', 0, 65535),
);
$fields = array(
];
$fields = [
'ping' => $response['ping_time'],
);
];
$update_array['last_ping'] = array('NOW()');
$update_array['last_ping_timetaken'] = $response['ping_time'];
$update_array['last_ping'] = ['NOW()'];
$update_array['last_ping_timetaken'] = $response['ping_time'];
data_update($device, 'ping-perf', $tags, $fields);
$os->enableGraph('ping_perf');
}
$device_time = round(microtime(true) - $device_start, 3);
$device_time = round(microtime(true) - $device_start, 3);
// Poller performance
if (!empty($device_time)) {
$tags = array(
if (! empty($device_time)) {
$tags = [
'rrd_def' => RrdDefinition::make()->addDataset('poller', 'GAUGE', 0),
'module' => 'ALL',
);
$fields = array(
];
$fields = [
'poller' => $device_time,
);
];
data_update($device, 'poller-perf', $tags, $fields);
$os->enableGraph('poller_modules_perf');
}
if (!$force_module) {
if (! $force_module) {
// don't update last_polled time if we are forcing a specific module to be polled
$update_array['last_polled'] = array('NOW()');
$update_array['last_polled'] = ['NOW()'];
$update_array['last_polled_timetaken'] = $device_time;
echo "Enabling graphs: ";
@@ -402,7 +404,7 @@ function poll_device($device, $force_module = false)
echo PHP_EOL;
}
$updated = dbUpdate($update_array, 'devices', '`device_id` = ?', array($device['device_id']));
$updated = dbUpdate($update_array, 'devices', '`device_id` = ?', [$device['device_id']]);
if ($updated) {
d_echo('Updating ' . $device['hostname'] . PHP_EOL);
}
@@ -439,28 +441,29 @@ function poll_device($device, $force_module = false)
* @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
*/
function update_application($app, $response, $metrics = array(), $status = '')
function update_application($app, $response, $metrics = [], $status = '')
{
if (!is_numeric($app['app_id'])) {
if (! is_numeric($app['app_id'])) {
d_echo('$app does not contain app_id, could not update');
return;
}
$data = array(
$data = [
'app_state' => 'UNKNOWN',
'app_status' => $status,
'timestamp' => array('NOW()'),
);
'timestamp' => ['NOW()'],
];
if ($response != '' && $response !== false) {
if (Str::contains($response, array(
if (Str::contains($response, [
'Traceback (most recent call last):',
))) {
])) {
$data['app_state'] = 'ERROR';
} elseif (in_array($response, ['OK', 'ERROR', 'LEGACY', 'UNSUPPORTED'])) {
$data['app_state'] = $response;
} else {
# should maybe be 'unknown' as state
// should maybe be 'unknown' as state
$data['app_state'] = 'OK';
}
}
@@ -468,7 +471,7 @@ function update_application($app, $response, $metrics = array(), $status = '')
if ($data['app_state'] != $app['app_state']) {
$data['app_state_prev'] = $app['app_state'];
$device = dbFetchRow('SELECT * FROM devices LEFT JOIN applications ON devices.device_id=applications.device_id WHERE applications.app_id=?', array($app['app_id']));
$device = dbFetchRow('SELECT * FROM devices LEFT JOIN applications ON devices.device_id=applications.device_id WHERE applications.app_id=?', [$app['app_id']]);
$app_name = \LibreNMS\Util\StringHelpers::nicecase($app['app_type']);
@@ -494,13 +497,13 @@ function update_application($app, $response, $metrics = array(), $status = '')
$event_msg = "has UNKNOWN state";
break;
}
log_event("Application ".$app_name." ".$event_msg, $device, 'application', $severity);
log_event("Application " . $app_name . " " . $event_msg, $device, 'application', $severity);
}
dbUpdate($data, 'applications', '`app_id` = ?', array($app['app_id']));
dbUpdate($data, 'applications', '`app_id` = ?', [$app['app_id']]);
// update metrics
if (!empty($metrics)) {
$db_metrics = dbFetchRows('SELECT * FROM `application_metrics` WHERE app_id=?', array($app['app_id']));
if (! empty($metrics)) {
$db_metrics = dbFetchRows('SELECT * FROM `application_metrics` WHERE app_id=?', [$app['app_id']]);
$db_metrics = array_by_column($db_metrics, 'metric');
// allow two level metrics arrays, flatten them and prepend the group name
@@ -517,34 +520,35 @@ function update_application($app, $response, $metrics = array(), $status = '')
foreach ($metrics[$metric_group] as $metric_name => $value) {
$carry[$prefix . $metric_name] = $value;
}
return $carry;
},
array()
[]
);
}
echo ': ';
foreach ($metrics as $metric_name => $value) {
if (!isset($db_metrics[$metric_name])) {
if (! isset($db_metrics[$metric_name])) {
// insert new metric
dbInsert(
array(
[
'app_id' => $app['app_id'],
'metric' => $metric_name,
'value' => $value,
),
],
'application_metrics'
);
echo '+';
} elseif ($value != $db_metrics[$metric_name]['value']) {
dbUpdate(
array(
[
'value' => $value,
'value_prev' => $db_metrics[$metric_name]['value'],
),
],
'application_metrics',
'app_id=? && metric=?',
array($app['app_id'], $metric_name)
[$app['app_id'], $metric_name]
);
echo 'U';
} else {
@@ -559,7 +563,7 @@ function update_application($app, $response, $metrics = array(), $status = '')
dbDelete(
'application_metrics',
'app_id=? && metric=?',
array($app['app_id'], $db_metric['metric'])
[$app['app_id'], $db_metric['metric']]
);
echo '-';
}
@@ -571,10 +575,10 @@ function update_application($app, $response, $metrics = array(), $status = '')
function convert_to_celsius($value)
{
$value = ($value - 32) / 1.8;
return sprintf('%.02f', $value);
}
/**
* This is to make it easier polling apps. Also to help standardize around JSON.
*
@@ -613,7 +617,7 @@ function convert_to_celsius($value)
*
* @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 integer $min_version the minimum version to accept for the returned JSON. default: 1
* @param int $min_version the minimum version to accept for the returned JSON. default: 1
*
* @return array The json output data parsed into an array
* @throws JsonAppBlankJsonException
@@ -625,7 +629,7 @@ function convert_to_celsius($value)
*/
function json_app_get($device, $extend, $min_version = 1)
{
$output = snmp_get($device, 'nsExtendOutputFull.'.string_to_oid($extend), '-Oqv', 'NET-SNMP-EXTEND-MIB');
$output = snmp_get($device, 'nsExtendOutputFull.' . string_to_oid($extend), '-Oqv', 'NET-SNMP-EXTEND-MIB');
// make sure we actually get something back
if (empty($output)) {
@@ -646,12 +650,12 @@ function json_app_get($device, $extend, $min_version = 1)
}
// 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'])) {
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);
throw new JsonAppWrongVersionException("Script,'" . $parsed_json['version'] . "', older than required version of '$min_version'", $output, $parsed_json, -6);
}
if ($parsed_json['error'] != 0) {
@@ -678,16 +682,16 @@ function json_app_get($device, $extend, $min_version = 1)
*/
function data_flatten($array, $prefix = '', $joiner = '_')
{
$return = array();
$return = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
if (strcmp($prefix, '')) {
$key=$prefix.$joiner.$key;
$key = $prefix . $joiner . $key;
}
$return = array_merge($return, data_flatten($value, $key, $joiner));
} else {
if (strcmp($prefix, '')) {
$key=$prefix.$joiner.$key;
$key = $prefix . $joiner . $key;
}
$return[$key] = $value;
}