/** * Discover a new sensor on a device * * This function adds a status sensor to a device, if it does not already exist. * Data on the sensor is updated if it has changed, and an event is logged with regards to the changes. * * Status sensors are handed off to discover_status(). * Current sensor values are rectified in case they are broken (added spaces, etc). * * @param array &$valid Array of currently valid sensors for poller type (used to delete later) * @param string $class Class of sensor (voltage, temperature, etc.) * @param array $device Device array sensor is being discovered on * @param string $oid SNMP OID of sensor * @param string $index SNMP index of sensor * @param string $type Type of sensor * @param string $sensor_descr Description of sensor * @param int $scale Scale of sensor (0.1 for 1:10 scale, 10 for 10:1 scale, etc) * @param string $value Current sensor value * @param array $options Options (sensor_unit, limit_auto, limit*) * @param string $poller_type Type of poller being used (SNMP, Agent, etc) - Used to check valid sensors per poller type * @return bool */ function discover_sensor(&$valid, $class, $device, $oid, $index, $type, $sensor_descr, $scale = 1, $value = NULL, $options = array(), $poller_type = 'snmp') { global $config; // If this is actually a status indicator, pass it off to discover_status() then return. if ($class == 'state' || $class == 'status') { print_debug("Redirecting call to discover_status()."); return discover_status($device, $oid, $index, $type, $sensor_descr, $value, $options, $poller_type); } // Init main $param_main = array('oid' => 'sensor_oid', 'sensor_descr' => 'sensor_descr', 'scale' => 'sensor_multiplier'); // Init numeric values if (!is_numeric($scale) || $scale == 0) { $scale = 1; } // Skip discovery sensor if value not numeric or null (default) if (strlen($value)) { // Some retarded devices report data with spaces and commas // STRING: " 20,4" $value = snmp_fix_numeric($value); } if (is_numeric($value)) { $value *= $scale; // Scale before unit conversion $value = value_to_si($value, $options['sensor_unit'], $class); // Convert if not SI unit } else { print_debug("Sensor skipped by not numeric value: '{$value}', '{$sensor_descr}'"); if (strlen($value)) { print_debug("Perhaps this is named sensor, use discover_status() instead."); } return FALSE; } $param_limits = array('limit_high' => 'sensor_limit', 'limit_high_warn' => 'sensor_limit_warn', 'limit_low' => 'sensor_limit_low', 'limit_low_warn' => 'sensor_limit_low_warn'); foreach ($param_limits as $key => $column) { // Set limits vars and unit convert if required ${$key} = is_numeric($options[$key]) ? value_to_si($options[$key], $options['sensor_unit'], $class) : NULL; } // Auto calculate high/low limits if not passed $limit_auto = !isset($options['limit_auto']) || (bool) $options['limit_auto']; // Init optional $param_opt = array('entPhysicalIndex', 'entPhysicalClass', 'entPhysicalIndex_measured', 'measured_class', 'measured_entity', 'sensor_unit'); foreach ($param_opt as $key) { ${$key} = $options[$key] ? $options[$key] : NULL; } print_debug("Discover sensor: {$class}, " . $device['hostname'] . ", {$oid}, {$index}, {$type}, {$sensor_descr}, SCALE: {$scale}, LIMITS: ({$limit_low}, {$limit_low_warn}, {$limit_high_warn}, {$limit_high}), CURRENT: {$value}, {$poller_type}, {$entPhysicalIndex}, {$entPhysicalClass}"); // Check sensor ignore filters foreach ($config['ignore_sensor'] as $bi) { if (strcasecmp($bi, $sensor_descr) == 0) { print_debug("Skipped by equals: {$bi}, {$sensor_descr} "); return FALSE; } } foreach ($config['ignore_sensor_string'] as $bi) { if (stripos($sensor_descr, $bi) !== FALSE) { print_debug("Skipped by strpos: {$bi}, {$sensor_descr} "); return FALSE; } } foreach ($config['ignore_sensor_regexp'] as $bi) { if (preg_match($bi, $sensor_descr) > 0) { print_debug("Skipped by regexp: {$bi}, {$sensor_descr} "); return FALSE; } } if (!is_null($limit_low_warn) && !is_null($limit_high_warn) && $limit_low_warn > $limit_high_warn) { // Fix high/low thresholds (i.e. on negative numbers) list($limit_high_warn, $limit_low_warn) = array($limit_low_warn, $limit_high_warn); } if (dbFetchCell('SELECT COUNT(`sensor_id`) FROM `sensors` WHERE `poller_type`= ? AND `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?', array($poller_type, $class, $device['device_id'], $type, $index)) == '0') { if (!$limit_high) { $limit_high = sensor_limit_high($class, $value, $limit_auto); } if (!$limit_low) { $limit_low = sensor_limit_low($class, $value, $limit_auto); } if (!is_null($limit_low) && !is_null($limit_high) && $limit_low > $limit_high) { // Fix high/low thresholds (i.e. on negative numbers) list($limit_high, $limit_low) = array($limit_low, $limit_high); print_debug("High/low limits swapped."); } $sensor_insert = array('poller_type' => $poller_type, 'sensor_class' => $class, 'device_id' => $device['device_id'], 'sensor_index' => $index, 'sensor_type' => $type); foreach ($param_main as $key => $column) { $sensor_insert[$column] = ${$key}; } foreach ($param_limits as $key => $column) { // Convert strings/numbers to (float) or to array('NULL') ${$key} = ${$key} === NULL ? array('NULL') : (double) ${$key}; $sensor_insert[$column] = ${$key}; } foreach ($param_opt as $key) { if (is_null(${$key})) { ${$key} = array('NULL'); } $sensor_insert[$key] = ${$key}; } $sensor_id = dbInsert($sensor_insert, 'sensors'); $state_insert = array('sensor_id' => $sensor_id, 'sensor_value' => $value, 'sensor_polled' => 'NOW()'); dbInsert($state_insert, 'sensors-state'); print_debug("( {$sensor_id} inserted )"); echo '+'; log_event("Sensor added: {$class} {$type} {$index} {$sensor_descr}", $device, 'sensor', $sensor_id); } else { $sensor_entry = dbFetchRow("SELECT * FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?", array($class, $device['device_id'], $type, $index)); // Limits if (!$sensor_entry['sensor_custom_limit']) { if (!is_numeric($limit_high)) { if ($sensor_entry['sensor_limit'] !== '') { // Calculate a reasonable limit $limit_high = sensor_limit_high($class, $value, $limit_auto); } else { // Use existing limit. (this is wrong! --mike) $limit_high = $sensor_entry['sensor_limit']; } } if (!is_numeric($limit_low)) { if ($sensor_entry['sensor_limit_low'] !== '') { // Calculate a reasonable limit $limit_low = sensor_limit_low($class, $value, $limit_auto); } else { // Use existing limit. (this is wrong! --mike) $limit_low = $sensor_entry['sensor_limit_low']; } } // Fix high/low thresholds (i.e. on negative numbers) if (!is_null($limit_low) && !is_null($limit_high) && $limit_low > $limit_high) { list($limit_high, $limit_low) = array($limit_low, $limit_high); print_debug("High/low limits swapped."); } // Update limits $update = array(); $update_msg = array(); $debug_msg = 'Current sensor value: "' . $value . '", scale: "' . $scale . '"' . PHP_EOL; foreach ($param_limits as $key => $column) { // $key - param name, $$key - param value, $column - column name in DB for $key $debug_msg .= ' ' . $key . ': "' . $sensor_entry[$column] . '" -> "' . ${$key} . '"' . PHP_EOL; //convert strings/numbers to identical type (float) or to array('NULL') for correct comparison ${$key} = ${$key} === NULL ? array('NULL') : (double) ${$key}; $sensor_entry[$column] = $sensor_entry[$column] === NULL ? array('NULL') : (double) $sensor_entry[$column]; if (float_cmp(${$key}, $sensor_entry[$column], 0.1) !== 0) { $update[$column] = ${$key}; $update_msg[] = $key . ' -> "' . (is_array(${$key}) ? 'NULL' : ${$key}) . '"'; } } if (count($update)) { echo "L"; print_debug($debug_msg); log_event('Sensor updated (limits): ' . implode(', ', $update_msg), $device, 'sensor', $sensor_entry['sensor_id']); $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id'])); } } $update = array(); foreach ($param_main as $key => $column) { if (float_cmp(${$key}, $sensor_entry[$column]) !== 0) { $update[$column] = ${$key}; } } foreach ($param_opt as $key) { if (${$key} != $sensor_entry[$key]) { $update[$key] = ${$key}; } } if (count($update)) { $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id'])); echo 'U'; log_event("Sensor updated: {$class} {$type} {$index} {$sensor_descr}", $device, 'sensor', $sensor_entry['sensor_id']); } else { echo '.'; } } $valid[$class][$type][$index] = 1; }
/** * Convert Fahrenheit -> Celsius * * @param float|string $fahrenheit Temperature value in Fahrenheit unit * @return float|string Temperature value in Celsius unit */ function f2c($fahrenheit) { return value_to_si($fahrenheit, 'F'); }
function poll_sensor($device, $class, $unit, &$oid_cache) { global $config, $agent_sensors, $ipmi_sensors, $graphs, $table_rows; $sql = "SELECT * FROM `sensors`"; $sql .= " LEFT JOIN `sensors-state` USING(`sensor_id`)"; $sql .= " WHERE `sensor_class` = ? AND `device_id` = ?"; foreach (dbFetchRows($sql, array($class, $device['device_id'])) as $sensor_db) { $sensor_poll = array(); //print_cli_heading("Sensor: ".$sensor_db['sensor_descr'], 3); if (OBS_DEBUG) { echo "Checking (" . $sensor_db['poller_type'] . ") {$class} " . $sensor_db['sensor_descr'] . " "; print_r($sensor_db); } if ($sensor_db['poller_type'] == "snmp") { # if ($class == "temperature" && $device['os'] == "papouch") // Why all temperature? if ($class == "temperature") { for ($i = 0; $i < 5; $i++) { // Take value from $oid_cache if we have it, else snmp_get it if (is_numeric($oid_cache[$sensor_db['sensor_oid']])) { print_debug("value taken from oid_cache"); $sensor_poll['sensor_value'] = $oid_cache[$sensor_db['sensor_oid']]; } else { $sensor_poll['sensor_value'] = snmp_get($device, $sensor_db['sensor_oid'], "-OUqnv", "SNMPv2-MIB"); } $sensor_poll['sensor_value'] = snmp_fix_numeric($sensor_poll['sensor_value']); if (is_numeric($sensor_poll['sensor_value']) && $sensor_poll['sensor_value'] != 9999) { break; } // Papouch TME sometimes sends 999.9 when it is right in the middle of an update; sleep(1); // Give the TME some time to reset } // If we received 999.9 degrees still, reset to Unknown. if ($sensor_poll['sensor_value'] == 9999) { $sensor_poll['sensor_value'] = "U"; } } else { if ($class == "runtime") { if (isset($oid_cache[$sensor_db['sensor_oid']])) { print_debug("value taken from oid_cache"); $sensor_poll['sensor_value'] = $oid_cache[$sensor_db['sensor_oid']]; } else { $sensor_poll['sensor_value'] = snmp_get($device, $sensor_db['sensor_oid'], "-OUqnv", "SNMPv2-MIB"); } if (strpos($sensor_poll['sensor_value'], ':') !== FALSE) { // Use timetick conversion only when snmpdata is formatted as timetick 0:0:21:00.00 $sensor_poll['sensor_value'] = timeticks_to_sec($sensor_poll['sensor_value']); } } else { // Take value from $oid_cache if we have it, else snmp_get it if (is_numeric($oid_cache[$sensor_db['sensor_oid']])) { print_debug("value taken from oid_cache"); $sensor_poll['sensor_value'] = $oid_cache[$sensor_db['sensor_oid']]; } else { $sensor_poll['sensor_value'] = snmp_get($device, $sensor_db['sensor_oid'], "-OUqnv", "SNMPv2-MIB"); } $sensor_poll['sensor_value'] = snmp_fix_numeric($sensor_poll['sensor_value']); } } } else { if ($sensor_db['poller_type'] == "agent") { if (isset($agent_sensors)) { $sensor_poll['sensor_value'] = $agent_sensors[$class][$sensor_db['sensor_type']][$sensor_db['sensor_index']]['current']; // FIXME pass unit? } else { print_warning("No agent sensor data available."); continue; } } else { if ($sensor_db['poller_type'] == "ipmi") { if (isset($ipmi_sensors)) { $sensor_poll['sensor_value'] = $ipmi_sensors[$class][$sensor_db['sensor_type']][$sensor_db['sensor_index']]['current']; $unit = $ipmi_sensors[$class][$sensor_db['sensor_type']][$sensor_db['sensor_index']]['unit']; } else { print_warning("No IPMI sensor data available."); continue; } } else { print_warning("Unknown sensor poller type."); continue; } } } $sensor_polled_time = time(); // Store polled time for current sensor if (OBS_DEBUG) { print_r($sensor_poll); } if ($sensor_poll['sensor_value'] == -32768) { print_debug("Invalid (-32768) "); $sensor_poll['sensor_value'] = 0; } // Scale if (isset($sensor_db['sensor_multiplier']) && $sensor_db['sensor_multiplier'] != 0) { $sensor_poll['sensor_value'] *= $sensor_db['sensor_multiplier']; } // Unit conversion to SI (if required) $sensor_poll['sensor_value'] = value_to_si($sensor_poll['sensor_value'], $sensor_db['sensor_unit'], $class); //print_cli_data("Value", $sensor_poll['sensor_value'] . "$unit ", 3); // FIXME this block and the other block below it are kinda retarded. They should be merged and simplified. if ($sensor_poll['sensor_ignore'] || $sensor_poll['sensor_disable']) { $sensor_poll['sensor_event'] = 'ignore'; } else { if ($sensor_db['sensor_limit_low'] != '' && $sensor_poll['sensor_value'] < $sensor_db['sensor_limit_low'] || $sensor_db['sensor_limit'] != '' && $sensor_poll['sensor_value'] > $sensor_db['sensor_limit']) { $sensor_poll['sensor_event'] = 'alert'; $sensor_poll['sensor_status'] = 'Sensor critical thresholds exceeded.'; // FIXME - be more specific } else { if ($sensor_db['sensor_limit_low_warn'] != '' && $sensor_poll['sensor_value'] < $sensor_db['sensor_limit_low_warn'] || $sensor_db['sensor_limit_warn'] != '' && $sensor_poll['sensor_value'] > $sensor_db['sensor_limit_warn']) { $sensor_poll['sensor_event'] = 'warning'; $sensor_poll['sensor_status'] = 'Sensor warning thresholds exceeded.'; // FIXME - be more specific } else { $sensor_poll['sensor_event'] = 'ok'; $sensor_poll['sensor_status'] = ''; //if ($sensor_db['sensor_event'] != 'up' && $sensor_db['sensor_event'] != '') //{ // $sensor_poll['sensor_status'] = 'Sensor thresholds cleared.'; // FIXME - be more specific //} } } } // If last change never set, use current time if (empty($sensor_db['sensor_last_change'])) { $sensor_db['sensor_last_change'] = $sensor_polled_time; } if ($sensor_poll['sensor_event'] != $sensor_db['sensor_event']) { // Sensor event changed, log and set sensor_last_change $sensor_poll['status_last_change'] = $sensor_polled_time; if ($sensor_db['sensor_event'] == 'ignore') { print_message("[%ySensor Ignored%n]", 'color'); } else { if ($sensor_db['sensor_limit_low'] != "" && $sensor_db['sensor_value'] >= $sensor_db['sensor_limit_low'] && $sensor_poll['sensor_value'] < $sensor_db['sensor_limit_low']) { // If old value greater than low limit and new value less than low limit $msg = ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor_db['sensor_descr'] . " is under threshold: " . $sensor_poll['sensor_value'] . "{$unit} (< " . $sensor_db['sensor_limit_low'] . "{$unit})"; log_event(ucfirst($class) . ' ' . $sensor_db['sensor_descr'] . " under threshold: " . $sensor_poll['sensor_value'] . " {$unit} (< " . $sensor_db['sensor_limit_low'] . " {$unit})", $device, 'sensor', $sensor_db['sensor_id'], 'warning'); } else { if ($sensor_db['sensor_limit'] != "" && $sensor_db['sensor_value'] <= $sensor_db['sensor_limit'] && $sensor_poll['sensor_value'] > $sensor_db['sensor_limit']) { // If old value less than high limit and new value greater than high limit $msg = ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor_db['sensor_descr'] . " is over threshold: " . $sensor_poll['sensor_value'] . "{$unit} (> " . $sensor_db['sensor_limit'] . "{$unit})"; log_event(ucfirst($class) . ' ' . $sensor_db['sensor_descr'] . " above threshold: " . $sensor_poll['sensor_value'] . " {$unit} (> " . $sensor_db['sensor_limit'] . " {$unit})", $device, 'sensor', $sensor_db['sensor_id'], 'warning'); } } } } else { // If sensor not changed, leave old last_change $sensor_poll['sensor_last_change'] = $sensor_db['sensor_last_change']; } // Send statistics array via AMQP/JSON if AMQP is enabled globally and for the ports module if ($config['amqp']['enable'] == TRUE && $config['amqp']['modules']['sensors']) { $json_data = array('value' => $sensor_poll['sensor_value']); messagebus_send(array('attribs' => array('t' => time(), 'device' => $device['hostname'], 'device_id' => $device['device_id'], 'e_type' => 'sensor', 'e_class' => $sensor_db['sensor_class'], 'e_type' => $sensor_db['sensor_type'], 'e_index' => $sensor_db['sensor_index']), 'data' => $json_data)); } // Add table row $table_rows[] = array($sensor_db['sensor_descr'], $sensor_db['sensor_class'], $sensor_db['sensor_type'], $sensor_db['poller_type'], $sensor_poll['sensor_value'] . $unit, $sensor_poll['sensor_event'], format_unixtime($sensor_poll['sensor_last_change'])); // Update StatsD/Carbon if ($config['statsd']['enable'] == TRUE) { StatsD::gauge(str_replace(".", "_", $device['hostname']) . '.' . 'sensor' . '.' . $sensor_db['sensor_class'] . '.' . $sensor_db['sensor_type'] . '.' . $sensor_db['sensor_index'], $sensor_poll['sensor_value']); } // Update RRD - FIXME - can't convert to NG because filename is dynamic! new function should return index instead of filename. $rrd_file = get_sensor_rrd($device, $sensor_db); rrdtool_create($device, $rrd_file, "DS:sensor:GAUGE:600:-20000:U"); rrdtool_update($device, $rrd_file, "N:" . $sensor_poll['sensor_value']); // Enable graph $graphs[$sensor_db['sensor_class']] = TRUE; // Check alerts $metrics = array(); $metrics['sensor_value'] = $sensor_poll['sensor_value']; $metrics['sensor_event'] = $sensor_poll['sensor_event']; $metrics['sensor_event_uptime'] = $sensor_polled_time - $sensor_poll['sensor_last_change']; $metrics['sensor_status'] = $sensor_poll['sensor_status']; check_entity('sensor', $sensor_db, $metrics); // Update SQL State if (is_numeric($sensor_db['sensor_polled'])) { dbUpdate(array('sensor_value' => $sensor_poll['sensor_value'], 'sensor_event' => $sensor_poll['sensor_event'], 'sensor_status' => $sensor_poll['sensor_status'], 'sensor_last_change' => $sensor_poll['sensor_last_change'], 'sensor_polled' => $sensor_polled_time), 'sensors-state', '`sensor_id` = ?', array($sensor_db['sensor_id'])); } else { dbInsert(array('sensor_id' => $sensor_db['sensor_id'], 'sensor_value' => $sensor_poll['sensor_value'], 'sensor_event' => $sensor_poll['sensor_event'], 'sensor_status' => $sensor_poll['sensor_status'], 'sensor_last_change' => $sensor_poll['sensor_last_change'], 'sensor_polled' => $sensor_polled_time), 'sensors-state'); } } }
/** * @dataProvider providerValueToSi * @group values */ public function testValueToSi($type, $unit, $value, $result) { $this->assertEquals($result, value_to_si($value, $unit, $type), '', 0.0001); }