From abc6a5b799401898b7cfd4730935988c5d6a7b3e Mon Sep 17 00:00:00 2001 From: Tony Murray Date: Sun, 28 Aug 2016 17:32:55 -0500 Subject: [PATCH] PSR-2 Final cleanup (#4247) refactor: Final PSR2 cleanup --- LibreNMS/ClassLoader.php | 10 +- LibreNMS/Component.php | 83 +- LibreNMS/Exceptions/FileExistsException.php | 1 - LibreNMS/Exceptions/HostExistsException.php | 1 - LibreNMS/Exceptions/HostIpExistsException.php | 1 - .../Exceptions/HostUnreachableException.php | 1 - .../HostUnreachablePingException.php | 1 - .../HostUnreachableSnmpException.php | 1 - .../InvalidPortAssocModeException.php | 1 - .../SnmpVersionUnsupportedException.php | 1 - LibreNMS/IRCBot.php | 306 ++- LibreNMS/ObjectCache.php | 34 +- LibreNMS/Proc.php | 2 +- LibreNMS/RRDRecursiveFilterIterator.php | 6 +- addhost.php | 15 +- adduser.php | 12 +- alerts.php | 121 +- billing-calculate.php | 6 +- build-base.php | 5 +- check-services.php | 1 - config_to_json.php | 7 +- daily.php | 10 +- delhost.php | 6 +- discovery.php | 22 +- dist-pollers.php | 15 +- poll-billing.php | 25 +- poller.php | 18 +- renamehost.php | 9 +- scripts/console-ui.php | 13 +- scripts/gen_smokeping.php | 2 +- scripts/pre-commit.php | 2 +- scripts/removespikes.php | 1744 +++++++++-------- scripts/tune_port.php | 7 +- scripts/update-sql.php | 3 +- snmp-scan.php | 6 +- snmptrap.php | 3 +- syslog.php | 2 +- tests/RrdtoolTest.php | 2 - tests/SyslogTest.php | 16 +- tests/bootstrap.php | 1 - validate.php | 214 +- 41 files changed, 1339 insertions(+), 1397 deletions(-) diff --git a/LibreNMS/ClassLoader.php b/LibreNMS/ClassLoader.php index b14f25bc47..3c9fb0afe1 100644 --- a/LibreNMS/ClassLoader.php +++ b/LibreNMS/ClassLoader.php @@ -25,7 +25,6 @@ namespace LibreNMS; - /** * Class ClassLoader * @package LibreNMS @@ -63,7 +62,7 @@ class ClassLoader $file = str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, $name) . '.php'; $fullFile = realpath(__DIR__ . '/..') . DIRECTORY_SEPARATOR . $file; - if($vdebug) { + if ($vdebug) { echo __CLASS__ . " [[ $name > $fullFile ]]\n"; } @@ -84,7 +83,7 @@ class ClassLoader if (isset($this->classMap[$name])) { $file = $this->classMap[$name]; - if($vdebug) { + if ($vdebug) { echo __CLASS__ . " (( $name > $file ))\n"; } @@ -99,7 +98,7 @@ class ClassLoader foreach (array_keys($this->dirMap[$namespace]) as $dir) { $file = $dir . DIRECTORY_SEPARATOR . $class . '.php'; - if($vdebug) { + if ($vdebug) { echo __CLASS__ . " (( $name > $file ))\n"; } @@ -180,7 +179,8 @@ class ClassLoader * @param string $class the full class name to split * @return array of the split class [namespace, classname] */ - private function splitNamespace($class) { + private function splitNamespace($class) + { $parts = explode('\\', $class); $last = array_pop($parts); return array(implode('\\', $parts), $last); diff --git a/LibreNMS/Component.php b/LibreNMS/Component.php index f71aa63fa6..54779462a1 100644 --- a/LibreNMS/Component.php +++ b/LibreNMS/Component.php @@ -25,7 +25,8 @@ namespace LibreNMS; -class Component { +class Component +{ /* * These fields are used in the component table. They are returned in the array * so that they can be modified but they can not be set as user attributes. We @@ -40,12 +41,12 @@ class Component { 'error' => '', ); - public function getComponentType($TYPE=null) { + public function getComponentType($TYPE = null) + { if (is_null($TYPE)) { $SQL = "SELECT DISTINCT `type` as `name` FROM `component` ORDER BY `name`"; $row = dbFetchRow($SQL, array()); - } - else { + } else { $SQL = "SELECT DISTINCT `type` as `name` FROM `component` WHERE `type` = ? ORDER BY `name`"; $row = dbFetchRow($SQL, array($TYPE)); } @@ -53,14 +54,14 @@ class Component { if (!isset($row)) { // We didn't find any component types return false; - } - else { + } else { // We found some.. return $row; } } - public function getComponents($device_id=null,$options=array()) { + public function getComponents($device_id = null, $options = array()) + { // Define our results array, this will be set even if no rows are returned. $RESULT = array(); $PARAM = array(); @@ -87,25 +88,24 @@ class Component { $SQL .= " ( "; foreach ($options['filter'] as $field => $array) { // Only add valid fields to the query - if (in_array($field,$validFields)) { + if (in_array($field, $validFields)) { if ($array[0] == 'LIKE') { $SQL .= "`".$field."` LIKE ? AND "; $array[1] = "%".$array[1]."%"; - } - else { + } else { // Equals operator is the default $SQL .= "`".$field."` = ? AND "; } - array_push($PARAM,$array[1]); + array_push($PARAM, $array[1]); } } // Strip the last " AND " before closing the bracket. - $SQL = substr($SQL,0,-5)." )"; + $SQL = substr($SQL, 0, -5)." )"; } if ($COUNT == 0) { // Strip the " WHERE " that we didn't use. - $SQL = substr($SQL,0,-7); + $SQL = substr($SQL, 0, -7); } // sort column direction @@ -149,7 +149,7 @@ class Component { foreach ($RESULT as $k => $v) { // k1 = component id, v1 = component array foreach ($v as $k1 => $v1) { - if ( ($COUNT >= $options['limit'][0]) && ($COUNT < $options['limit'][0]+$options['limit'][1])) { + if (($COUNT >= $options['limit'][0]) && ($COUNT < $options['limit'][0]+$options['limit'][1])) { $TEMP[$k][$k1] = $v1; } // We are counting components. @@ -162,7 +162,8 @@ class Component { return $RESULT; } - public function getComponentStatus($device=null) { + public function getComponentStatus($device = null) + { $sql_query = "SELECT status, count(status) as count FROM component WHERE"; $sql_param = array(); $add = 0; @@ -191,12 +192,13 @@ class Component { $count[$v['status']] = $v['count']; } - d_echo("Component Count by Status: ".print_r($count,TRUE)."\n"); + d_echo("Component Count by Status: ".print_r($count, true)."\n"); return $count; } - public function getComponentStatusLog($component=null,$start=null,$end=null) { - if ( ($component == null) || ($start == null) || ($end == null) ) { + public function getComponentStatusLog($component = null, $start = null, $end = null) + { + if (($component == null) || ($start == null) || ($end == null)) { // Error... d_echo("Required arguments are missing. Component: ".$component.", Start: ".$start.", End: ".$end."\n"); return false; @@ -211,8 +213,7 @@ class Component { $result = dbFetchRow($sql_query, $sql_param); if ($result == false) { $return['initial'] = false; - } - else { + } else { $return['initial'] = $result['status']; } @@ -221,11 +222,12 @@ class Component { $sql_param = array($component,$start,$end); $return['data'] = dbFetchRows($sql_query, $sql_param); - d_echo("Status Log Data: ".print_r($return,TRUE)."\n"); + d_echo("Status Log Data: ".print_r($return, true)."\n"); return $return; } - public function createComponent ($device_id,$TYPE) { + public function createComponent($device_id, $TYPE) + { // Prepare our default values to be inserted. $DATA = $this->reserved; @@ -237,16 +239,17 @@ class Component { $id = dbInsert($DATA, 'component'); // Add a default status log entry - we always start ok. - $this->createStatusLogEntry($id,0,'Component Created'); + $this->createStatusLogEntry($id, 0, 'Component Created'); // Create a default component array based on what was inserted. $ARRAY = array(); $ARRAY[$id] = $DATA; - unset ($ARRAY[$id]['device_id']); // This doesn't belong here. + unset($ARRAY[$id]['device_id']); // This doesn't belong here. return $ARRAY; } - public function createStatusLogEntry($component,$status,$message) { + public function createStatusLogEntry($component, $status, $message) + { // Add an entry to the statuslog table for a particular component. $DATA = array( 'component' => $component, @@ -257,18 +260,19 @@ class Component { return dbInsert($DATA, 'component_statuslog'); } - public function deleteComponent ($id) { + public function deleteComponent($id) + { // Delete a component from the database. - return dbDelete('component', "`id` = ?",array($id)); + return dbDelete('component', "`id` = ?", array($id)); } - public function setComponentPrefs ($device_id,$ARRAY) { + public function setComponentPrefs($device_id, $ARRAY) + { // Compare the arrays. Update/Insert where necessary. $OLD = $this->getComponents($device_id); // Loop over each component. foreach ($ARRAY as $COMPONENT => $AVP) { - // Make sure the component already exists. if (!isset($OLD[$device_id][$COMPONENT])) { // Error. Component doesn't exist in the database. @@ -281,7 +285,7 @@ class Component { // If the Status has changed we need to add a log entry if ($AVP['status'] != $OLD[$device_id][$COMPONENT]['status']) { d_echo("Status Changed - Old: ".$OLD[$device_id][$COMPONENT]['status'].", New: ".$AVP['status']."\n"); - $this->createStatusLogEntry($COMPONENT,$AVP['status'],$AVP['error']); + $this->createStatusLogEntry($COMPONENT, $AVP['status'], $AVP['error']); } // Process our reserved components first. @@ -289,7 +293,6 @@ class Component { foreach ($this->reserved as $k => $v) { // does the reserved field exist, if not skip. if (isset($AVP[$k])) { - // Has the value changed? if ($AVP[$k] != $OLD[$device_id][$COMPONENT][$k]) { // The value has been modified, add it to our update array. @@ -311,8 +314,8 @@ class Component { foreach ($UPDATE as $k => $v) { $MSG .= $k." => ".$v.","; } - $MSG = substr($MSG,0,-1); - log_event($MSG,$device_id,'component',$COMPONENT); + $MSG = substr($MSG, 0, -1); + log_event($MSG, $device_id, 'component', $COMPONENT); } // Process our AVP Adds and Updates @@ -325,32 +328,28 @@ class Component { dbInsert($DATA, 'component_prefs'); // Log the addition to the Eventlog. - log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $ATTR . ", was added with value: " . $VALUE, $device_id, 'component', $COMPONENT); - } - elseif ($OLD[$device_id][$COMPONENT][$ATTR] != $VALUE) { + log_event("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $ATTR . ", was added with value: " . $VALUE, $device_id, 'component', $COMPONENT); + } elseif ($OLD[$device_id][$COMPONENT][$ATTR] != $VALUE) { // Attribute exists but the value is different, need to update $DATA = array('value'=>$VALUE); dbUpdate($DATA, 'component_prefs', '`component` = ? AND `attribute` = ?', array($COMPONENT, $ATTR)); // Add the modification to the Eventlog. - log_event("Component: ".$AVP[$COMPONENT]['type']."(".$COMPONENT."). Attribute: ".$ATTR.", was modified from: ".$OLD[$COMPONENT][$ATTR].", to: ".$VALUE,$device_id,'component',$COMPONENT); + log_event("Component: ".$AVP[$COMPONENT]['type']."(".$COMPONENT."). Attribute: ".$ATTR.", was modified from: ".$OLD[$COMPONENT][$ATTR].", to: ".$VALUE, $device_id, 'component', $COMPONENT); } - } // End Foreach AVP // Process our Deletes. $DELETE = array_diff_key($OLD[$device_id][$COMPONENT], $AVP); foreach ($DELETE as $KEY => $VALUE) { // As the Attribute has been removed from the array, we should remove it from the database. - dbDelete('component_prefs', "`component` = ? AND `attribute` = ?",array($COMPONENT,$KEY)); + dbDelete('component_prefs', "`component` = ? AND `attribute` = ?", array($COMPONENT,$KEY)); // Log the addition to the Eventlog. - log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $KEY . ", was deleted.", $COMPONENT); + log_event("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $KEY . ", was deleted.", $COMPONENT); } - } return true; } - } diff --git a/LibreNMS/Exceptions/FileExistsException.php b/LibreNMS/Exceptions/FileExistsException.php index 02ec938f5a..55a42cd183 100644 --- a/LibreNMS/Exceptions/FileExistsException.php +++ b/LibreNMS/Exceptions/FileExistsException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class FileExistsException extends \Exception { diff --git a/LibreNMS/Exceptions/HostExistsException.php b/LibreNMS/Exceptions/HostExistsException.php index c48740b81a..7e3e9de88b 100644 --- a/LibreNMS/Exceptions/HostExistsException.php +++ b/LibreNMS/Exceptions/HostExistsException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class HostExistsException extends \Exception { diff --git a/LibreNMS/Exceptions/HostIpExistsException.php b/LibreNMS/Exceptions/HostIpExistsException.php index 4159bfdbc1..7345a8d9f2 100644 --- a/LibreNMS/Exceptions/HostIpExistsException.php +++ b/LibreNMS/Exceptions/HostIpExistsException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class HostIpExistsException extends HostExistsException { diff --git a/LibreNMS/Exceptions/HostUnreachableException.php b/LibreNMS/Exceptions/HostUnreachableException.php index 951ccf1a60..8ab9bac383 100644 --- a/LibreNMS/Exceptions/HostUnreachableException.php +++ b/LibreNMS/Exceptions/HostUnreachableException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class HostUnreachableException extends \Exception { protected $reasons = array(); diff --git a/LibreNMS/Exceptions/HostUnreachablePingException.php b/LibreNMS/Exceptions/HostUnreachablePingException.php index f013587d13..c0fa98f18a 100644 --- a/LibreNMS/Exceptions/HostUnreachablePingException.php +++ b/LibreNMS/Exceptions/HostUnreachablePingException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class HostUnreachablePingException extends HostUnreachableException { diff --git a/LibreNMS/Exceptions/HostUnreachableSnmpException.php b/LibreNMS/Exceptions/HostUnreachableSnmpException.php index ec6e97d677..6ccabd0f24 100644 --- a/LibreNMS/Exceptions/HostUnreachableSnmpException.php +++ b/LibreNMS/Exceptions/HostUnreachableSnmpException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class HostUnreachableSnmpException extends HostUnreachableException { diff --git a/LibreNMS/Exceptions/InvalidPortAssocModeException.php b/LibreNMS/Exceptions/InvalidPortAssocModeException.php index 285fb4ac9c..0217ac5aad 100644 --- a/LibreNMS/Exceptions/InvalidPortAssocModeException.php +++ b/LibreNMS/Exceptions/InvalidPortAssocModeException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class InvalidPortAssocModeException extends \Exception { diff --git a/LibreNMS/Exceptions/SnmpVersionUnsupportedException.php b/LibreNMS/Exceptions/SnmpVersionUnsupportedException.php index 79b87e053e..bf8f2bbe61 100644 --- a/LibreNMS/Exceptions/SnmpVersionUnsupportedException.php +++ b/LibreNMS/Exceptions/SnmpVersionUnsupportedException.php @@ -25,7 +25,6 @@ namespace LibreNMS\Exceptions; - class SnmpVersionUnsupportedException extends \Exception { diff --git a/LibreNMS/IRCBot.php b/LibreNMS/IRCBot.php index e5dcdf5dfe..c4452e183b 100644 --- a/LibreNMS/IRCBot.php +++ b/LibreNMS/IRCBot.php @@ -20,7 +20,8 @@ namespace LibreNMS; -class IRCBot { +class IRCBot +{ private $last_activity = ''; @@ -62,7 +63,8 @@ class IRCBot { private $tick = 62500; - public function __construct() { + public function __construct() + { global $config, $database_link; $this->log('Setting up IRC-Bot..'); if (is_resource($database_link)) { @@ -77,8 +79,7 @@ class IRCBot { if ($this->config['irc_port'][0] == '+') { $this->ssl = true; $this->port = substr($this->config['irc_port'], 1); - } - else { + } else { $this->port = $this->config['irc_port']; } @@ -89,11 +90,9 @@ class IRCBot { if ($this->config['irc_chan']) { if (is_array($this->config['irc_chan'])) { $this->chan = $this->config['irc_chan']; - } - else if (strstr($this->config['irc_chan'], ',')) { + } elseif (strstr($this->config['irc_chan'], ',')) { $this->chan = explode(',', $this->config['irc_chan']); - } - else { + } else { $this->chan = array($this->config['irc_chan']); } } @@ -101,8 +100,7 @@ class IRCBot { if ($this->config['irc_alert_chan']) { if (strstr($this->config['irc_alert_chan'], ',')) { $this->config['irc_alert_chan'] = explode(',', $this->config['irc_alert_chan']); - } - else { + } else { $this->config['irc_alert_chan'] = array($this->config['irc_alert_chan']); } } @@ -111,14 +109,14 @@ class IRCBot { $this->pass = $this->config['irc_pass']; } - $this->load_external(); + $this->loadExternal(); $this->log('Starting IRC-Bot..'); $this->init(); - }//end __construct() - private function load_external() { + private function loadExternal() + { if (!$this->config['irc_external']) { return true; } @@ -135,13 +133,13 @@ class IRCBot { } return $this->log('Cached '.sizeof($this->external).' commands.'); - }//end load_external() - private function init() { + private function init() + { if ($this->config['irc_alert']) { - $this->connect_alert(); + $this->connectAlert(); } $this->last_activity = time(); @@ -182,11 +180,11 @@ class IRCBot { } return $this->init(); - }//end init() - private function connect_alert() { + private function connectAlert() + { $f = $this->config['install_dir'].'/.ircbot.alert'; if (( file_exists($f) && filetype($f) != 'fifo' && !unlink($f) ) || ( !file_exists($f) && !shell_exec("mkfifo $f && echo 1") )) { $this->log('Error - Cannot create Alert-File'); @@ -201,11 +199,11 @@ class IRCBot { $this->log('Error - Cannot open Alert-File'); return false; - }//end connect_alert() - private function read($buff) { + private function read($buff) + { $r = fread($this->socket[$buff], 64); $this->buff[$buff] .= $r; $r = strlen($r); @@ -224,21 +222,26 @@ class IRCBot { } return false; - }//end read() - private function alertData() { + private function alertData() + { if (($alert = $this->read('alert')) !== false) { $alert = json_decode($alert, true); if (!is_array($alert)) { return false; } - switch ($alert['state']): - case 3: $severity_extended = '+'; break; - case 4: $severity_extended = '-'; break; - default: $severity_extended = ''; + switch ($alert['state']) : + case 3: + $severity_extended = '+'; + break; + case 4: + $severity_extended = '-'; + break; + default: + $severity_extended = ''; endswitch; $severity = str_replace(array('warning', 'critical'), array(chr(3).'8Warning', chr(3).'4Critical'), $alert['severity']).$severity_extended.chr(3).' '; @@ -248,18 +251,17 @@ class IRCBot { if ($this->config['irc_alert_chan']) { foreach ($this->config['irc_alert_chan'] as $chan) { - $this->irc_raw('PRIVMSG '.$chan.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults:' : '')); + $this->ircRaw('PRIVMSG '.$chan.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults:' : '')); foreach ($alert['faults'] as $k => $v) { - $this->irc_raw('PRIVMSG '.$chan.' :#'.$k.' '.$v['string']); + $this->ircRaw('PRIVMSG '.$chan.' :#'.$k.' '.$v['string']); } } - } - else { + } else { foreach ($this->authd as $nick => $data) { if ($data['expire'] >= time()) { - $this->irc_raw('PRIVMSG '.$nick.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults'.(sizeof($alert['faults']) > 3 ? ' (showing first 3 out of '.sizeof($alert['faults']).' )' : '' ).':' : '')); + $this->ircRaw('PRIVMSG '.$nick.' :'.$severity.trim($alert['title']).' - Rule: '.trim($alert['name'] ? $alert['name'] : $alert['rule']).(sizeof($alert['faults']) > 0 ? ' - Faults'.(sizeof($alert['faults']) > 3 ? ' (showing first 3 out of '.sizeof($alert['faults']).' )' : '' ).':' : '')); foreach ($alert['faults'] as $k => $v) { - $this->irc_raw('PRIVMSG '.$nick.' :#'.$k.' '.$v['string']); + $this->ircRaw('PRIVMSG '.$nick.' :#'.$k.' '.$v['string']); if ($k >= 3) { break; } @@ -268,17 +270,17 @@ class IRCBot { } } }//end if - }//end alertData() - private function getData() { + private function getData() + { if (($data = $this->read('irc')) !== false) { $this->last_activity = time(); $this->data = $data; $ex = explode(' ', $this->data); if ($ex[0] == 'PING') { - return $this->irc_raw('PONG '.$ex[1]); + return $this->ircRaw('PONG '.$ex[1]); } if ($ex[1] == 376 || $ex[1] == 422 || ($ex[1] == 'MODE' && $ex[2] == $this->nick)) { @@ -293,79 +295,78 @@ class IRCBot { $this->handleCommand(); } } - }//end getData() - private function joinChan($chan=false) { + private function joinChan($chan = false) + { if ($chan) { $this->chan[] = $chan; } foreach ($this->chan as $chan) { - $this->irc_raw('JOIN '.$chan); + $this->ircRaw('JOIN '.$chan); } return true; - }//end joinChan() - private function handleCommand() { + private function handleCommand() + { $this->command = str_replace(':.', '', $this->command); $tmp = explode(':.'.$this->command.' ', $this->data); - $this->user = $this->get_user(); + $this->user = $this->getAuthdUser(); if ($this->isAuthd() || trim($this->command) == 'auth') { $this->proceedCommand(str_replace("\n", '', trim($this->command)), trim($tmp[1])); } $this->authd[$this->getUser($this->data)] = $this->user; return false; - }//end handleCommand() - private function proceedCommand($command, $params) { + private function proceedCommand($command, $params) + { $command = strtolower($command); if (in_array($command, $this->commands)) { $this->chkdb(); $this->log($command." ( '".$params."' )"); return $this->{'_'.$command}($params); - } - else if ($this->external[$command]) { + } elseif ($this->external[$command]) { $this->chkdb(); $this->log($command." ( '".$params."' ) [Ext]"); return eval($this->external[$command]); } return false; - }//end proceedCommand() - private function respond($msg) { + private function respond($msg) + { $chan = $this->getChan($this->data); return $this->sendMessage($msg, strstr($chan, '#') ? $chan : $this->getUser($this->data)); - }//end respond() - private function getChan($param) { + private function getChan($param) + { $data = explode('PRIVMSG ', $this->data, 3); $data = explode(' ', $data[1], 2); return $data[0]; - }//end getChan() - private function getUser($param) { + private function getUser($param) + { $arrData = explode('!', $param, 2); return str_replace(':', '', $arrData[0]); - }//end getUser() - private function connect($try) { + private function connect($try) + { if ($try > $this->max_retry) { $this->log('Failed too many connection attempts, aborting'); return die(); @@ -378,8 +379,7 @@ class IRCBot { if ($this->ssl) { $server = 'ssl://'.$this->server; - } - else { + } else { $server = $this->server; } @@ -387,91 +387,86 @@ class IRCBot { $ssl_context_params = array('ssl'=>array('allow_self_signed'=> true, 'verify_peer' => false, 'verify_peer_name' => false )); $ssl_context = stream_context_create($ssl_context_params); $this->socket['irc'] = stream_socket_client($server.':'.$this->port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ssl_context); - } - else { + } else { $this->socket['irc'] = fsockopen($server, $this->port); } if (!is_resource($this->socket['irc'])) { return $this->connect($try + 1); - } - else { + } else { stream_set_blocking($this->socket['irc'], false); return true; } - }//end connect() - private function doAuth() { - if ($this->irc_raw('USER '.$this->nick.' 0 '.$this->nick.' :'.$this->nick) && $this->irc_raw('NICK '.$this->nick)) { + private function doAuth() + { + if ($this->ircRaw('USER '.$this->nick.' 0 '.$this->nick.' :'.$this->nick) && $this->ircRaw('NICK '.$this->nick)) { return true; } return false; - }//end doAuth() - private function sendMessage($message, $chan) { + private function sendMessage($message, $chan) + { if ($this->debug) { $this->log("Sending 'PRIVMSG ".trim($chan).' :'.trim($message)."'"); } - return $this->irc_raw('PRIVMSG '.trim($chan).' :'.trim($message)); - + return $this->ircRaw('PRIVMSG '.trim($chan).' :'.trim($message)); }//end sendMessage() - private function log($msg) { + private function log($msg) + { echo '['.date('r').'] '.trim($msg)."\n"; return true; - }//end log() - private function chkdb() { + private function chkdb() + { if (!is_resource($this->sql)) { if (($this->sql = mysqli_connect($this->config['db_host'], $this->config['db_user'], $this->config['db_pass'])) != false && mysqli_select_db($this->sql, $this->config['db_name'])) { return true; - } - else { + } else { $this->log('Cannot connect to MySQL'); return die(); } - } - else { + } else { return true; } - }//end chkdb() - private function isAuthd() { + private function isAuthd() + { if ($this->user['expire'] >= time()) { $this->user['expire'] = (time() + ($this->config['irc_authtime'] * 3600)); return true; - } - else { + } else { return false; } - }//end isAuthd() - private function get_user() { + private function getAuthdUser() + { return $this->authd[$this->getUser($this->data)]; - }//end get_user() - private function irc_raw($params) { + private function ircRaw($params) + { return fputs($this->socket['irc'], $params."\r\n"); - }//end irc_raw() - private function _auth($params) { + private function _auth($params) + { $params = explode(' ', $params, 2); if (strlen($params[0]) == 64) { if ($this->tokens[$this->getUser($this->data)] == $params[0]) { @@ -489,12 +484,10 @@ class IRCBot { } return $this->respond('Authenticated.'); - } - else { + } else { return $this->respond('Nope.'); } - } - else { + } else { $user = dbFetchRow('SELECT `user_id`,`username`,`email` FROM `users` WHERE `username` = ?', array(mres($params[0]))); if ($user['email'] && $user['username'] == $params[0]) { $token = hash('gost', openssl_random_pseudo_bytes(1024)); @@ -507,21 +500,19 @@ class IRCBot { if (send_mail($user['email'], 'LibreNMS IRC-Bot Authtoken', "Your Authtoken for the IRC-Bot:\r\n\r\n".$token."\r\n\r\n") === true) { return $this->respond('Token sent!'); - } - else { + } else { return $this->respond('Sorry, seems like mail doesnt like us.'); } - } - else { + } else { return $this->respond('Who are you again?'); } }//end if return false; - }//end _auth() - private function _reload() { + private function _reload() + { if ($this->user['level'] == 10) { global $config; $config = array(); @@ -532,54 +523,51 @@ class IRCBot { if ($config != $this->config) { return $this->__construct(); } - } - else { + } else { return $this->respond('Permission denied.'); } - }//end _reload() - private function _join($params) { + private function _join($params) + { if ($this->user['level'] == 10) { return $this->joinChan($params); - } - else { + } else { return $this->respond('Permission denied.'); } - }//end _join() - private function _quit($params) { + private function _quit($params) + { if ($this->user['level'] == 10) { return die(); - } - else { + } else { return $this->respond('Permission denied.'); } - }//end _quit() - private function _help($params) { + private function _help($params) + { foreach ($this->commands as $cmd) { $msg .= ', '.$cmd; } $msg = substr($msg, 2); return $this->respond("Available commands: $msg"); - }//end _help() - private function _version($params) { + private function _version($params) + { return $this->respond($this->config['project_name_version'].', PHP: '.PHP_VERSION); - }//end _version() - private function _log($params) { + private function _log($params) + { $num = 1; if ($params > 1) { $num = $params; @@ -587,8 +575,7 @@ class IRCBot { if ($this->user['level'] < 5) { $tmp = dbFetchRows('SELECT `event_id`,`host`,`datetime`,`message`,`type` FROM `eventlog` WHERE `host` IN ('.implode(',', $this->user['devices']).') ORDER BY `event_id` DESC LIMIT '.mres($num)); - } - else { + } else { $tmp = dbFetchRows('SELECT `event_id`,`host`,`datetime`,`message`,`type` FROM `eventlog` ORDER BY `event_id` DESC LIMIT '.mres($num)); } @@ -602,15 +589,14 @@ class IRCBot { } return true; - }//end _log() - private function _down($params) { + private function _down($params) + { if ($this->user['level'] < 5) { $tmp = dbFetchRows('SELECT `hostname` FROM `devices` WHERE status=0 AND `device_id` IN ('.implode(',', $this->user['devices']).')'); - } - else { + } else { $tmp = dbFetchRows('SELECT `hostname` FROM `devices` WHERE status=0'); } @@ -623,11 +609,11 @@ class IRCBot { $msg = substr($msg, 2); $msg = $msg ? $msg : 'Nothing to show :)'; return $this->respond($msg); - }//end _down() - private function _device($params) { + private function _device($params) + { $params = explode(' ', $params); $hostname = $params[0]; $device = dbFetchRow('SELECT * FROM `devices` WHERE `hostname` = ?', array($hostname)); @@ -643,11 +629,11 @@ class IRCBot { $status .= $device['ignore'] ? '*Ignored*' : ''; $status .= $device['disabled'] ? '*Disabled*' : ''; return $this->respond($device['os'].' '.$device['version'].' '.$device['features'].' '.$status); - }//end _device() - private function _port($params) { + private function _port($params) + { $params = explode(' ', $params); $hostname = $params[0]; $ifname = $params[1]; @@ -666,15 +652,14 @@ class IRCBot { $pps_in = format_bi($port['ifInUcastPkts_rate']); $pps_out = format_bi($port['ifOutUcastPkts_rate']); return $this->respond($port['ifAdminStatus'].'/'.$port['ifOperStatus'].' '.$bps_in.' > bps > '.$bps_out.' | '.$pps_in.'pps > PPS > '.$pps_out.'pps'); - }//end _port() - private function _listdevices($params) { + private function _listdevices($params) + { if ($this->user['level'] < 5) { $tmp = dbFetchRows('SELECT `hostname` FROM `devices` WHERE `device_id` IN ('.implode(',', $this->user['devices']).')'); - } - else { + } else { $tmp = dbFetchRows('SELECT `hostname` FROM `devices`'); } @@ -685,11 +670,11 @@ class IRCBot { $msg = substr($msg, 2); $msg = $msg ? $msg : 'Nothing to show..?'; return $this->respond($msg); - }//end _listdevices() - private function _status($params) { + private function _status($params) + { $params = explode(' ', $params); $statustype = $params[0]; if ($this->user['level'] < 5) { @@ -700,48 +685,45 @@ class IRCBot { } switch ($statustype) { - case 'devices': - case 'device': - case 'dev': - $devcount = array_pop(dbFetchRow('SELECT count(*) FROM devices'.$d_w)); - $devup = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '1' AND `ignore` = '0'".$d_a)); - $devdown = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '0' AND `ignore` = '0'".$d_a)); - $devign = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `ignore` = '1'".$d_a)); - $devdis = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `disabled` = '1'".$d_a)); - $msg = 'Devices: '.$devcount.' ('.$devup.' up, '.$devdown.' down, '.$devign.' ignored, '.$devdis.' disabled'.')'; - break; + case 'devices': + case 'device': + case 'dev': + $devcount = array_pop(dbFetchRow('SELECT count(*) FROM devices'.$d_w)); + $devup = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '1' AND `ignore` = '0'".$d_a)); + $devdown = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE status = '0' AND `ignore` = '0'".$d_a)); + $devign = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `ignore` = '1'".$d_a)); + $devdis = array_pop(dbFetchRow("SELECT count(*) FROM devices WHERE `disabled` = '1'".$d_a)); + $msg = 'Devices: '.$devcount.' ('.$devup.' up, '.$devdown.' down, '.$devign.' ignored, '.$devdis.' disabled'.')'; + break; - case 'ports': - case 'port': - case 'prt': - $prtcount = array_pop(dbFetchRow('SELECT count(*) FROM ports'.$p_w)); - $prtup = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'up' AND I.ignore = '0' AND I.device_id = D.device_id AND D.ignore = '0'".$p_a)); - $prtdown = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'down' AND I.ifAdminStatus = 'up' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a)); - $prtsht = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifAdminStatus = 'down' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a)); - $prtign = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '1' OR D.ignore = '1')".$p_a)); - $prterr = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '0' OR D.ignore = '0') AND (I.ifInErrors_delta > '0' OR I.ifOutErrors_delta > '0')".$p_a)); - $msg = 'Ports: '.$prtcount.' ('.$prtup.' up, '.$prtdown.' down, '.$prtign.' ignored, '.$prtsht.' shutdown'.')'; - break; + case 'ports': + case 'port': + case 'prt': + $prtcount = array_pop(dbFetchRow('SELECT count(*) FROM ports'.$p_w)); + $prtup = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'up' AND I.ignore = '0' AND I.device_id = D.device_id AND D.ignore = '0'".$p_a)); + $prtdown = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifOperStatus = 'down' AND I.ifAdminStatus = 'up' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a)); + $prtsht = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE I.ifAdminStatus = 'down' AND I.ignore = '0' AND D.device_id = I.device_id AND D.ignore = '0'".$p_a)); + $prtign = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '1' OR D.ignore = '1')".$p_a)); + $prterr = array_pop(dbFetchRow("SELECT count(*) FROM ports AS I, devices AS D WHERE D.device_id = I.device_id AND (I.ignore = '0' OR D.ignore = '0') AND (I.ifInErrors_delta > '0' OR I.ifOutErrors_delta > '0')".$p_a)); + $msg = 'Ports: '.$prtcount.' ('.$prtup.' up, '.$prtdown.' down, '.$prtign.' ignored, '.$prtsht.' shutdown'.')'; + break; - case 'services': - case 'service': - case 'srv': - $srvcount = array_pop(dbFetchRow('SELECT count(service_id) FROM services'.$d_w)); - $srvup = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '1' AND service_ignore ='0'".$d_a)); - $srvdown = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '0' AND service_ignore = '0'".$d_a)); - $srvign = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_ignore = '1'".$d_a)); - $srvdis = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_disabled = '1'".$d_a)); - $msg = 'Services: '.$srvcount.' ('.$srvup.' up, '.$srvdown.' down, '.$srvign.' ignored, '.$srvdis.' disabled'.')'; - break; + case 'services': + case 'service': + case 'srv': + $srvcount = array_pop(dbFetchRow('SELECT count(service_id) FROM services'.$d_w)); + $srvup = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '1' AND service_ignore ='0'".$d_a)); + $srvdown = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_status = '0' AND service_ignore = '0'".$d_a)); + $srvign = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_ignore = '1'".$d_a)); + $srvdis = array_pop(dbFetchRow("SELECT count(service_id) FROM services WHERE service_disabled = '1'".$d_a)); + $msg = 'Services: '.$srvcount.' ('.$srvup.' up, '.$srvdown.' down, '.$srvign.' ignored, '.$srvdis.' disabled'.')'; + break; - default: - $msg = 'Error: STATUS requires one of the following: ||'; - break; + default: + $msg = 'Error: STATUS requires one of the following: ||'; + break; }//end switch return $this->respond($msg); - }//end _status() - - }//end class diff --git a/LibreNMS/ObjectCache.php b/LibreNMS/ObjectCache.php index c2bb3f7d66..437c96402d 100644 --- a/LibreNMS/ObjectCache.php +++ b/LibreNMS/ObjectCache.php @@ -28,7 +28,8 @@ namespace LibreNMS; use ArrayAccess; -class ObjectCache implements ArrayAccess { +class ObjectCache implements ArrayAccess +{ private $data = array(); @@ -39,13 +40,13 @@ class ObjectCache implements ArrayAccess { * Initialize ObjectCache * @param string $obj Name of Object */ - public function __construct($obj) { + public function __construct($obj) + { global $config; $this->obj = $obj; if (isset($GLOBALS['_ObjCache'][$obj])) { $this->data = $GLOBALS['_ObjCacheSkell'][$obj]; - } - else { + } else { if (!is_array($GLOBALS['_ObjCacheSkell'])) { $GLOBALS['_ObjCacheSkell'] = array(); } @@ -64,7 +65,6 @@ class ObjectCache implements ArrayAccess { } } }//end if - }//end __construct() @@ -73,13 +73,13 @@ class ObjectCache implements ArrayAccess { * @param string $obj Name of Data-Object * @return boolean */ - public function offsetExists($obj) { + public function offsetExists($obj) + { if (isset($this->data[$obj])) { return true; } return false; - }//end offsetExists() @@ -88,15 +88,14 @@ class ObjectCache implements ArrayAccess { * @param string $obj Name of Data-Object * @return mixed */ - public function offsetGet($obj) { + public function offsetGet($obj) + { if (isset($this->data[$obj])) { if (isset($this->data[$obj]['value'])) { return $this->data[$obj]['value']; - } - else if (isset($GLOBALS['_ObjCache'][$this->obj][$obj]['value'])) { + } elseif (isset($GLOBALS['_ObjCache'][$this->obj][$obj]['value'])) { return $GLOBALS['_ObjCache'][$this->obj][$obj]['value']; - } - else { + } else { $GLOBALS['_ObjCache'][$this->obj][$obj]['value'] = dbFetchRows($this->data[$obj]['query'], $this->data[$obj]['params']); if (sizeof($GLOBALS['_ObjCache'][$this->obj][$obj]['value']) == 1 && sizeof($GLOBALS['_ObjCache'][$this->obj][$obj]['value'][0]) == 1) { $GLOBALS['_ObjCache'][$this->obj][$obj]['value'] = current($GLOBALS['_ObjCache'][$this->obj][$obj]['value'][0]); @@ -104,7 +103,6 @@ class ObjectCache implements ArrayAccess { return $GLOBALS['_ObjCache'][$this->obj][$obj]['value']; } } - }//end offsetGet() @@ -114,14 +112,14 @@ class ObjectCache implements ArrayAccess { * @param mixed $value Value * @return boolean */ - public function offsetSet($obj, $value) { + public function offsetSet($obj, $value) + { if (!is_array($this->data[$obj])) { $this->data[$obj] = array(); } $this->data[$obj]['value'] = $value; return $this->data[$obj]['value']; - }//end offsetSet() @@ -130,11 +128,9 @@ class ObjectCache implements ArrayAccess { * @param string $obj Name of Data-Object * @return mixed */ - public function offsetUnset($obj) { + public function offsetUnset($obj) + { unset($this->data[$obj]['value']); return true; - }//end offsetUnset() - - }//end class diff --git a/LibreNMS/Proc.php b/LibreNMS/Proc.php index 4c2050ffc9..a588fdbf18 100644 --- a/LibreNMS/Proc.php +++ b/LibreNMS/Proc.php @@ -207,7 +207,7 @@ class Proc */ public function isRunning() { - if(!is_resource($this->_process)) { + if (!is_resource($this->_process)) { return false; } $st = $this->getStatus(); diff --git a/LibreNMS/RRDRecursiveFilterIterator.php b/LibreNMS/RRDRecursiveFilterIterator.php index ef038fe313..527b2f60ee 100644 --- a/LibreNMS/RRDRecursiveFilterIterator.php +++ b/LibreNMS/RRDRecursiveFilterIterator.php @@ -31,9 +31,11 @@ namespace LibreNMS; * @method boolean isDir() * **/ -class RRDRecursiveFilterIterator extends \RecursiveFilterIterator { +class RRDRecursiveFilterIterator extends \RecursiveFilterIterator +{ - public function accept() { + public function accept() + { $filename = $this->current()->getFilename(); if ($filename[0] === '.') { // Ignore hidden files and directories diff --git a/addhost.php b/addhost.php index ed33b148d8..329ecb960f 100755 --- a/addhost.php +++ b/addhost.php @@ -45,12 +45,12 @@ if (isset($options['f']) && $options['f'] == 0) { } $port_assoc_mode = $config['default_port_association_mode']; -$valid_assoc_modes = get_port_assoc_modes (); -if (isset ($options['p'])) { +$valid_assoc_modes = get_port_assoc_modes(); +if (isset($options['p'])) { $port_assoc_mode = $options['p']; - if (! in_array ($port_assoc_mode, $valid_assoc_modes)) { + if (! in_array($port_assoc_mode, $valid_assoc_modes)) { echo "Invalid port association mode '" . $port_assoc_mode . "'\n"; - echo 'Valid modes: ' . join (', ', $valid_assoc_modes) . "\n"; + echo 'Valid modes: ' . join(', ', $valid_assoc_modes) . "\n"; exit(1); } @@ -178,14 +178,13 @@ if (!empty($argv[1])) { echo " $reason\n"; } exit(2); - } catch (Exception $e){ + } catch (Exception $e) { print_error($e->getMessage()); exit(3); } } else { - c_echo( - "\n".$config['project_name_version'].' Add Host Tool + "\n".$config['project_name_version'].' Add Host Tool Usage (SNMPv1/2c): ./addhost.php [-g ] [-f] [-p ] <%Whostname%n> [community] [v1|v2c] [port] ['.implode('|', $config['snmp']['transports']).'] Usage (SNMPv3) : Config Defaults : ./addhost.php [-g ] [-f] [-p ] <%Whostname%n> any v3 [user] [port] ['.implode('|', $config['snmp']['transports']).'] @@ -198,7 +197,7 @@ if (!empty($argv[1])) { -p allow you to set a port association mode for this device. By default ports are associated by \'ifIndex\'. For Linux/Unix based devices \'ifName\' or \'ifDescr\' might be useful for a stable iface mapping. The default for this installation is \'' . $config['default_port_association_mode'] . '\' - Valid port assoc modes are: ' . join (', ', $valid_assoc_modes) . ' + Valid port assoc modes are: ' . join(', ', $valid_assoc_modes) . ' %rRemember to run discovery for the host afterwards.%n ' diff --git a/adduser.php b/adduser.php index 21f368d755..d456cf8ce5 100755 --- a/adduser.php +++ b/adduser.php @@ -22,8 +22,7 @@ require 'includes/functions.php'; if (file_exists('html/includes/authentication/'.$config['auth_mechanism'].'.inc.php')) { include 'html/includes/authentication/'.$config['auth_mechanism'].'.inc.php'; -} -else { +} else { echo "ERROR: no valid auth_mechanism defined.\n"; exit(); } @@ -34,15 +33,12 @@ if (auth_usermanagement()) { if (adduser($argv[1], $argv[2], $argv[3], @$argv[4])) { echo 'User '.$argv[1]." added successfully\n"; } - } - else { + } else { echo 'User '.$argv[1]." already exists!\n"; } - } - else { + } else { echo "Add User Tool\nUsage: ./adduser.php [email]\n"; } -} -else { +} else { echo "Auth module does not allow adding users!\n"; }//end if diff --git a/alerts.php b/alerts.php index 185ff1047b..143a6fcb0c 100755 --- a/alerts.php +++ b/alerts.php @@ -41,8 +41,7 @@ if (file_exists($config['install_dir'].'/.alerts.lock')) { if ($lock === true) { exit(1); -} -else { +} else { file_put_contents($config['install_dir'].'/.alerts.lock', getmypid()); } @@ -57,8 +56,7 @@ if (isset($options['d'])) { ini_set('display_startup_errors', 1); ini_set('log_errors', 1); ini_set('error_reporting', 1); -} -else { +} else { $debug = false; // ini_set('display_errors', 0); ini_set('display_startup_errors', 0); @@ -86,7 +84,8 @@ unlink($config['install_dir'].'/.alerts.lock'); * @param integer $rule Rule-ID * @return boolean */ -function IsRuleValid($device, $rule) { +function IsRuleValid($device, $rule) +{ global $rulescache; if (empty($rulescache[$device]) || !isset($rulescache[$device])) { foreach (GetRules($device) as $chk) { @@ -99,7 +98,6 @@ function IsRuleValid($device, $rule) { } return false; - }//end IsRuleValid() @@ -108,7 +106,8 @@ function IsRuleValid($device, $rule) { * @param array $alert * @return boolean */ -function IssueAlert($alert) { +function IssueAlert($alert) +{ global $config; if (dbFetchCell('SELECT attrib_value FROM devices_attribs WHERE attrib_type = "disable_notify" && device_id = ?', array($alert['device_id'])) == '1') { return true; @@ -129,7 +128,6 @@ function IssueAlert($alert) { } return true; - }//end IssueAlert() @@ -137,7 +135,8 @@ function IssueAlert($alert) { * Issue ACK notification * @return void */ -function RunAcks() { +function RunAcks() +{ foreach (dbFetchRows('SELECT alerts.device_id, alerts.rule_id, alerts.state FROM alerts WHERE alerts.state = 2 && alerts.open = 1') as $alert) { $tmp = array( $alert['rule_id'], @@ -156,7 +155,6 @@ function RunAcks() { IssueAlert($alert); dbUpdate(array('open' => 0), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id'])); } - }//end RunAcks() @@ -164,7 +162,8 @@ function RunAcks() { * Run Follow-Up alerts * @return void */ -function RunFollowUp() { +function RunFollowUp() +{ global $config; foreach (dbFetchRows('SELECT alerts.device_id, alerts.rule_id, alerts.state FROM alerts WHERE alerts.state != 2 && alerts.state > 0 && alerts.open = 0') as $alert) { $tmp = array( @@ -193,12 +192,11 @@ function RunFollowUp() { if ($n > $o) { $ret .= ' Worsens'; $state = 3; - $alert['details']['diff'] = array_diff($chk,$alert['details']['rule']); - } - elseif ($n < $o) { + $alert['details']['diff'] = array_diff($chk, $alert['details']['rule']); + } elseif ($n < $o) { $ret .= ' Betters'; $state = 4; - $alert['details']['diff'] = array_diff($alert['details']['rule'],$chk); + $alert['details']['diff'] = array_diff($alert['details']['rule'], $chk); } if ($state > 0 && $n > 0) { @@ -210,7 +208,6 @@ function RunFollowUp() { echo $ret.' ('.$o.'/'.$n.")\r\n"; } }//end foreach - }//end RunFollowUp() @@ -218,7 +215,8 @@ function RunFollowUp() { * Run all alerts * @return void */ -function RunAlerts() { +function RunAlerts() +{ global $config; foreach (dbFetchRows('SELECT alerts.device_id, alerts.rule_id, alerts.state FROM alerts WHERE alerts.state != 2 && alerts.open = 1') as $alert) { $tmp = array( @@ -248,8 +246,7 @@ function RunAlerts() { if (!empty($rextra['delay'])) { if ((time() - strtotime($alert['time_logged']) + $config['alert']['tolerance_window']) < $rextra['delay'] || (!empty($alert['details']['delay']) && (time() - $alert['details']['delay'] + $config['alert']['tolerance_window']) < $rextra['delay'])) { continue; - } - else { + } else { $alert['details']['delay'] = time(); $updet = true; } @@ -263,8 +260,7 @@ function RunAlerts() { $updet = true; $noiss = false; } - } - else { + } else { // This is the new way if (!empty($rextra['delay']) && (time() - strtotime($alert['time_logged']) + $config['alert']['tolerance_window']) < $rextra['delay']) { continue; @@ -273,8 +269,7 @@ function RunAlerts() { if (!empty($rextra['interval'])) { if (!empty($alert['details']['interval']) && (time() - $alert['details']['interval'] + $config['alert']['tolerance_window']) < $rextra['interval']) { continue; - } - else { + } else { $alert['details']['interval'] = time(); $updet = true; } @@ -318,7 +313,6 @@ function RunAlerts() { dbUpdate(array('open' => 0), 'alerts', 'rule_id = ? && device_id = ?', array($alert['rule_id'], $alert['device_id'])); } }//end foreach - }//end RunAlerts() @@ -327,7 +321,8 @@ function RunAlerts() { * @param array $obj Alert-Array * @return void */ -function ExtTransports($obj) { +function ExtTransports($obj) +{ global $config; $tmp = false; // To keep scrutinizer from naging because it doesnt understand eval @@ -348,12 +343,10 @@ function ExtTransports($obj) { if ($tmp === true) { echo 'OK'; log_event('Issued '.$prefix[$obj['state']]." for rule '".$obj['name']."' to transport '".$transport."'", $obj['device_id']); - } - elseif ($tmp === false) { + } elseif ($tmp === false) { echo 'ERROR'; log_event('Could not issue '.$prefix[$obj['state']]." for rule '".$obj['name']."' to transport '".$transport."'", $obj['device_id']); - } - else { + } else { echo 'ERROR: '.$tmp."\r\n"; log_event('Could not issue '.$prefix[$obj['state']]." for rule '".$obj['name']."' to transport '".$transport."' Error: ".$tmp, $obj['device_id']); } @@ -361,7 +354,6 @@ function ExtTransports($obj) { echo '; '; } - }//end ExtTransports() @@ -370,7 +362,8 @@ function ExtTransports($obj) { * @param array $obj Alert-Array * @return string */ -function FormatAlertTpl($obj) { +function FormatAlertTpl($obj) +{ $tpl = $obj["template"]; $msg = '$ret .= "'.str_replace(array('{else}', '{/if}', '{/foreach}'), array('"; } else { $ret .= "', '"; } $ret .= "', '"; } $ret .= "'), addslashes($tpl)).'";'; $parsed = $msg; @@ -381,23 +374,19 @@ function FormatAlertTpl($obj) { while (++$x < $s) { if ($msg[$x] == '{' && $buff == '') { $buff .= $msg[$x]; - } - elseif ($buff == '{ ') { + } elseif ($buff == '{ ') { $buff = ''; - } - elseif ($buff != '') { + } elseif ($buff != '') { $buff .= $msg[$x]; } if ($buff == '{if') { $pos = $x; $if = true; - } - elseif ($buff == '{foreach') { + } elseif ($buff == '{foreach') { $pos = $x; $for = true; - } - elseif ($buff == '{calc') { + } elseif ($buff == '{calc') { $pos = $x; $calc = true; } @@ -413,24 +402,21 @@ function FormatAlertTpl($obj) { '"; if( ', ' ) { $ret .= "', ); - } - elseif ($for) { + } elseif ($for) { $for = false; $o = 8; $native = array( '"; foreach( ', ' as $key=>$value) { $ret .= "', ); - } - elseif ($calc) { + } elseif ($calc) { $calc = false; $o = 5; $native = array( '"; $ret .= (float) (0+(', ')); $ret .= "', ); - } - else { + } else { continue; } @@ -443,7 +429,6 @@ function FormatAlertTpl($obj) { $parsed = populate($parsed); return RunJail($parsed, $obj); - }//end FormatAlertTpl() @@ -452,7 +437,8 @@ function FormatAlertTpl($obj) { * @param array $alert Alert-Result from DB * @return array */ -function DescribeAlert($alert) { +function DescribeAlert($alert) +{ $obj = array(); $i = 0; $device = dbFetchRow('SELECT hostname, sysName, location, uptime FROM devices WHERE device_id = ?', array($alert['device_id'])); @@ -472,17 +458,14 @@ function DescribeAlert($alert) { if ($alert['state'] >= 1) { if (!empty($tpl['title'])) { $obj['title'] = $tpl['title']; - } - else { + } else { $obj['title'] = 'Alert for device '.$device['hostname'].' - '.($alert['name'] ? $alert['name'] : $alert['rule']); } if ($alert['state'] == 2) { $obj['title'] .= ' got acknowledged'; - } - elseif ($alert['state'] == 3) { + } elseif ($alert['state'] == 3) { $obj['title'] .= ' got worse'; - } - elseif ($alert['state'] == 4) { + } elseif ($alert['state'] == 4) { $obj['title'] .= ' got better'; } @@ -496,11 +479,10 @@ function DescribeAlert($alert) { } } $obj['elapsed'] = TimeFormat(time() - strtotime($alert['time_logged'])); - if( !empty($extra['diff']) ) { + if (!empty($extra['diff'])) { $obj['diff'] = $extra['diff']; } - } - elseif ($alert['state'] == 0) { + } elseif ($alert['state'] == 0) { $id = dbFetchRow('SELECT alert_log.id,alert_log.time_logged,alert_log.details FROM alert_log WHERE alert_log.state != 2 && alert_log.state != 0 && alert_log.rule_id = ? && alert_log.device_id = ? && alert_log.id < ? ORDER BY id DESC LIMIT 1', array($alert['rule_id'], $alert['device_id'], $alert['id'])); if (empty($id['id'])) { return false; @@ -509,15 +491,13 @@ function DescribeAlert($alert) { $extra = json_decode(gzuncompress($id['details']), true); if (!empty($tpl['title_rec'])) { $obj['title'] = $tpl['title_rec']; - } - else { + } else { $obj['title'] = 'Device '.$device['hostname'].' recovered from '.($alert['name'] ? $alert['name'] : $alert['rule']); } $obj['elapsed'] = TimeFormat(strtotime($alert['time_logged']) - strtotime($id['time_logged'])); $obj['id'] = $id['id']; $obj['faults'] = false; - } - else { + } else { return 'Unknown State'; }//end if $obj['uid'] = $alert['id']; @@ -527,11 +507,10 @@ function DescribeAlert($alert) { $obj['timestamp'] = $alert['time_logged']; $obj['contacts'] = $extra['contacts']; $obj['state'] = $alert['state']; - if (strstr($obj['title'],'%')) { + if (strstr($obj['title'], '%')) { $obj['title'] = RunJail('$ret = "'.populate(addslashes($obj['title'])).'";', $obj); } return $obj; - }//end DescribeAlert() @@ -540,7 +519,8 @@ function DescribeAlert($alert) { * @param integer $secs Seconds elapsed * @return string */ -function TimeFormat($secs) { +function TimeFormat($secs) +{ $bit = array( 'y' => $secs / 31556926 % 12, 'w' => $secs / 604800 % 52, @@ -561,7 +541,6 @@ function TimeFormat($secs) { } return join(' ', $ret); - }//end TimeFormat() @@ -571,11 +550,11 @@ function TimeFormat($secs) { * @param array $obj Object with variables * @return string|mixed */ -function RunJail($code, $obj) { +function RunJail($code, $obj) +{ $ret = ''; eval($code); return $ret; - }//end RunJail() @@ -585,21 +564,20 @@ function RunJail($code, $obj) { * @param boolean $wrap Wrap variable for text-usage (default: true) * @return string */ -function populate($txt, $wrap=true) { +function populate($txt, $wrap = true) +{ preg_match_all('/%([\w\.]+)/', $txt, $m); foreach ($m[1] as $tmp) { $orig = $tmp; $rep = false; if ($tmp == 'key' || $tmp == 'value') { $rep = '$'.$tmp; - } - else { + } else { if (strstr($tmp, '.')) { $tmp = explode('.', $tmp, 2); $pre = '$'.$tmp[0]; $tmp = $tmp[1]; - } - else { + } else { $pre = '$obj'; } @@ -613,5 +591,4 @@ function populate($txt, $wrap=true) { }//end foreach return $txt; - }//end populate() diff --git a/billing-calculate.php b/billing-calculate.php index e89e65675a..5ad73352a7 100755 --- a/billing-calculate.php +++ b/billing-calculate.php @@ -60,8 +60,7 @@ foreach (dbFetchRows('SELECT * FROM `bills` ORDER BY `bill_id`') as $bill) { $overuse = ($used - $allowed); $overuse = (($overuse <= 0) ? '0' : $overuse); $percent = round((($rate_data['rate_95th'] / $bill['bill_cdr']) * 100), 2); - } - else if ($bill['bill_type'] == 'quota') { + } elseif ($bill['bill_type'] == 'quota') { $type = 'Quota'; $allowed = $bill['bill_quota']; $used = $rate_data['total_data']; @@ -113,8 +112,7 @@ foreach (dbFetchRows('SELECT * FROM `bills` ORDER BY `bill_id`') as $bill) { dbUpdate($update, 'bill_history', '`bill_hist_id` = ?', array($check['bill_hist_id'])); echo ' Updated history! '; - } - else { + } else { $update = array( 'rate_95th' => $rate_data['rate_95th'], 'rate_95th_in' => $rate_data['rate_95th_in'], diff --git a/build-base.php b/build-base.php index c6135a12c8..3256594a8f 100644 --- a/build-base.php +++ b/build-base.php @@ -29,12 +29,11 @@ if ($select === false) { $limit = 0; while (!feof($sql_fh)) { $line = fgetss($sql_fh); - if (isset($_SESSION['stage']) ) { + if (isset($_SESSION['stage'])) { $limit++; if (isset($_SESSION['offset']) && $limit < $_REQUEST['offset']) { continue; - } - elseif ( time()-$_SESSION['last'] > 45 ) { + } elseif (time()-$_SESSION['last'] > 45) { $_SESSION['offset'] = $limit; $GLOBALS['refresh'] = 'Installing, please wait..'.date('r').''; return; diff --git a/check-services.php b/check-services.php index d2aec7fc65..ee2ab28a64 100755 --- a/check-services.php +++ b/check-services.php @@ -51,6 +51,5 @@ rrdtool_initialize(); foreach (dbFetchRows('SELECT * FROM `devices` AS D, `services` AS S WHERE S.device_id = D.device_id ORDER by D.device_id DESC') as $service) { // Run the polling function poll_service($service); - } //end foreach rrdtool_close(); diff --git a/config_to_json.php b/config_to_json.php index 5d5b0a4d79..789e3b9686 100644 --- a/config_to_json.php +++ b/config_to_json.php @@ -12,14 +12,13 @@ $config_file = 'config.php'; // move to install dir chdir(dirname($argv[0])); -function iscli() { +function iscli() +{ if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) { return true; - } - else { + } else { return false; } - } // check if we are running through the CLI, otherwise abort diff --git a/daily.php b/daily.php index 4f3292ec8a..a18d4525d6 100644 --- a/daily.php +++ b/daily.php @@ -24,8 +24,7 @@ if ($options['f'] === 'update') { if ($config['update_channel'] == 'master') { exit(1); - } - elseif ($config['update_channel'] == 'release') { + } elseif ($config['update_channel'] == 'release') { exit(3); } exit(0); @@ -54,8 +53,7 @@ if ($options['f'] === 'syslog') { if (dbDelete('syslog', 'seq >= ? AND seq < ? AND timestamp < DATE_SUB(NOW(), INTERVAL ? DAY)', array($rows, $limit, $config['syslog_purge'])) > 0) { $rows = $limit; echo 'Syslog cleared for entries over '.$config['syslog_purge']." days 1000 limit\n"; - } - else { + } else { break; } } @@ -145,8 +143,8 @@ if ($options['f'] === 'purgeusers') { foreach (dbFetchRows("SELECT DISTINCT(`user`) FROM `authlog` WHERE `datetime` >= DATE_SUB(NOW(), INTERVAL ? DAY)", array($purge)) as $user) { $users[] = $user['user']; } - $del_users = '"'.implode('","',$users).'"'; - if (dbDelete('users', "username NOT IN ($del_users)",array($del_users))) { + $del_users = '"'.implode('","', $users).'"'; + if (dbDelete('users', "username NOT IN ($del_users)", array($del_users))) { echo "Removed users that haven't logged in for $purge days"; } } diff --git a/delhost.php b/delhost.php index 38ea772ad4..b45009844b 100755 --- a/delhost.php +++ b/delhost.php @@ -25,11 +25,9 @@ if ($argv[1]) { $id = getidbyname($host); if ($id) { echo delete_device($id)."\n"; - } - else { + } else { echo "Host doesn't exist!\n"; } -} -else { +} else { echo "Host Removal Tool\nUsage: ./delhost.php \n"; } diff --git a/discovery.php b/discovery.php index 86f3c11567..bafd95adc2 100755 --- a/discovery.php +++ b/discovery.php @@ -23,7 +23,7 @@ require 'includes/discovery/functions.inc.php'; $start = microtime(true); $runtime_stats = array(); $sqlparams = array(); -$options = getopt('h:m:i:n:d::v::a::q',array('os:','type:')); +$options = getopt('h:m:i:n:d::v::a::q', array('os:','type:')); if (!isset($options['q'])) { echo $config['project_name_version']." Discovery\n"; @@ -42,25 +42,20 @@ if (isset($options['h'])) { if ($options['h'] == 'odd') { $options['n'] = '1'; $options['i'] = '2'; - } - else if ($options['h'] == 'even') { + } elseif ($options['h'] == 'even') { $options['n'] = '0'; $options['i'] = '2'; - } - else if ($options['h'] == 'all') { + } elseif ($options['h'] == 'all') { $where = ' '; $doing = 'all'; - } - else if ($options['h'] == 'new') { + } elseif ($options['h'] == 'new') { $where = 'AND `last_discovered` IS NULL'; $doing = 'new'; - } - else if ($options['h']) { + } elseif ($options['h']) { if (is_numeric($options['h'])) { $where = "AND `device_id` = '".$options['h']."'"; $doing = $options['h']; - } - else { + } else { $where = "AND `hostname` LIKE '".str_replace('*', '%', mres($options['h']))."'"; $doing = $options['h']; } @@ -92,8 +87,7 @@ if (isset($options['d']) || isset($options['v'])) { ini_set('display_startup_errors', 1); ini_set('log_errors', 1); ini_set('error_reporting', 1); -} -else { +} else { $debug = false; // ini_set('display_errors', 0); ini_set('display_startup_errors', 0); @@ -129,7 +123,7 @@ if (!empty($config['distributed_poller_group'])) { $where .= ' AND poller_group IN('.$config['distributed_poller_group'].')'; } -foreach (dbFetch("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 $where ORDER BY device_id DESC",$sqlparams) as $device) { +foreach (dbFetch("SELECT * FROM `devices` WHERE status = 1 AND disabled = 0 $where ORDER BY device_id DESC", $sqlparams) as $device) { discover_device($device, $options); } diff --git a/dist-pollers.php b/dist-pollers.php index 1e3934ffcc..24f314a32c 100755 --- a/dist-pollers.php +++ b/dist-pollers.php @@ -33,8 +33,7 @@ if (isset($options['l'])) { } echo $tbl->getTable(); - } - else if ($options['l'] == 'groups') { + } elseif ($options['l'] == 'groups') { $tbl = new Console_Table(); $tbl->setHeaders(array('ID', 'Group Name', 'Description')); foreach (dbFetchRows('SELECT * FROM `poller_groups`') as $groups) { @@ -43,25 +42,21 @@ if (isset($options['l'])) { echo $tbl->getTable(); } -} -else if (isset($options['u']) && !empty($options['u'])) { +} elseif (isset($options['u']) && !empty($options['u'])) { if (is_numeric($options['u'])) { $db_column = 'id'; - } - else { + } else { $db_column = 'poller_name'; } if (dbDelete('pollers', "`$db_column` = ?", array($options['u'])) >= 0) { echo 'Poller '.$options['u']." has been removed\n"; } -} -else if (isset($options['r'])) { +} elseif (isset($options['r'])) { if (dbInsert(array('poller_name' => $config['distributed_poller_name'], 'last_polled' => '0000-00-00 00:00:00', 'devices' => 0, 'time_taken' => 0), 'pollers') >= 0) { echo 'Poller '.$config['distributed_poller_name']." has been registered\n"; } -} -else { +} else { echo "-l pollers | groups List registered pollers or poller groups\n"; echo "-u | Unregister a poller\n"; echo "-r Register this install as a poller\n"; diff --git a/poll-billing.php b/poll-billing.php index 55ece83b25..7bb1f0e06b 100755 --- a/poll-billing.php +++ b/poll-billing.php @@ -49,7 +49,8 @@ foreach (dbFetchRows('SELECT * FROM `bills`') as $bill_data) { } -function CollectData($bill_id) { +function CollectData($bill_id) +{ $port_list = dbFetchRows('SELECT * FROM `bill_ports` as P, `ports` as I, `devices` as D WHERE P.bill_id=? AND I.port_id = P.port_id AND D.device_id = I.device_id', array($bill_id)); $now = dbFetchCell('SELECT NOW()'); @@ -77,25 +78,20 @@ function CollectData($bill_id) { if ($port_data['ifSpeed'] > 0 && (delta_to_bits($port_data['in_measurement'], $tmp_period)-delta_to_bits($port_data['last_in_measurement'], $tmp_period)) > $port_data['ifSpeed']) { $port_data['in_delta'] = $port_data['last_in_delta']; - } - elseif ($port_data['in_measurement'] >= $port_data['last_in_measurement']) { + } elseif ($port_data['in_measurement'] >= $port_data['last_in_measurement']) { $port_data['in_delta'] = ($port_data['in_measurement'] - $port_data['last_in_measurement']); - } - else { + } else { $port_data['in_delta'] = $port_data['last_in_delta']; } if ($port_data['ifSpeed'] > 0 && (delta_to_bits($port_data['out_measurement'], $tmp_period)-delta_to_bits($port_data['last_out_measurement'], $tmp_period)) > $port_data['ifSpeed']) { $port_data['out_delta'] = $port_data['last_out_delta']; - } - elseif ($port_data['out_measurement'] >= $port_data['last_out_measurement']) { + } elseif ($port_data['out_measurement'] >= $port_data['last_out_measurement']) { $port_data['out_delta'] = ($port_data['out_measurement'] - $port_data['last_out_measurement']); - } - else { + } else { $port_data['out_delta'] = $port_data['last_out_delta']; } - } - else { + } else { $port_data['in_delta'] = '0'; $port_data['out_delta'] = '0'; } @@ -120,8 +116,7 @@ function CollectData($bill_id) { $prev_out_delta = $last_data[out_delta]; $prev_timestamp = $last_data[timestamp]; $period = dbFetchCell("SELECT UNIX_TIMESTAMP(CURRENT_TIMESTAMP()) - UNIX_TIMESTAMP('".mres($prev_timestamp)."')"); - } - else { + } else { $prev_delta = '0'; $period = '0'; $prev_in_delta = '0'; @@ -136,11 +131,9 @@ function CollectData($bill_id) { if (!empty($period) && $period < '0') { logfile("BILLING: negative period! id:$bill_id period:$period delta:$delta in_delta:$in_delta out_delta:$out_delta"); - } - else { + } else { dbInsert(array('bill_id' => $bill_id, 'timestamp' => $now, 'period' => $period, 'delta' => $delta, 'in_delta' => $in_delta, 'out_delta' => $out_delta), 'bill_data'); } - }//end CollectData() diff --git a/poller.php b/poller.php index 0868dde869..5af545b91b 100755 --- a/poller.php +++ b/poller.php @@ -39,21 +39,17 @@ $options = getopt('h:m:i:n:r::d::v::a::f::'); if ($options['h'] == 'odd') { $options['n'] = '1'; $options['i'] = '2'; -} -else if ($options['h'] == 'even') { +} elseif ($options['h'] == 'even') { $options['n'] = '0'; $options['i'] = '2'; -} -else if ($options['h'] == 'all') { +} elseif ($options['h'] == 'all') { $where = ' '; $doing = 'all'; -} -else if ($options['h']) { +} elseif ($options['h']) { if (is_numeric($options['h'])) { $where = "AND `device_id` = '".$options['h']."'"; $doing = $options['h']; - } - else { + } else { $where = "AND `hostname` LIKE '".str_replace('*', '%', mres($options['h']))."'"; $doing = $options['h']; } @@ -101,8 +97,7 @@ if (isset($options['d']) || isset($options['v'])) { ini_set('display_startup_errors', 1); ini_set('log_errors', 1); ini_set('error_reporting', 1); -} -else { +} else { $debug = false; // ini_set('display_errors', 0); ini_set('display_startup_errors', 0); @@ -120,8 +115,7 @@ if (isset($options['f'])) { if ($config['noinfluxdb'] !== true && $config['influxdb']['enable'] === true) { $influxdb = influxdb_connect(); -} -else { +} else { $influxdb = false; } diff --git a/renamehost.php b/renamehost.php index e1a369eed0..ebd859c74f 100755 --- a/renamehost.php +++ b/renamehost.php @@ -28,16 +28,13 @@ if ($argv[1] && $argv[2]) { $toid = getidbyname($tohost); if ($toid) { echo "NOT renamed. New hostname $tohost already exists.\n"; - } - else { + } else { renamehost($id, $tohost, 'console'); echo "Renamed $host\n"; } - } - else { + } else { echo "Host doesn't exist!\n"; } -} -else { +} else { echo "Host Rename Tool\nUsage: ./renamehost.php \n"; } diff --git a/scripts/console-ui.php b/scripts/console-ui.php index 0fa0d6e31b..ede19c8ecf 100755 --- a/scripts/console-ui.php +++ b/scripts/console-ui.php @@ -20,7 +20,6 @@ while ($end == 0) { passthru('clear'); $tbl = new Console_Table(CONSOLE_TABLE_ALIGN_RIGHT); foreach (dbFetchRows('SELECT * FROM `devices` ORDER BY `hostname`') as $device) { - $devices['count']++; $cache['devices']['hostname'][$device['hostname']] = $device['device_id']; @@ -51,8 +50,7 @@ while ($end == 0) { } echo $tbl->getTable(); - } - else if ($options['l'] == 'syslog') { + } elseif ($options['l'] == 'syslog') { $tbl = new Console_Table(); $tbl->setHeaders(array('Date time', 'Host', 'Program', 'Message', 'Level', 'Facility')); if (is_numeric($options['d'])) { @@ -65,8 +63,7 @@ while ($end == 0) { } echo $tbl->getTable(); - } - else if ($options['list'] == 'devices') { + } elseif ($options['list'] == 'devices') { $tbl = new Console_Table(); $tbl->setHeaders(array('Device ID', 'Device Hostname')); $query = 'SELECT device_id,hostname FROM `devices` ORDER BY hostname'; @@ -76,8 +73,7 @@ while ($end == 0) { echo $tbl->getTable(); exit; - } - else if (isset($options['device-stats'])) { + } elseif (isset($options['device-stats'])) { $tbl = new Console_Table(); $tbl->setHeaders(array('Port name', 'Status', 'IPv4 Address', 'Speed In', 'Speed Out', 'Packets In', 'Packets Out', 'Speed', 'Duplex', 'Type', 'MAC Address', 'MTU')); foreach (dbFetchRows('SELECT * FROM `ports` WHERE `device_id` = ?', array($options['d'])) as $port) { @@ -108,8 +104,7 @@ while ($end == 0) { }//end foreach echo $tbl->getTable(); - } - else { + } else { echo $options['list']; echo "Usage of console-ui.php: diff --git a/scripts/gen_smokeping.php b/scripts/gen_smokeping.php index 5763f7349e..b061a4d368 100755 --- a/scripts/gen_smokeping.php +++ b/scripts/gen_smokeping.php @@ -28,7 +28,7 @@ foreach (dbFetchRows("SELECT `type` FROM `devices` WHERE `ignore` = 0 AND `disab echo 'title = ' . $groups['type'] . PHP_EOL; foreach (dbFetchRows("SELECT `hostname` FROM `devices` WHERE `type` = ? AND `ignore` = 0 AND `disabled` = 0", array($groups['type'])) as $devices) { //Dot needs to be replaced, since smokeping doesn't accept it at this level - echo '++ ' . str_replace(".","_",$devices['hostname']) . PHP_EOL; + echo '++ ' . str_replace(".", "_", $devices['hostname']) . PHP_EOL; echo 'menu = ' . $devices['hostname'] . PHP_EOL; echo 'title = ' . $devices['hostname'] . PHP_EOL; echo 'host = ' . $devices['hostname'] . PHP_EOL . PHP_EOL; diff --git a/scripts/pre-commit.php b/scripts/pre-commit.php index 37ce5ab42b..291ff7c3fb 100755 --- a/scripts/pre-commit.php +++ b/scripts/pre-commit.php @@ -120,7 +120,7 @@ function check_style($passthru = false, $command_only = false) ); $cs_exclude = build_excludes('--ignore=', $cs_excludes); - $cs_cmd = "./vendor/bin/phpcs -n -p --colors --extensions=php --standard=PSR2 $cs_exclude ./html ./includes"; + $cs_cmd = "./vendor/bin/phpcs -n -p --colors --extensions=php --standard=PSR2 $cs_exclude ./"; if ($command_only) { echo $cs_cmd . PHP_EOL; diff --git a/scripts/removespikes.php b/scripts/removespikes.php index 9736b24c5e..afb2da4257 100755 --- a/scripts/removespikes.php +++ b/scripts/removespikes.php @@ -1,841 +1,903 @@ -#!/usr/bin/php -q -This script is only meant to run at the command line."); -} - -/* We are not talking to the browser */ -$no_http_headers = true; - -$dir = dirname(__FILE__); -chdir($dir); - -if (strpos($dir, 'spikekill') !== false) { - chdir('../../'); -} - -$using_cacti = false; - -/* setup defaults */ -$debug = FALSE; -$dryrun = FALSE; -$avgnan = 'avg'; -$rrdfile = ""; -$std_kills = TRUE; -$var_kills = TRUE; -$html = FALSE; - -if ($using_cacti) { - $method = read_config_option("spikekill_method"); - $numspike = read_config_option("spikekill_number"); - $stddev = read_config_option("spikekill_deviations"); - $percent = read_config_option("spikekill_percent"); - $outliers = read_config_option("spikekill_outliers"); -}else{ - $method = 1; // Standard Deviation - $numspike = 10; - $stddev = 10; - $percent = 500; - $outliers = 5; -} - -/* process calling arguments */ -$parms = $_SERVER["argv"]; -array_shift($parms); - -foreach($parms as $parameter) { - @list($arg, $value) = @explode("=", $parameter); - - switch ($arg) { - case "--method": - case "-M": - if ($value == "variance") { - $method = 2; - }elseif ($value == "stddev") { - $method = 1; - }else{ - echo "FATAL: You must specify either 'stddev' or 'variance' as methods.\n\n"; - display_help(); - exit; - } - - break; - case "--avgnan": - case "-A": - if ($value == "avg") { - $avgnan = "avg"; - }elseif ($value == "nan") { - $avgnan = "nan"; - }else{ - echo "FATAL: You must specify either 'avg' or 'nan' as replacement methods.\n\n"; - display_help(); - exit; - } - - break; - case "--rrdfile": - case "-R": - $rrdfile = $value; - - if (!file_exists($rrdfile)) { - echo "FATAL: File '$rrdfile' does not exist.\n"; - exit; - } - - if (!is_writable($rrdfile)) { - echo "FATAL: File '$rrdfile' is not writable by this account.\n"; - exit; - } - - break; - case "--stddev": - case "-S": - $stddev = $value; - - if (!is_numeric($stddev) || ($stddev < 1)) { - echo "FATAL: Standard Deviation must be a positive integer.\n\n"; - display_help(); - exit; - } - - break; - case "--outliers": - case "-O": - $outliers = $value; - - if (!is_numeric($outliers) || ($outliers < 1)) { - echo "FATAL: The number of outliers to exlude must be a positive integer.\n\n"; - display_help(); - exit; - } - - break; - case "--percent": - case "-P": - $percent = $value/100; - - if (!is_numeric($percent) || ($percent <= 0)) { - echo "FATAL: Percent deviation must be a positive floating point number.\n\n"; - display_help(); - exit; - } - - break; - case "--html": - $html = TRUE; - - break; - case "-d": - case "--debug": - $debug = TRUE; - - break; - case "-D": - case "--dryrun": - $dryrun = TRUE; - - break; - case "--number": - case "-n": - $numspike = $value; - - if (!is_numeric($numspike) || ($numspike < 1)) { - echo "FATAL: Number of spikes to remove must be a positive integer\n\n"; - display_help(); - exit; - } - - break; - case "-h": - case "-v": - case "-V": - case "--version": - case "--help": - display_help(); - exit; - default: - print "ERROR: Invalid Parameter " . $parameter . "\n\n"; - display_help(); - exit; - } -} - -/* additional error check */ -if ($rrdfile == "") { - echo "FATAL: You must specify an RRDfile!\n\n"; - display_help(); - exit; -} - -/* determine the temporary file name */ -$seed = mt_rand(); -if ($config["cacti_server_os"] == "win32") { - $tempdir = getenv("TEMP"); - $xmlfile = $tempdir . "/" . str_replace(".rrd", "", basename($rrdfile)) . ".dump." . $seed; -}else{ - $tempdir = "/tmp"; - $xmlfile = "/tmp/" . str_replace(".rrd", "", basename($rrdfile)) . ".dump." . $seed; -} - -if ($html) { - echo ""; -} - -if ($using_cacti) { - cacti_log("NOTE: Removing Spikes for '$rrdfile', Method:'$method'", false, "WEBUI"); -} - -/* execute the dump command */ -echo ($html ? "\n":"\n"); - -if ($using_cacti) { - shell_exec(read_config_option("path_rrdtool") . " dump $rrdfile > $xmlfile"); -}else{ - shell_exec("rrdtool dump $rrdfile > $xmlfile"); -} - -/* read the xml file into an array*/ -if (file_exists($xmlfile)) { - $output = file($xmlfile); - - /* remove the temp file */ - unlink($xmlfile); -}else{ - if ($using_cacti) { - echo ($html ? "\n":"\n"); - }else{ - echo ($html ? "\n":"\n"); - } - exit; -} - -/* process the xml file and remove all comments */ -$output = removeComments($output); - -/* Read all the rra's ds values and obtain the following pieces of information from each - rra archive. - - * numsamples - The number of 'valid' non-nan samples - * sumofsamples - The sum of all 'valid' samples. - * average - The average of all samples - * standard_deviation - The standard deviation of all samples - * max_value - The maximum value of all samples - * min_value - The minimum value of all samples - * max_cutoff - Any value above this value will be set to the average. - * min_cutoff - Any value lower than this value will be set to the average. - - This will end up being a n-dimensional array as follows: - rra[x][ds#]['totalsamples']; - rra[x][ds#]['numsamples']; - rra[x][ds#]['sumofsamples']; - rra[x][ds#]['average']; - rra[x][ds#]['stddev']; - rra[x][ds#]['max_value']; - rra[x][ds#]['min_value']; - rra[x][ds#]['max_cutoff']; - rra[x][ds#]['min_cutoff']; - - There will also be a secondary array created with the actual samples. This - array will be used to calculate the standard deviation of the sample set. - samples[rra_num][ds_num][]; - - Also track the min and max value for each ds and store it into the two - arrays: ds_min[ds#], ds_max[ds#]. - - The we don't need to know the type of rra, only it's number for this analysis - the same applies for the ds' as well. -*/ -$rra = array(); -$rra_cf = array(); -$rra_pdp = array(); -$rra_num = 0; -$ds_num = 0; -$total_kills = 0; -$in_rra = false; -$in_db = false; -$ds_min = array(); -$ds_max = array(); -$ds_name = array(); - -/* perform a first pass on the array and do the following: - 1) Get the number of good samples per ds - 2) Get the sum of the samples per ds - 3) Get the max and min values for all samples - 4) Build both the rra and sample arrays - 5) Get each ds' min and max values -*/ -if (sizeof($output)) { -foreach($output as $line) { - if (substr_count($line, "")) { - $linearray = explode("", $line); - /* discard the row */ - array_shift($linearray); - $ds_num = 0; - foreach($linearray as $dsvalue) { - /* peel off garbage */ - $dsvalue = trim(str_replace("", "", str_replace("", "", $dsvalue))); - if (strtolower($dsvalue) != "nan") { - if (!isset($rra[$rra_num][$ds_num]["numsamples"])) { - $rra[$rra_num][$ds_num]["numsamples"] = 1; - }else{ - $rra[$rra_num][$ds_num]["numsamples"]++; - } - - if (!isset($rra[$rra_num][$ds_num]["sumofsamples"])) { - $rra[$rra_num][$ds_num]["sumofsamples"] = $dsvalue; - }else{ - $rra[$rra_num][$ds_num]["sumofsamples"] += $dsvalue; - } - - if (!isset($rra[$rra_num][$ds_num]["max_value"])) { - $rra[$rra_num][$ds_num]["max_value"] = $dsvalue; - }else if ($dsvalue > $rra[$rra_num][$ds_num]["max_value"]) { - $rra[$rra_num][$ds_num]["max_value"] = $dsvalue; - } - - if (!isset($rra[$rra_num][$ds_num]["min_value"])) { - $rra[$rra_num][$ds_num]["min_value"] = $dsvalue; - }else if ($dsvalue < $rra[$rra_num][$ds_num]["min_value"]) { - $rra[$rra_num][$ds_num]["min_value"] = $dsvalue; - } - - /* store the sample for standard deviation calculation */ - $samples[$rra_num][$ds_num][] = $dsvalue; - } - - if (!isset($rra[$rra_num][$ds_num]["totalsamples"])) { - $rra[$rra_num][$ds_num]["totalsamples"] = 1; - }else{ - $rra[$rra_num][$ds_num]["totalsamples"]++; - } - - $ds_num++; - } - } elseif (substr_count($line, "")) { - $in_rra = true; - } elseif (substr_count($line, "")) { - $ds_min[] = trim(str_replace("", "", str_replace("", "", trim($line)))); - } elseif (substr_count($line, "")) { - $ds_max[] = trim(str_replace("", "", str_replace("", "", trim($line)))); - } elseif (substr_count($line, "")) { - $ds_name[] = trim(str_replace("", "", str_replace("", "", trim($line)))); - } elseif (substr_count($line, "")) { - $rra_cf[] = trim(str_replace("", "", str_replace("", "", trim($line)))); - } elseif (substr_count($line, "")) { - $rra_pdp[] = trim(str_replace("", "", str_replace("", "", trim($line)))); - } elseif (substr_count($line, "")) { - $in_rra = false; - $rra_num++; - } elseif (substr_count($line, "")) { - $step = trim(str_replace("", "", str_replace("", "", trim($line)))); - } -} -} - -/* For all the samples determine the average with the outliers removed */ -calculateVarianceAverages($rra, $samples); - -/* Now scan the rra array and the samples array and calculate the following - 1) The standard deviation of all samples - 2) The average of all samples per ds - 3) The max and min cutoffs of all samples - 4) The number of kills in each ds based upon the thresholds -*/ -echo ($html ? "\n":"\n"); -calculateOverallStatistics($rra, $samples); - -/* debugging and/or status report */ -if ($debug || $dryrun) { - outputStatistics($rra); -} - -/* create an output array */ -if ($method == 1) { - /* standard deviation subroutine */ - if ($std_kills) { - if (!$dryrun) { - $new_output = updateXML($output, $rra); - } - }else{ - echo ($html ? "\n":"\n"); - } -}else{ - /* variance subroutine */ - if ($var_kills) { - if (!$dryrun) { - $new_output = updateXML($output, $rra); - } - }else{ - echo ($html ? "\n":"\n"); - } -} - -/* finally update the file XML file and Reprocess the RRDfile */ -if (!$dryrun) { - if ($total_kills) { - if (writeXMLFile($new_output, $xmlfile)) { - if (backupRRDFile($rrdfile)) { - createRRDFileFromXML($xmlfile, $rrdfile); - }else{ - echo ($html ? "\n":"\n"); - } - }else{ - echo ($html ? "\n":"\n"); - } - } -}else{ - echo ($html ? "\n":"\n"); -} - -if ($html) { - echo "
":"") . "NOTE: Creating XML file '$xmlfile' from '$rrdfile'" . ($html ? "
":"") . "FATAL: RRDtool Command Failed. Please verify that the RRDtool path is valid in Settings->Paths!" . ($html ? "
":"") . "FATAL: RRDtool Command Failed. Please insure RRDtool is in your path!" . ($html ? "
":"") . "NOTE: Searching for Spikes in XML file '$xmlfile'" . ($html ? "
":"") . "NOTE: NO Standard Deviation Spikes found in '$rrdfile'" . ($html ? "
":"") . "NOTE: NO Variance Spikes found in '$rrdfile'" . ($html ? "
":"") . "FATAL: Unable to backup '$rrdfile'" . ($html ? "
":"") . "FATAL: Unable to write XML file '$xmlfile'" . ($html ? "
":"") . "NOTE: Dryrun requested. No updates performed" . ($html ? "
"; -} - -/* All Functions */ -function createRRDFileFromXML($xmlfile, $rrdfile) { - global $using_cacti, $html; - - /* execute the dump command */ - echo ($html ? "":"") . "NOTE: Re-Importing '$xmlfile' to '$rrdfile'" . ($html ? "\n":"\n"); - if ($using_cacti) { - $response = shell_exec(read_config_option("path_rrdtool") . " restore -f -r $xmlfile $rrdfile"); - }else{ - $response = shell_exec("rrdtool restore -f -r $xmlfile $rrdfile"); - } - if (strlen($response)) echo ($html ? "":"") . $response . ($html ? "\n":"\n"); -} - -function writeXMLFile($output, $xmlfile) { - return file_put_contents($xmlfile, $output); -} - -function backupRRDFile($rrdfile) { - global $using_cacti, $tempdir, $seed, $html; - - if ($using_cacti) { - $backupdir = read_config_option("spikekill_backupdir"); - - if ($backupdir == "") { - $backupdir = $tempdir; - } - }else{ - $backupdir = $tempdir; - } - - if (file_exists($backupdir . "/" . basename($rrdfile))) { - $newfile = basename($rrdfile) . "." . $seed; - }else{ - $newfile = basename($rrdfile); - } - - echo ($html ? "":"") . "NOTE: Backing Up '$rrdfile' to '" . $backupdir . "/" . $newfile . "'" . ($html ? "\n":"\n"); - - return copy($rrdfile, $backupdir . "/" . $newfile); -} - -function calculateVarianceAverages(&$rra, &$samples) { - global $outliers; - - if (sizeof($samples)) { - foreach($samples as $rra_num => $dses) { - if (sizeof($dses)) { - foreach($dses as $ds_num => $ds) { - if (sizeof($ds) < $outliers * 3) { - $rra[$rra_num][$ds_num]["variance_avg"] = "NAN"; - }else{ - rsort($ds, SORT_NUMERIC); - $ds = array_slice($ds, $outliers); - - sort($ds, SORT_NUMERIC); - $ds = array_slice($ds, $outliers); - - $rra[$rra_num][$ds_num]["variance_avg"] = array_sum($ds) / sizeof($ds); - } - } - } - } - } -} - -function calculateOverallStatistics(&$rra, &$samples) { - global $percent, $stddev, $ds_min, $ds_max, $var_kills, $std_kills; - - $rra_num = 0; - if (sizeof($rra)) { - foreach($rra as $dses) { - $ds_num = 0; - - if (sizeof($dses)) { - foreach($dses as $ds) { - if (isset($samples[$rra_num][$ds_num])) { - $rra[$rra_num][$ds_num]["standard_deviation"] = standard_deviation($samples[$rra_num][$ds_num]); - if ($rra[$rra_num][$ds_num]["standard_deviation"] == "NAN") { - $rra[$rra_num][$ds_num]["standard_deviation"] = 0; - } - $rra[$rra_num][$ds_num]["average"] = $rra[$rra_num][$ds_num]["sumofsamples"] / $rra[$rra_num][$ds_num]["numsamples"]; - - $rra[$rra_num][$ds_num]["min_cutoff"] = $rra[$rra_num][$ds_num]["average"] - ($stddev * $rra[$rra_num][$ds_num]["standard_deviation"]); - if ($rra[$rra_num][$ds_num]["min_cutoff"] < $ds_min[$ds_num]) { - $rra[$rra_num][$ds_num]["min_cutoff"] = $ds_min[$ds_num]; - } - - $rra[$rra_num][$ds_num]["max_cutoff"] = $rra[$rra_num][$ds_num]["average"] + ($stddev * $rra[$rra_num][$ds_num]["standard_deviation"]); - if ($rra[$rra_num][$ds_num]["max_cutoff"] > $ds_max[$ds_num]) { - $rra[$rra_num][$ds_num]["max_cutoff"] = $ds_max[$ds_num]; - } - - $rra[$rra_num][$ds_num]["numnksamples"] = 0; - $rra[$rra_num][$ds_num]["sumnksamples"] = 0; - $rra[$rra_num][$ds_num]["avgnksamples"] = 0; - - /* go through values and find cutoffs */ - $rra[$rra_num][$ds_num]["stddev_killed"] = 0; - $rra[$rra_num][$ds_num]["variance_killed"] = 0; - - if (sizeof($samples[$rra_num][$ds_num])) { - foreach($samples[$rra_num][$ds_num] as $sample) { - if (($sample > $rra[$rra_num][$ds_num]["max_cutoff"]) || - ($sample < $rra[$rra_num][$ds_num]["min_cutoff"])) { - debug(sprintf("Std Kill: Value '%.4e', StandardDev '%.4e', StdDevLimit '%.4e'", $sample, $rra[$rra_num][$ds_num]["standard_deviation"], ($rra[$rra_num][$ds_num]["max_cutoff"] * (1+$percent)))); - $rra[$rra_num][$ds_num]["stddev_killed"]++; - $std_kills = true; - }else{ - $rra[$rra_num][$ds_num]["numnksamples"]++; - $rra[$rra_num][$ds_num]["sumnksamples"] += $sample; - } - - if ($rra[$rra_num][$ds_num]["variance_avg"] == "NAN") { - /* not enought samples to calculate */ - }else if ($sample > ($rra[$rra_num][$ds_num]["variance_avg"] * (1+$percent))) { - /* kill based upon variance */ - debug(sprintf("Var Kill: Value '%.4e', VarianceDev '%.4e', VarianceLimit '%.4e'", $sample, $rra[$rra_num][$ds_num]["variance_avg"], ($rra[$rra_num][$ds_num]["variance_avg"] * (1+$percent)))); - $rra[$rra_num][$ds_num]["variance_killed"]++; - $var_kills = true; - } - } - } - - if ($rra[$rra_num][$ds_num]["numnksamples"] > 0) { - $rra[$rra_num][$ds_num]["avgnksamples"] = $rra[$rra_num][$ds_num]["sumnksamples"] / $rra[$rra_num][$ds_num]["numnksamples"]; - } - }else{ - $rra[$rra_num][$ds_num]["standard_deviation"] = "N/A"; - $rra[$rra_num][$ds_num]["average"] = "N/A"; - $rra[$rra_num][$ds_num]["min_cutoff"] = "N/A"; - $rra[$rra_num][$ds_num]["max_cutoff"] = "N/A"; - $rra[$rra_num][$ds_num]["numnksamples"] = "N/A"; - $rra[$rra_num][$ds_num]["sumnksamples"] = "N/A"; - $rra[$rra_num][$ds_num]["avgnksamples"] = "N/A"; - $rra[$rra_num][$ds_num]["stddev_killed"] = "N/A"; - $rra[$rra_num][$ds_num]["variance_killed"] = "N/A"; - $rra[$rra_num][$ds_num]["stddev_killed"] = "N/A"; - $rra[$rra_num][$ds_num]["numnksamples"] = "N/A"; - $rra[$rra_num][$ds_num]["sumnksamples"] = "N/A"; - $rra[$rra_num][$ds_num]["variance_killed"] = "N/A"; - $rra[$rra_num][$ds_num]["avgnksamples"] = "N/A"; - } - - $ds_num++; - } - } - - $rra_num++; - } - } -} - -function outputStatistics($rra) { - global $rra_cf, $rra_name, $ds_name, $rra_pdp, $html; - - if (sizeof($rra)) { - if (!$html) { - echo "\n"; - printf("%10s %16s %10s %7s %7s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n", - "Size", "DataSource", "CF", "Samples", "NonNan", "Avg", "StdDev", - "MaxValue", "MinValue", "MaxStdDev", "MinStdDev", "StdKilled", "VarKilled", "StdDevAvg", "VarAvg"); - printf("%10s %16s %10s %7s %7s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n", - "----------", "---------------", "----------", "-------", "-------", "----------", "----------", "----------", - "----------", "----------", "----------", "----------", "----------", "----------", - "----------"); - foreach($rra as $rra_key => $dses) { - if (sizeof($dses)) { - foreach($dses as $dskey => $ds) { - printf("%10s %16s %10s %7s %7s " . - ($ds["average"] < 1E6 ? "%10s ":"%10.4e ") . - ($ds["standard_deviation"] < 1E6 ? "%10s ":"%10.4e ") . - (isset($ds["max_value"]) ? ($ds["max_value"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . - (isset($ds["min_value"]) ? ($ds["min_value"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . - (isset($ds["max_cutoff"]) ? ($ds["max_cutoff"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . - (isset($ds["min_cutoff"]) ? ($ds["min_cutoff"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . - "%10s %10s " . - (isset($ds["avgnksampled"]) ? ($ds["avgnksamples"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . - (isset($ds["variance_avg"]) ? ($ds["variance_avg"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . "\n", - displayTime($rra_pdp[$rra_key]), - $ds_name[$dskey], - $rra_cf[$rra_key], - $ds["totalsamples"], - (isset($ds["numsamples"]) ? $ds["numsamples"] : "0"), - ($ds["average"] != "N/A" ? round($ds["average"],2) : $ds["average"]), - ($ds["standard_deviation"] != "N/A" ? round($ds["standard_deviation"],2) : $ds["standard_deviation"]), - (isset($ds["max_value"]) ? round($ds["max_value"],2) : "N/A"), - (isset($ds["min_value"]) ? round($ds["min_value"],2) : "N/A"), - ($ds["max_cutoff"] != "N/A" ? round($ds["max_cutoff"],2) : $ds["max_cutoff"]), - ($ds["min_cutoff"] != "N/A" ? round($ds["min_cutoff"],2) : $ds["min_cutoff"]), - $ds["stddev_killed"], - $ds["variance_killed"], - ($ds["avgnksamples"] != "N/A" ? round($ds["avgnksamples"],2) : $ds["avgnksamples"]), - (isset($ds["variance_avg"]) ? round($ds["variance_avg"],2) : "N/A")); - } - } - } - - echo "\n"; - }else{ - printf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", - "Size", "DataSource", "CF", "Samples", "NonNan", "Avg", "StdDev", - "MaxValue", "MinValue", "MaxStdDev", "MinStdDev", "StdKilled", "VarKilled", "StdDevAvg", "VarAvg"); - foreach($rra as $rra_key => $dses) { - if (sizeof($dses)) { - foreach($dses as $dskey => $ds) { - printf("%s%s%s%s%s" . - ($ds["average"] < 1E6 ? "%s":"%.4e") . - ($ds["standard_deviation"] < 1E6 ? "%s":"%.4e") . - (isset($ds["max_value"]) ? ($ds["max_value"] < 1E6 ? "%s":"%.4e") : "%s") . - (isset($ds["min_value"]) ? ($ds["min_value"] < 1E6 ? "%s":"%.4e") : "%s") . - (isset($ds["max_cutoff"]) ? ($ds["max_cutoff"] < 1E6 ? "%s":"%.4e") : "%s") . - (isset($ds["min_cutoff"]) ? ($ds["min_cutoff"] < 1E6 ? "%s":"%.4e") : "%s") . - "%s%s" . - (isset($ds["avgnksampled"]) ? ($ds["avgnksamples"] < 1E6 ? "%s":"%.4e") : "%s") . - (isset($ds["variance_avg"]) ? ($ds["variance_avg"] < 1E6 ? "%s\n":"%.4e\n") : "%s\n") . "\n", - displayTime($rra_pdp[$rra_key]), - $ds_name[$dskey], - $rra_cf[$rra_key], - $ds["totalsamples"], - (isset($ds["numsamples"]) ? $ds["numsamples"] : "0"), - ($ds["average"] != "N/A" ? round($ds["average"],2) : $ds["average"]), - ($ds["standard_deviation"] != "N/A" ? round($ds["standard_deviation"],2) : $ds["standard_deviation"]), - (isset($ds["max_value"]) ? round($ds["max_value"],2) : "N/A"), - (isset($ds["min_value"]) ? round($ds["min_value"],2) : "N/A"), - ($ds["max_cutoff"] != "N/A" ? round($ds["max_cutoff"],2) : $ds["max_cutoff"]), - ($ds["min_cutoff"] != "N/A" ? round($ds["min_cutoff"],2) : $ds["min_cutoff"]), - $ds["stddev_killed"], - $ds["variance_killed"], - ($ds["avgnksamples"] != "N/A" ? round($ds["avgnksamples"],2) : $ds["avgnksamples"]), - (isset($ds["variance_avg"]) ? round($ds["variance_avg"],2) : "N/A")); - } - } - } - } - } -} - -function updateXML(&$output, &$rra) { - global $numspike, $percent, $avgnan, $method, $total_kills; - $new_array = array(); - - /* variance subroutine */ - $rra_num = 0; - $ds_num = 0; - $kills = 0; - - if (sizeof($output)) { - foreach($output as $line) { - if (substr_count($line, "")) { - $linearray = explode("", $line); - /* discard the row */ - array_shift($linearray); - - /* initialize variables */ - $ds_num = 0; - $out_row = ""; - foreach($linearray as $dsvalue) { - /* peel off garbage */ - $dsvalue = trim(str_replace("", "", str_replace("", "", $dsvalue))); - if (strtolower($dsvalue) == "nan") { - /* do nothing, it's a NaN */ - }else{ - if ($method == 2) { - if ($dsvalue > (1+$percent)*$rra[$rra_num][$ds_num]["variance_avg"]) { - if ($kills < $numspike) { - if ($avgnan == "avg") { - $dsvalue = $rra[$rra_num][$ds_num]["variance_avg"]; - }else{ - $dsvalue = "NaN"; - } - $kills++; - $total_kills++; - } - } - }else{ - if (($dsvalue > $rra[$rra_num][$ds_num]["max_cutoff"]) || - ($dsvalue < $rra[$rra_num][$ds_num]["min_cutoff"])) { - if ($kills < $numspike) { - if ($avgnan == "avg") { - $dsvalue = $rra[$rra_num][$ds_num]["average"]; - }else{ - $dsvalue = "NaN"; - } - $kills++; - $total_kills++; - } - } - } - } - - $out_row .= " " . $dsvalue . ""; - $ds_num++; - } - - $out_row .= ""; - - $new_array[] = $out_row; - }else{ - if (substr_count($line, "")) { - $ds_minmax = array(); - $rra_num++; - $kills = 0; - }else if (substr_count($line, "")) { - $ds_num++; - $kills = 0; - } - - $new_array[] = $line; - } - } - } - - return $new_array; -} - -function removeComments(&$output) { - $new_array = array(); - if (sizeof($output)) { - foreach($output as $line) { - $line = trim($line); - if ($line == "") { - continue; - }else{ - /* is there a comment, remove it */ - $comment_start = strpos($line, ""); - if ($comment_start == 0) { - $line = trim(substr($line, $comment_end+3)); - }else{ - $line = trim(substr($line,0,$comment_start-1) . substr($line,$comment_end+3)); - } - } - - if ($line != "") { - $new_array[] = $line; - } - } - } - /* transfer the new array back to the original array */ - return $new_array; - } -} - -function displayTime($pdp) { - global $step; - - $total_time = $pdp * $step; // seconds - - if ($total_time < 60) { - return $total_time . " secs"; - }else{ - $total_time = $total_time / 60; - - if ($total_time < 60) { - return $total_time . " mins"; - }else{ - $total_time = $total_time / 60; - - if ($total_time < 24) { - return $total_time . " hours"; - }else{ - $total_time = $total_time / 24; - - return $total_time . " days"; - } - } - } -} - -function debug($string) { - global $debug; - - if ($debug) { - echo "DEBUG: " . $string . "\n"; - } -} - -function standard_deviation($samples) { - $sample_count = count($samples); - $sample_square = array(); - - for ($current_sample = 0; $sample_count > $current_sample; ++$current_sample) { - $sample_square[$current_sample] = pow($samples[$current_sample], 2); - } - - return sqrt(array_sum($sample_square) / $sample_count - pow((array_sum($samples) / $sample_count), 2)); -} - -/* display_help - displays the usage of the function */ -function display_help () { - global $using_cacti; - - if ($using_cacti) { - $version = spikekill_version(); - }else{ - $version = "v1.0"; - } - - echo "Cacti Spike Remover " . ($using_cacti ? "v" . $version["version"] : $version) . ", Copyright 2009, The Cacti Group, Inc.\n\n"; - echo "Usage:\n"; - echo "removespikes.php -R|--rrdfile=rrdfile [-M|--method=stddev] [-A|--avgnan] [-S|--stddev=N]\n"; - echo " [-P|--percent=N] [-N|--number=N] [-D|--dryrun] [-d|--debug] [-h|--help|-v|-V|--version]\n\n"; - - echo "The RRDfile input parameter is mandatory. If no other input parameters are specified the defaults\n"; - echo "are taken from the Spikekill Plugin settings.\n\n"; - - echo "-M|--method - The spike removal method to use. Options are 'stddev'|'variance'\n"; - echo "-A|--avgnan - The spike replacement method to use. Options are 'avg'|'nan'\n"; - echo "-S|--stddev - The number of standard deviations +/- allowed\n"; - echo "-P|--percent - The sample to sample percentage variation allowed\n"; - echo "-N|--number - The maximum number of spikes to remove from the RRDfile\n"; - echo "-D|--dryrun - If specified, the RRDfile will not be changed. Instead a summary of\n"; - echo " changes that would have been performed will be issued.\n\n"; - - echo "The remainder of arguments are informational\n"; - echo "-d|--debug - Display verbose output during execution\n"; - echo "-v -V --version - Display this help message\n"; - echo "-h --help - display this help message\n"; -} +#!/usr/bin/php -q +This script is only meant to run at the command line."); +} + +/* We are not talking to the browser */ +$no_http_headers = true; + +$dir = dirname(__FILE__); +chdir($dir); + +if (strpos($dir, 'spikekill') !== false) { + chdir('../../'); +} + +$using_cacti = false; + +/* setup defaults */ +$debug = false; +$dryrun = false; +$avgnan = 'avg'; +$rrdfile = ""; +$std_kills = true; +$var_kills = true; +$html = false; + +if ($using_cacti) { + $method = read_config_option("spikekill_method"); + $numspike = read_config_option("spikekill_number"); + $stddev = read_config_option("spikekill_deviations"); + $percent = read_config_option("spikekill_percent"); + $outliers = read_config_option("spikekill_outliers"); +} else { + $method = 1; // Standard Deviation + $numspike = 10; + $stddev = 10; + $percent = 500; + $outliers = 5; +} + +/* process calling arguments */ +$parms = $_SERVER["argv"]; +array_shift($parms); + +foreach ($parms as $parameter) { + @list($arg, $value) = @explode("=", $parameter); + + switch ($arg) { + case "--method": + case "-M": + if ($value == "variance") { + $method = 2; + } elseif ($value == "stddev") { + $method = 1; + } else { + echo "FATAL: You must specify either 'stddev' or 'variance' as methods.\n\n"; + display_help(); + exit; + } + + break; + case "--avgnan": + case "-A": + if ($value == "avg") { + $avgnan = "avg"; + } elseif ($value == "nan") { + $avgnan = "nan"; + } else { + echo "FATAL: You must specify either 'avg' or 'nan' as replacement methods.\n\n"; + display_help(); + exit; + } + + break; + case "--rrdfile": + case "-R": + $rrdfile = $value; + + if (!file_exists($rrdfile)) { + echo "FATAL: File '$rrdfile' does not exist.\n"; + exit; + } + + if (!is_writable($rrdfile)) { + echo "FATAL: File '$rrdfile' is not writable by this account.\n"; + exit; + } + + break; + case "--stddev": + case "-S": + $stddev = $value; + + if (!is_numeric($stddev) || ($stddev < 1)) { + echo "FATAL: Standard Deviation must be a positive integer.\n\n"; + display_help(); + exit; + } + + break; + case "--outliers": + case "-O": + $outliers = $value; + + if (!is_numeric($outliers) || ($outliers < 1)) { + echo "FATAL: The number of outliers to exlude must be a positive integer.\n\n"; + display_help(); + exit; + } + + break; + case "--percent": + case "-P": + $percent = $value/100; + + if (!is_numeric($percent) || ($percent <= 0)) { + echo "FATAL: Percent deviation must be a positive floating point number.\n\n"; + display_help(); + exit; + } + + break; + case "--html": + $html = true; + + break; + case "-d": + case "--debug": + $debug = true; + + break; + case "-D": + case "--dryrun": + $dryrun = true; + + break; + case "--number": + case "-n": + $numspike = $value; + + if (!is_numeric($numspike) || ($numspike < 1)) { + echo "FATAL: Number of spikes to remove must be a positive integer\n\n"; + display_help(); + exit; + } + + break; + case "-h": + case "-v": + case "-V": + case "--version": + case "--help": + display_help(); + exit; + default: + print "ERROR: Invalid Parameter " . $parameter . "\n\n"; + display_help(); + exit; + } +} + +/* additional error check */ +if ($rrdfile == "") { + echo "FATAL: You must specify an RRDfile!\n\n"; + display_help(); + exit; +} + +/* determine the temporary file name */ +$seed = mt_rand(); +if ($config["cacti_server_os"] == "win32") { + $tempdir = getenv("TEMP"); + $xmlfile = $tempdir . "/" . str_replace(".rrd", "", basename($rrdfile)) . ".dump." . $seed; +} else { + $tempdir = "/tmp"; + $xmlfile = "/tmp/" . str_replace(".rrd", "", basename($rrdfile)) . ".dump." . $seed; +} + +if ($html) { + echo ""; +} + +if ($using_cacti) { + cacti_log("NOTE: Removing Spikes for '$rrdfile', Method:'$method'", false, "WEBUI"); +} + +/* execute the dump command */ +echo ($html ? "\n":"\n"); + +if ($using_cacti) { + shell_exec(read_config_option("path_rrdtool") . " dump $rrdfile > $xmlfile"); +} else { + shell_exec("rrdtool dump $rrdfile > $xmlfile"); +} + +/* read the xml file into an array*/ +if (file_exists($xmlfile)) { + $output = file($xmlfile); + + /* remove the temp file */ + unlink($xmlfile); +} else { + if ($using_cacti) { + echo ($html ? "\n":"\n"); + } else { + echo ($html ? "\n":"\n"); + } + exit; +} + +/* process the xml file and remove all comments */ +$output = removeComments($output); + +/* Read all the rra's ds values and obtain the following pieces of information from each + rra archive. + + * numsamples - The number of 'valid' non-nan samples + * sumofsamples - The sum of all 'valid' samples. + * average - The average of all samples + * standard_deviation - The standard deviation of all samples + * max_value - The maximum value of all samples + * min_value - The minimum value of all samples + * max_cutoff - Any value above this value will be set to the average. + * min_cutoff - Any value lower than this value will be set to the average. + + This will end up being a n-dimensional array as follows: + rra[x][ds#]['totalsamples']; + rra[x][ds#]['numsamples']; + rra[x][ds#]['sumofsamples']; + rra[x][ds#]['average']; + rra[x][ds#]['stddev']; + rra[x][ds#]['max_value']; + rra[x][ds#]['min_value']; + rra[x][ds#]['max_cutoff']; + rra[x][ds#]['min_cutoff']; + + There will also be a secondary array created with the actual samples. This + array will be used to calculate the standard deviation of the sample set. + samples[rra_num][ds_num][]; + + Also track the min and max value for each ds and store it into the two + arrays: ds_min[ds#], ds_max[ds#]. + + The we don't need to know the type of rra, only it's number for this analysis + the same applies for the ds' as well. +*/ +$rra = array(); +$rra_cf = array(); +$rra_pdp = array(); +$rra_num = 0; +$ds_num = 0; +$total_kills = 0; +$in_rra = false; +$in_db = false; +$ds_min = array(); +$ds_max = array(); +$ds_name = array(); + +/* perform a first pass on the array and do the following: + 1) Get the number of good samples per ds + 2) Get the sum of the samples per ds + 3) Get the max and min values for all samples + 4) Build both the rra and sample arrays + 5) Get each ds' min and max values +*/ +if (sizeof($output)) { + foreach ($output as $line) { + if (substr_count($line, "")) { + $linearray = explode("", $line); + /* discard the row */ + array_shift($linearray); + $ds_num = 0; + foreach ($linearray as $dsvalue) { + /* peel off garbage */ + $dsvalue = trim(str_replace("", "", str_replace("", "", $dsvalue))); + if (strtolower($dsvalue) != "nan") { + if (!isset($rra[$rra_num][$ds_num]["numsamples"])) { + $rra[$rra_num][$ds_num]["numsamples"] = 1; + } else { + $rra[$rra_num][$ds_num]["numsamples"]++; + } + + if (!isset($rra[$rra_num][$ds_num]["sumofsamples"])) { + $rra[$rra_num][$ds_num]["sumofsamples"] = $dsvalue; + } else { + $rra[$rra_num][$ds_num]["sumofsamples"] += $dsvalue; + } + + if (!isset($rra[$rra_num][$ds_num]["max_value"])) { + $rra[$rra_num][$ds_num]["max_value"] = $dsvalue; + } elseif ($dsvalue > $rra[$rra_num][$ds_num]["max_value"]) { + $rra[$rra_num][$ds_num]["max_value"] = $dsvalue; + } + + if (!isset($rra[$rra_num][$ds_num]["min_value"])) { + $rra[$rra_num][$ds_num]["min_value"] = $dsvalue; + } elseif ($dsvalue < $rra[$rra_num][$ds_num]["min_value"]) { + $rra[$rra_num][$ds_num]["min_value"] = $dsvalue; + } + + /* store the sample for standard deviation calculation */ + $samples[$rra_num][$ds_num][] = $dsvalue; + } + + if (!isset($rra[$rra_num][$ds_num]["totalsamples"])) { + $rra[$rra_num][$ds_num]["totalsamples"] = 1; + } else { + $rra[$rra_num][$ds_num]["totalsamples"]++; + } + + $ds_num++; + } + } elseif (substr_count($line, "")) { + $in_rra = true; + } elseif (substr_count($line, "")) { + $ds_min[] = trim(str_replace("", "", str_replace("", "", trim($line)))); + } elseif (substr_count($line, "")) { + $ds_max[] = trim(str_replace("", "", str_replace("", "", trim($line)))); + } elseif (substr_count($line, "")) { + $ds_name[] = trim(str_replace("", "", str_replace("", "", trim($line)))); + } elseif (substr_count($line, "")) { + $rra_cf[] = trim(str_replace("", "", str_replace("", "", trim($line)))); + } elseif (substr_count($line, "")) { + $rra_pdp[] = trim(str_replace("", "", str_replace("", "", trim($line)))); + } elseif (substr_count($line, "")) { + $in_rra = false; + $rra_num++; + } elseif (substr_count($line, "")) { + $step = trim(str_replace("", "", str_replace("", "", trim($line)))); + } + } +} + +/* For all the samples determine the average with the outliers removed */ +calculateVarianceAverages($rra, $samples); + +/* Now scan the rra array and the samples array and calculate the following + 1) The standard deviation of all samples + 2) The average of all samples per ds + 3) The max and min cutoffs of all samples + 4) The number of kills in each ds based upon the thresholds +*/ +echo ($html ? "\n":"\n"); +calculateOverallStatistics($rra, $samples); + +/* debugging and/or status report */ +if ($debug || $dryrun) { + outputStatistics($rra); +} + +/* create an output array */ +if ($method == 1) { + /* standard deviation subroutine */ + if ($std_kills) { + if (!$dryrun) { + $new_output = updateXML($output, $rra); + } + } else { + echo ($html ? "\n":"\n"); + } +} else { + /* variance subroutine */ + if ($var_kills) { + if (!$dryrun) { + $new_output = updateXML($output, $rra); + } + } else { + echo ($html ? "\n":"\n"); + } +} + +/* finally update the file XML file and Reprocess the RRDfile */ +if (!$dryrun) { + if ($total_kills) { + if (writeXMLFile($new_output, $xmlfile)) { + if (backupRRDFile($rrdfile)) { + createRRDFileFromXML($xmlfile, $rrdfile); + } else { + echo ($html ? "\n":"\n"); + } + } else { + echo ($html ? "\n":"\n"); + } + } +} else { + echo ($html ? "\n":"\n"); +} + +if ($html) { + echo "
":"") . "NOTE: Creating XML file '$xmlfile' from '$rrdfile'" . ($html ? "
":"") . "FATAL: RRDtool Command Failed. Please verify that the RRDtool path is valid in Settings->Paths!" . ($html ? "
":"") . "FATAL: RRDtool Command Failed. Please insure RRDtool is in your path!" . ($html ? "
":"") . "NOTE: Searching for Spikes in XML file '$xmlfile'" . ($html ? "
":"") . "NOTE: NO Standard Deviation Spikes found in '$rrdfile'" . ($html ? "
":"") . "NOTE: NO Variance Spikes found in '$rrdfile'" . ($html ? "
":"") . "FATAL: Unable to backup '$rrdfile'" . ($html ? "
":"") . "FATAL: Unable to write XML file '$xmlfile'" . ($html ? "
":"") . "NOTE: Dryrun requested. No updates performed" . ($html ? "
"; +} + +/* All Functions */ +function createRRDFileFromXML($xmlfile, $rrdfile) +{ + global $using_cacti, $html; + + /* execute the dump command */ + echo ($html ? "":"") . "NOTE: Re-Importing '$xmlfile' to '$rrdfile'" . ($html ? "\n":"\n"); + if ($using_cacti) { + $response = shell_exec(read_config_option("path_rrdtool") . " restore -f -r $xmlfile $rrdfile"); + } else { + $response = shell_exec("rrdtool restore -f -r $xmlfile $rrdfile"); + } + if (strlen($response)) { + echo ($html ? "":"") . $response . ($html ? "\n":"\n"); + } +} + +function writeXMLFile($output, $xmlfile) +{ + return file_put_contents($xmlfile, $output); +} + +function backupRRDFile($rrdfile) +{ + global $using_cacti, $tempdir, $seed, $html; + + if ($using_cacti) { + $backupdir = read_config_option("spikekill_backupdir"); + + if ($backupdir == "") { + $backupdir = $tempdir; + } + } else { + $backupdir = $tempdir; + } + + if (file_exists($backupdir . "/" . basename($rrdfile))) { + $newfile = basename($rrdfile) . "." . $seed; + } else { + $newfile = basename($rrdfile); + } + + echo ($html ? "":"") . "NOTE: Backing Up '$rrdfile' to '" . $backupdir . "/" . $newfile . "'" . ($html ? "\n":"\n"); + + return copy($rrdfile, $backupdir . "/" . $newfile); +} + +function calculateVarianceAverages(&$rra, &$samples) +{ + global $outliers; + + if (sizeof($samples)) { + foreach ($samples as $rra_num => $dses) { + if (sizeof($dses)) { + foreach ($dses as $ds_num => $ds) { + if (sizeof($ds) < $outliers * 3) { + $rra[$rra_num][$ds_num]["variance_avg"] = "NAN"; + } else { + rsort($ds, SORT_NUMERIC); + $ds = array_slice($ds, $outliers); + + sort($ds, SORT_NUMERIC); + $ds = array_slice($ds, $outliers); + + $rra[$rra_num][$ds_num]["variance_avg"] = array_sum($ds) / sizeof($ds); + } + } + } + } + } +} + +function calculateOverallStatistics(&$rra, &$samples) +{ + global $percent, $stddev, $ds_min, $ds_max, $var_kills, $std_kills; + + $rra_num = 0; + if (sizeof($rra)) { + foreach ($rra as $dses) { + $ds_num = 0; + + if (sizeof($dses)) { + foreach ($dses as $ds) { + if (isset($samples[$rra_num][$ds_num])) { + $rra[$rra_num][$ds_num]["standard_deviation"] = standard_deviation($samples[$rra_num][$ds_num]); + if ($rra[$rra_num][$ds_num]["standard_deviation"] == "NAN") { + $rra[$rra_num][$ds_num]["standard_deviation"] = 0; + } + $rra[$rra_num][$ds_num]["average"] = $rra[$rra_num][$ds_num]["sumofsamples"] / $rra[$rra_num][$ds_num]["numsamples"]; + + $rra[$rra_num][$ds_num]["min_cutoff"] = $rra[$rra_num][$ds_num]["average"] - ($stddev * $rra[$rra_num][$ds_num]["standard_deviation"]); + if ($rra[$rra_num][$ds_num]["min_cutoff"] < $ds_min[$ds_num]) { + $rra[$rra_num][$ds_num]["min_cutoff"] = $ds_min[$ds_num]; + } + + $rra[$rra_num][$ds_num]["max_cutoff"] = $rra[$rra_num][$ds_num]["average"] + ($stddev * $rra[$rra_num][$ds_num]["standard_deviation"]); + if ($rra[$rra_num][$ds_num]["max_cutoff"] > $ds_max[$ds_num]) { + $rra[$rra_num][$ds_num]["max_cutoff"] = $ds_max[$ds_num]; + } + + $rra[$rra_num][$ds_num]["numnksamples"] = 0; + $rra[$rra_num][$ds_num]["sumnksamples"] = 0; + $rra[$rra_num][$ds_num]["avgnksamples"] = 0; + + /* go through values and find cutoffs */ + $rra[$rra_num][$ds_num]["stddev_killed"] = 0; + $rra[$rra_num][$ds_num]["variance_killed"] = 0; + + if (sizeof($samples[$rra_num][$ds_num])) { + foreach ($samples[$rra_num][$ds_num] as $sample) { + if (($sample > $rra[$rra_num][$ds_num]["max_cutoff"]) || + ($sample < $rra[$rra_num][$ds_num]["min_cutoff"])) { + debug(sprintf("Std Kill: Value '%.4e', StandardDev '%.4e', StdDevLimit '%.4e'", $sample, $rra[$rra_num][$ds_num]["standard_deviation"], ($rra[$rra_num][$ds_num]["max_cutoff"] * (1+$percent)))); + $rra[$rra_num][$ds_num]["stddev_killed"]++; + $std_kills = true; + } else { + $rra[$rra_num][$ds_num]["numnksamples"]++; + $rra[$rra_num][$ds_num]["sumnksamples"] += $sample; + } + + if ($rra[$rra_num][$ds_num]["variance_avg"] == "NAN") { + /* not enought samples to calculate */ + } elseif ($sample > ($rra[$rra_num][$ds_num]["variance_avg"] * (1+$percent))) { + /* kill based upon variance */ + debug(sprintf("Var Kill: Value '%.4e', VarianceDev '%.4e', VarianceLimit '%.4e'", $sample, $rra[$rra_num][$ds_num]["variance_avg"], ($rra[$rra_num][$ds_num]["variance_avg"] * (1+$percent)))); + $rra[$rra_num][$ds_num]["variance_killed"]++; + $var_kills = true; + } + } + } + + if ($rra[$rra_num][$ds_num]["numnksamples"] > 0) { + $rra[$rra_num][$ds_num]["avgnksamples"] = $rra[$rra_num][$ds_num]["sumnksamples"] / $rra[$rra_num][$ds_num]["numnksamples"]; + } + } else { + $rra[$rra_num][$ds_num]["standard_deviation"] = "N/A"; + $rra[$rra_num][$ds_num]["average"] = "N/A"; + $rra[$rra_num][$ds_num]["min_cutoff"] = "N/A"; + $rra[$rra_num][$ds_num]["max_cutoff"] = "N/A"; + $rra[$rra_num][$ds_num]["numnksamples"] = "N/A"; + $rra[$rra_num][$ds_num]["sumnksamples"] = "N/A"; + $rra[$rra_num][$ds_num]["avgnksamples"] = "N/A"; + $rra[$rra_num][$ds_num]["stddev_killed"] = "N/A"; + $rra[$rra_num][$ds_num]["variance_killed"] = "N/A"; + $rra[$rra_num][$ds_num]["stddev_killed"] = "N/A"; + $rra[$rra_num][$ds_num]["numnksamples"] = "N/A"; + $rra[$rra_num][$ds_num]["sumnksamples"] = "N/A"; + $rra[$rra_num][$ds_num]["variance_killed"] = "N/A"; + $rra[$rra_num][$ds_num]["avgnksamples"] = "N/A"; + } + + $ds_num++; + } + } + + $rra_num++; + } + } +} + +function outputStatistics($rra) +{ + global $rra_cf, $rra_name, $ds_name, $rra_pdp, $html; + + if (sizeof($rra)) { + if (!$html) { + echo "\n"; + printf( + "%10s %16s %10s %7s %7s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n", + "Size", + "DataSource", + "CF", + "Samples", + "NonNan", + "Avg", + "StdDev", + "MaxValue", + "MinValue", + "MaxStdDev", + "MinStdDev", + "StdKilled", + "VarKilled", + "StdDevAvg", + "VarAvg" + ); + printf( + "%10s %16s %10s %7s %7s %10s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n", + "----------", + "---------------", + "----------", + "-------", + "-------", + "----------", + "----------", + "----------", + "----------", + "----------", + "----------", + "----------", + "----------", + "----------", + "----------" + ); + foreach ($rra as $rra_key => $dses) { + if (sizeof($dses)) { + foreach ($dses as $dskey => $ds) { + printf( + "%10s %16s %10s %7s %7s " . + ($ds["average"] < 1E6 ? "%10s ":"%10.4e ") . + ($ds["standard_deviation"] < 1E6 ? "%10s ":"%10.4e ") . + (isset($ds["max_value"]) ? ($ds["max_value"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . + (isset($ds["min_value"]) ? ($ds["min_value"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . + (isset($ds["max_cutoff"]) ? ($ds["max_cutoff"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . + (isset($ds["min_cutoff"]) ? ($ds["min_cutoff"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . + "%10s %10s " . + (isset($ds["avgnksampled"]) ? ($ds["avgnksamples"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . + (isset($ds["variance_avg"]) ? ($ds["variance_avg"] < 1E6 ? "%10s ":"%10.4e ") : "%10s ") . "\n", + displayTime($rra_pdp[$rra_key]), + $ds_name[$dskey], + $rra_cf[$rra_key], + $ds["totalsamples"], + (isset($ds["numsamples"]) ? $ds["numsamples"] : "0"), + ($ds["average"] != "N/A" ? round($ds["average"], 2) : $ds["average"]), + ($ds["standard_deviation"] != "N/A" ? round($ds["standard_deviation"], 2) : $ds["standard_deviation"]), + (isset($ds["max_value"]) ? round($ds["max_value"], 2) : "N/A"), + (isset($ds["min_value"]) ? round($ds["min_value"], 2) : "N/A"), + ($ds["max_cutoff"] != "N/A" ? round($ds["max_cutoff"], 2) : $ds["max_cutoff"]), + ($ds["min_cutoff"] != "N/A" ? round($ds["min_cutoff"], 2) : $ds["min_cutoff"]), + $ds["stddev_killed"], + $ds["variance_killed"], + ($ds["avgnksamples"] != "N/A" ? round($ds["avgnksamples"], 2) : $ds["avgnksamples"]), + (isset($ds["variance_avg"]) ? round($ds["variance_avg"], 2) : "N/A") + ); + } + } + } + + echo "\n"; + } else { + printf( + "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", + "Size", + "DataSource", + "CF", + "Samples", + "NonNan", + "Avg", + "StdDev", + "MaxValue", + "MinValue", + "MaxStdDev", + "MinStdDev", + "StdKilled", + "VarKilled", + "StdDevAvg", + "VarAvg" + ); + foreach ($rra as $rra_key => $dses) { + if (sizeof($dses)) { + foreach ($dses as $dskey => $ds) { + printf( + "%s%s%s%s%s" . + ($ds["average"] < 1E6 ? "%s":"%.4e") . + ($ds["standard_deviation"] < 1E6 ? "%s":"%.4e") . + (isset($ds["max_value"]) ? ($ds["max_value"] < 1E6 ? "%s":"%.4e") : "%s") . + (isset($ds["min_value"]) ? ($ds["min_value"] < 1E6 ? "%s":"%.4e") : "%s") . + (isset($ds["max_cutoff"]) ? ($ds["max_cutoff"] < 1E6 ? "%s":"%.4e") : "%s") . + (isset($ds["min_cutoff"]) ? ($ds["min_cutoff"] < 1E6 ? "%s":"%.4e") : "%s") . + "%s%s" . + (isset($ds["avgnksampled"]) ? ($ds["avgnksamples"] < 1E6 ? "%s":"%.4e") : "%s") . + (isset($ds["variance_avg"]) ? ($ds["variance_avg"] < 1E6 ? "%s\n":"%.4e\n") : "%s\n") . "\n", + displayTime($rra_pdp[$rra_key]), + $ds_name[$dskey], + $rra_cf[$rra_key], + $ds["totalsamples"], + (isset($ds["numsamples"]) ? $ds["numsamples"] : "0"), + ($ds["average"] != "N/A" ? round($ds["average"], 2) : $ds["average"]), + ($ds["standard_deviation"] != "N/A" ? round($ds["standard_deviation"], 2) : $ds["standard_deviation"]), + (isset($ds["max_value"]) ? round($ds["max_value"], 2) : "N/A"), + (isset($ds["min_value"]) ? round($ds["min_value"], 2) : "N/A"), + ($ds["max_cutoff"] != "N/A" ? round($ds["max_cutoff"], 2) : $ds["max_cutoff"]), + ($ds["min_cutoff"] != "N/A" ? round($ds["min_cutoff"], 2) : $ds["min_cutoff"]), + $ds["stddev_killed"], + $ds["variance_killed"], + ($ds["avgnksamples"] != "N/A" ? round($ds["avgnksamples"], 2) : $ds["avgnksamples"]), + (isset($ds["variance_avg"]) ? round($ds["variance_avg"], 2) : "N/A") + ); + } + } + } + } + } +} + +function updateXML(&$output, &$rra) +{ + global $numspike, $percent, $avgnan, $method, $total_kills; + $new_array = array(); + + /* variance subroutine */ + $rra_num = 0; + $ds_num = 0; + $kills = 0; + + if (sizeof($output)) { + foreach ($output as $line) { + if (substr_count($line, "")) { + $linearray = explode("", $line); + /* discard the row */ + array_shift($linearray); + + /* initialize variables */ + $ds_num = 0; + $out_row = ""; + foreach ($linearray as $dsvalue) { + /* peel off garbage */ + $dsvalue = trim(str_replace("", "", str_replace("", "", $dsvalue))); + if (strtolower($dsvalue) == "nan") { + /* do nothing, it's a NaN */ + } else { + if ($method == 2) { + if ($dsvalue > (1+$percent)*$rra[$rra_num][$ds_num]["variance_avg"]) { + if ($kills < $numspike) { + if ($avgnan == "avg") { + $dsvalue = $rra[$rra_num][$ds_num]["variance_avg"]; + } else { + $dsvalue = "NaN"; + } + $kills++; + $total_kills++; + } + } + } else { + if (($dsvalue > $rra[$rra_num][$ds_num]["max_cutoff"]) || + ($dsvalue < $rra[$rra_num][$ds_num]["min_cutoff"])) { + if ($kills < $numspike) { + if ($avgnan == "avg") { + $dsvalue = $rra[$rra_num][$ds_num]["average"]; + } else { + $dsvalue = "NaN"; + } + $kills++; + $total_kills++; + } + } + } + } + + $out_row .= " " . $dsvalue . ""; + $ds_num++; + } + + $out_row .= ""; + + $new_array[] = $out_row; + } else { + if (substr_count($line, "")) { + $ds_minmax = array(); + $rra_num++; + $kills = 0; + } elseif (substr_count($line, "")) { + $ds_num++; + $kills = 0; + } + + $new_array[] = $line; + } + } + } + + return $new_array; +} + +function removeComments(&$output) +{ + $new_array = array(); + if (sizeof($output)) { + foreach ($output as $line) { + $line = trim($line); + if ($line == "") { + continue; + } else { + /* is there a comment, remove it */ + $comment_start = strpos($line, ""); + if ($comment_start == 0) { + $line = trim(substr($line, $comment_end+3)); + } else { + $line = trim(substr($line, 0, $comment_start-1) . substr($line, $comment_end+3)); + } + } + + if ($line != "") { + $new_array[] = $line; + } + } + } + /* transfer the new array back to the original array */ + return $new_array; + } +} + +function displayTime($pdp) +{ + global $step; + + $total_time = $pdp * $step; // seconds + + if ($total_time < 60) { + return $total_time . " secs"; + } else { + $total_time = $total_time / 60; + + if ($total_time < 60) { + return $total_time . " mins"; + } else { + $total_time = $total_time / 60; + + if ($total_time < 24) { + return $total_time . " hours"; + } else { + $total_time = $total_time / 24; + + return $total_time . " days"; + } + } + } +} + +function debug($string) +{ + global $debug; + + if ($debug) { + echo "DEBUG: " . $string . "\n"; + } +} + +function standard_deviation($samples) +{ + $sample_count = count($samples); + $sample_square = array(); + + for ($current_sample = 0; $sample_count > $current_sample; ++$current_sample) { + $sample_square[$current_sample] = pow($samples[$current_sample], 2); + } + + return sqrt(array_sum($sample_square) / $sample_count - pow((array_sum($samples) / $sample_count), 2)); +} + +/* display_help - displays the usage of the function */ +function display_help() +{ + global $using_cacti; + + if ($using_cacti) { + $version = spikekill_version(); + } else { + $version = "v1.0"; + } + + echo "Cacti Spike Remover " . ($using_cacti ? "v" . $version["version"] : $version) . ", Copyright 2009, The Cacti Group, Inc.\n\n"; + echo "Usage:\n"; + echo "removespikes.php -R|--rrdfile=rrdfile [-M|--method=stddev] [-A|--avgnan] [-S|--stddev=N]\n"; + echo " [-P|--percent=N] [-N|--number=N] [-D|--dryrun] [-d|--debug] [-h|--help|-v|-V|--version]\n\n"; + + echo "The RRDfile input parameter is mandatory. If no other input parameters are specified the defaults\n"; + echo "are taken from the Spikekill Plugin settings.\n\n"; + + echo "-M|--method - The spike removal method to use. Options are 'stddev'|'variance'\n"; + echo "-A|--avgnan - The spike replacement method to use. Options are 'avg'|'nan'\n"; + echo "-S|--stddev - The number of standard deviations +/- allowed\n"; + echo "-P|--percent - The sample to sample percentage variation allowed\n"; + echo "-N|--number - The maximum number of spikes to remove from the RRDfile\n"; + echo "-D|--dryrun - If specified, the RRDfile will not be changed. Instead a summary of\n"; + echo " changes that would have been performed will be issued.\n\n"; + + echo "The remainder of arguments are informational\n"; + echo "-d|--debug - Display verbose output during execution\n"; + echo "-v -V --version - Display this help message\n"; + echo "-h --help - display this help message\n"; +} diff --git a/scripts/tune_port.php b/scripts/tune_port.php index 81cc98e4e0..162f6a3d70 100755 --- a/scripts/tune_port.php +++ b/scripts/tune_port.php @@ -13,19 +13,16 @@ $hosts = str_replace('*', '%', mres($options['h'])); $ports = str_replace('*', '%', mres($options['p'])); if (empty($hosts) && empty($ports)) { - echo "-h Device(s) to match\n"; echo "-p Port(s) to match using ifName\n"; echo "\n"; - } foreach (dbFetchRows("SELECT `device_id`,`hostname` FROM `devices` WHERE `hostname` LIKE ?", array('%'.$hosts.'%')) as $device) { echo "Found hostname " . $device['hostname'].".......\n"; foreach (dbFetchRows("SELECT `port_id`,`ifIndex`,`ifName`,`ifSpeed` FROM `ports` WHERE `ifName` LIKE ? AND `device_id` = ?", array('%'.$ports.'%',$device['device_id'])) as $port) { echo "Tuning port " . $port['ifName'].".......\n"; - $rrdfile = get_port_rrdfile_path ($device['hostname'], $port['port_id']); - rrdtool_tune('port',$rrdfile,$port['ifSpeed']); + $rrdfile = get_port_rrdfile_path($device['hostname'], $port['port_id']); + rrdtool_tune('port', $rrdfile, $port['ifSpeed']); } } - diff --git a/scripts/update-sql.php b/scripts/update-sql.php index 632093a7c9..5f7129eb22 100755 --- a/scripts/update-sql.php +++ b/scripts/update-sql.php @@ -17,7 +17,6 @@ if ($fd = @fopen($argv[1], 'r')) { // FIXME check query success? echo "$line \n"; } -} -else { +} else { echo "ERROR: Could not open file \"$argv[1]\".\n"; } diff --git a/snmp-scan.php b/snmp-scan.php index 82dc14ac73..095982ed7d 100755 --- a/snmp-scan.php +++ b/snmp-scan.php @@ -44,7 +44,8 @@ if ($config['autodiscovery']['snmpscan'] == false) { exit(2); } -function perform_snmp_scan($net) { +function perform_snmp_scan($net) +{ global $stats, $config, $debug, $vdebug; echo 'Range: '.$net->network.'/'.$net->bitmask.PHP_EOL; $config['snmp']['timeout'] = 1; @@ -141,7 +142,7 @@ if (isset($opts['r'])) { if (!is_array($config['nets'])) { $config['nets'] = array( $config['nets'] ); } - foreach( $config['nets'] as $subnet ) { + foreach ($config['nets'] as $subnet) { $net = Net_IPv4::parseAddress($subnet); perform_snmp_scan($net); } @@ -151,4 +152,3 @@ if (isset($opts['r'])) { echo 'Please either add a range argument with \'-r \' or define $config[\'nets\'] in your config.php'.PHP_EOL; exit(2); } - diff --git a/snmptrap.php b/snmptrap.php index 04f6f5de6c..0526f74232 100755 --- a/snmptrap.php +++ b/snmptrap.php @@ -40,7 +40,6 @@ if (!$device['device_id']) { $file = $config['install_dir'].'/includes/snmptrap/'.$entry['1'].'.inc.php'; if (is_file($file)) { include "$file"; -} -else { +} else { echo "unknown trap ($file)"; } diff --git a/syslog.php b/syslog.php index be0af66581..754438d406 100755 --- a/syslog.php +++ b/syslog.php @@ -23,7 +23,7 @@ require_once 'includes/functions.php'; $i = "1"; -$s = fopen('php://stdin','r'); +$s = fopen('php://stdin', 'r'); while ($line = fgets($s)) { #logfile($line); list($entry['host'],$entry['facility'],$entry['priority'], $entry['level'], $entry['tag'], $entry['timestamp'], $entry['msg'], $entry['program']) = explode("||", trim($line)); diff --git a/tests/RrdtoolTest.php b/tests/RrdtoolTest.php index 261b38b9bd..42c0e7da94 100644 --- a/tests/RrdtoolTest.php +++ b/tests/RrdtoolTest.php @@ -84,7 +84,6 @@ class RrdtoolTest extends \PHPUnit_Framework_TestCase $cmd = rrdtool_build_command('update', '/opt/librenms/rrd/f', 'o'); $this->assertEquals('update f o --daemon server:42217', $cmd); - } public function testBuildCommandException() @@ -97,5 +96,4 @@ class RrdtoolTest extends \PHPUnit_Framework_TestCase // use this file, since it is guaranteed to exist rrdtool_build_command('create', __FILE__, 'o'); } - } diff --git a/tests/SyslogTest.php b/tests/SyslogTest.php index b8b70b25cf..f0341b9b2e 100644 --- a/tests/SyslogTest.php +++ b/tests/SyslogTest.php @@ -32,13 +32,15 @@ class SyslogTest extends \PHPUnit_Framework_TestCase // $SOURCEIP||$FACILITY||$PRIORITY||$LEVEL||$TAG||$YEAR-$MONTH-$DAY $HOUR:$MIN:$SEC||$MSG||$PROGRAM // There add an IP for each OS you want to test and use that in the input file - private function fillLine($line) { + private function fillLine($line) + { $entry = array(); list($entry['host'],$entry['facility'],$entry['priority'], $entry['level'], $entry['tag'], $entry['timestamp'], $entry['msg'], $entry['program']) = explode("||", trim($line)); return $entry; } - private function createData($line, $resultDelta) { + private function createData($line, $resultDelta) + { $entry = $this->fillLine($line); $data = array(); $data['input'] = $entry; @@ -54,7 +56,8 @@ class SyslogTest extends \PHPUnit_Framework_TestCase * @param string $inputline The line from the syslog daemon including the ||'s * @param array $modified of the modified fields, most likely containging the keys program and msg */ - private function checkSyslog($inputline, $modified) { + private function checkSyslog($inputline, $modified) + { $data = $this->createData($inputline, $modified); $res = process_syslog($data['input'], 0); $this->assertEquals($data['result'], $res); @@ -126,18 +129,18 @@ class SyslogTest extends \PHPUnit_Framework_TestCase ); // With program from syslog - $this->checkSyslog( + $this->checkSyslog( "1.1.1.1||local7||notice||notice||bd||2016-04-04 15:18:43||Apr 4 13:18:42.670: %LINEPROTO-5-UPDOWN: Line protocol on Interface GigabitEthernet0/32, changed state to up||345735", array('device_id'=>1, 'program'=>'%LINEPROTO-5-UPDOWN', 'msg'=>'Line protocol on Interface GigabitEthernet0/32, changed state to up') ); // Incorrect time - $this->checkSyslog( + $this->checkSyslog( "1.1.1.1||user||info||info||0e||2016-04-06 15:20:35||*Apr 4 21:26:41.778 UTC: %LWAPP-3-REPLAY_ERR: 1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx||", array('device_id'=>1, 'program'=>'%LWAPP-3-REPLAY_ERR', 'msg'=>'1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx') ); - $this->checkSyslog( + $this->checkSyslog( "1.1.1.1||user||info||info||0e||2016-04-06 15:20:35||.Apr 4 21:26:41.778 UTC: %LWAPP-3-REPLAY_ERR: 1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx||", array('device_id'=>1, 'program'=>'%LWAPP-3-REPLAY_ERR', 'msg'=>'1 wcm: Received replay error on slot 1, WLAN ID 1, count 1 from AP xxxx.xxxx.xxxx') ); @@ -232,4 +235,3 @@ class SyslogTest extends \PHPUnit_Framework_TestCase ); } } - diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 3a8379a2b2..58b9e29526 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -32,4 +32,3 @@ $classLoader->registerDir($install_dir . '/tests', 'LibreNMS\Tests'); require_once $install_dir . '/includes/rrdtool.inc.php'; require_once $install_dir . '/includes/syslog.php'; - diff --git a/validate.php b/validate.php index d6d46c9629..208f2cf142 100755 --- a/validate.php +++ b/validate.php @@ -16,7 +16,7 @@ $options = getopt('m:h::'); if (isset($options['h'])) { - echo + echo "\n Validate setup tool Usage: ./validate.php [-m ] [-h] @@ -38,15 +38,12 @@ if (strstr(`php -ln config.php`, 'No syntax errors detected')) { $last_lines = explode(PHP_EOL, `tail -n2 config.php`); if (substr($first_line, 0, 5) !== '' && $last_lines[1] == '') { + } elseif ($last_lines[0] == '?>' && $last_lines[1] == '') { print_fail('config.php contains a new line at the end, please remove any whitespace at the end of the file and also remove ?>'); - } - else if ($last_lines[1] == '?>') { + } elseif ($last_lines[1] == '?>') { print_warn("It looks like you have ?> at the end of config.php, it is suggested you remove this"); } -} -else { +} else { print_fail('Syntax error in config.php'); } @@ -61,7 +58,7 @@ require_once 'includes/defaults.inc.php'; require_once 'config.php'; // make sure install_dir is set correctly, or the next includes will fail -if(!file_exists($config['install_dir'].'/config.php')) { +if (!file_exists($config['install_dir'].'/config.php')) { print_fail('$config[\'install_dir\'] is not set correctly. It should probably be set to: ' . getcwd()); exit; } @@ -79,21 +76,20 @@ $cur_sha = $versions['local_sha']; if ($config['update_channel'] == 'master' && $cur_sha != $versions['github']['sha']) { $commit_date = new DateTime('@'.$versions['local_date'], new DateTimeZone(date_default_timezone_get())); print_warn("Your install is out of date: $cur_sha " . $commit_date->format('(r)')); -} -else { +} else { echo "Commit SHA: $cur_sha\n"; } -if($versions['local_branch'] != 'master') { +if ($versions['local_branch'] != 'master') { print_warn("Your local git branch is not master, this will prevent automatic updates."); } // check for modified files $modifiedcmd = 'git diff --name-only --exit-code'; -if($username === 'root') { +if ($username === 'root') { $modifiedcmd = 'su '.$config['user'].' -c "'.$modifiedcmd.'"'; } exec($modifiedcmd, $cmdoutput, $code); -if($code !== 0 && !empty($cmdoutput)) { +if ($code !== 0 && !empty($cmdoutput)) { print_warn("Your local git contains modified files, this could prevent automatic updates.\nModified files:"); echo(' ' . implode("\n ", $cmdoutput) . "\n"); } @@ -142,8 +138,7 @@ if (isset($config['user'])) { echo "\n"; } } -} -else { +} else { print_warn('You don\'t have $config["user"] set, this most likely needs to be set to librenms'); } @@ -151,14 +146,13 @@ else { $test_db = @mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']); if (mysqli_connect_error()) { print_fail('Error connecting to your database '.mysqli_connect_error()); -} -else { +} else { print_ok('Database connection successful'); } // Test for MySQL Strict mode $strict_mode = dbFetchCell("SELECT @@global.sql_mode"); -if(strstr($strict_mode, 'STRICT_TRANS_TABLES')) { +if (strstr($strict_mode, 'STRICT_TRANS_TABLES')) { print_fail('You have MySQL STRICT_TRANS_TABLES enabled, please disable this until full support has been added: https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html'); } @@ -229,101 +223,89 @@ if (!function_exists('openssl_random_pseudo_bytes')) { $modules = explode(',', $options['m']); foreach ($modules as $module) { switch ($module) { - case 'mail': - if ($config['alert']['transports']['mail'] === true) { - $run_test = 1; - if (empty($config['alert']['default_mail'])) { - print_fail('default_mail config option needs to be specified to test email'); - $run_test = 0; - } - else if ($config['email_backend'] == 'sendmail') { - if (empty($config['email_sendmail_path'])) { - print_fail("You have selected sendmail but not configured email_sendmail_path"); - $run_test = 0; - } - elseif (!file_exists($config['email_sendmail_path'])) { - print_fail("The configured email_sendmail_path is not valid"); - $run_test = 0; - } - } - else if ($config['email_backend'] == 'smtp') { - if (empty($config['email_smtp_host'])) { - print_fail('You have selected SMTP but not configured an SMTP host'); - $run_test = 0; - } - if (empty($config['email_smtp_port'])) { - print_fail('You have selected SMTP but not configured an SMTP port'); - $run_test = 0; - } - if (($config['email_smtp_auth'] === true) && (empty($config['email_smtp_username']) || empty($config['email_smtp_password']))) { - print_fail('You have selected SMTP auth but have not configured both username and password'); + case 'mail': + if ($config['alert']['transports']['mail'] === true) { + $run_test = 1; + if (empty($config['alert']['default_mail'])) { + print_fail('default_mail config option needs to be specified to test email'); $run_test = 0; + } elseif ($config['email_backend'] == 'sendmail') { + if (empty($config['email_sendmail_path'])) { + print_fail("You have selected sendmail but not configured email_sendmail_path"); + $run_test = 0; + } elseif (!file_exists($config['email_sendmail_path'])) { + print_fail("The configured email_sendmail_path is not valid"); + $run_test = 0; + } + } elseif ($config['email_backend'] == 'smtp') { + if (empty($config['email_smtp_host'])) { + print_fail('You have selected SMTP but not configured an SMTP host'); + $run_test = 0; + } + if (empty($config['email_smtp_port'])) { + print_fail('You have selected SMTP but not configured an SMTP port'); + $run_test = 0; + } + if (($config['email_smtp_auth'] === true) && (empty($config['email_smtp_username']) || empty($config['email_smtp_password']))) { + print_fail('You have selected SMTP auth but have not configured both username and password'); + $run_test = 0; + } + }//end if + if ($run_test == 1) { + if ($err = send_mail($config['alert']['default_mail'], 'Test email', 'Testing email from NMS')) { + print_ok('Email has been sent'); + } else { + print_fail('Issue sending email to '.$config['alert']['default_mail'].' with error '.$err); + } } }//end if - if ($run_test == 1) { - if ($err = send_mail($config['alert']['default_mail'], 'Test email', 'Testing email from NMS')) { - print_ok('Email has been sent'); + break; + case 'dist-poller': + if ($config['distributed_poller'] !== true) { + print_fail('You have not enabled distributed_poller'); + } else { + if (empty($config['distributed_poller_memcached_host'])) { + print_fail('You have not configured $config[\'distributed_poller_memcached_host\']'); + } elseif (empty($config['distributed_poller_memcached_port'])) { + print_fail('You have not configured $config[\'distributed_poller_memcached_port\']'); + } else { + $connection = @fsockopen($config['distributed_poller_memcached_host'], $config['distributed_poller_memcached_port']); + if (!is_resource($connection)) { + print_fail('We could not get memcached stats, it is possible that we cannot connect to your memcached server, please check'); + } else { + fclose($connection); + print_ok('Connection to memcached is ok'); + } } - else { - print_fail('Issue sending email to '.$config['alert']['default_mail'].' with error '.$err); + if (empty($config['rrdcached'])) { + print_fail('You have not configured $config[\'rrdcached\']'); + } elseif (empty($config['rrd_dir'])) { + print_fail('You have not configured $config[\'rrd_dir\']'); + } else { + check_rrdcached(); } } - }//end if - break; - case 'dist-poller': - if ($config['distributed_poller'] !== true) { - print_fail('You have not enabled distributed_poller'); - } - else { - if (empty($config['distributed_poller_memcached_host'])) { - print_fail('You have not configured $config[\'distributed_poller_memcached_host\']'); - } - elseif (empty($config['distributed_poller_memcached_port'])) { - print_fail('You have not configured $config[\'distributed_poller_memcached_port\']'); - } - else { - $connection = @fsockopen($config['distributed_poller_memcached_host'], $config['distributed_poller_memcached_port']); - if (!is_resource($connection)) { - print_fail('We could not get memcached stats, it is possible that we cannot connect to your memcached server, please check'); - } - else { - fclose($connection); - print_ok('Connection to memcached is ok'); - } - } - if (empty($config['rrdcached'])) { - print_fail('You have not configured $config[\'rrdcached\']'); - } - elseif (empty($config['rrd_dir'])) { - print_fail('You have not configured $config[\'rrd_dir\']'); - } - else { - check_rrdcached(); - } - } - break; - case 'rrdcheck': + break; + case 'rrdcheck': + // Loop through the rrd_dir + $rrd_directory = new RecursiveDirectoryIterator($config['rrd_dir']); + // Filter out any non rrd files + $rrd_directory_filter = new LibreNMS\RRDRecursiveFilterIterator($rrd_directory); + $rrd_iterator = new RecursiveIteratorIterator($rrd_directory_filter); + $rrd_total = iterator_count($rrd_iterator); + $rrd_iterator->rewind(); // Rewind iterator in case iterator_count left iterator in unknown state - // Loop through the rrd_dir - $rrd_directory = new RecursiveDirectoryIterator($config['rrd_dir']); - // Filter out any non rrd files - $rrd_directory_filter = new LibreNMS\RRDRecursiveFilterIterator($rrd_directory); - $rrd_iterator = new RecursiveIteratorIterator($rrd_directory_filter); - $rrd_total = iterator_count($rrd_iterator); - $rrd_iterator->rewind(); // Rewind iterator in case iterator_count left iterator in unknown state + echo "\nScanning ".$rrd_total." rrd files in ".$config['rrd_dir']."...\n"; - echo "\nScanning ".$rrd_total." rrd files in ".$config['rrd_dir']."...\n"; - - // Count loops so we can push status to the user - $loopcount = 0; - $screenpad = 0; - - foreach ($rrd_iterator as $filename => $file) { + // Count loops so we can push status to the user + $loopcount = 0; + $screenpad = 0; + foreach ($rrd_iterator as $filename => $file) { $rrd_test_result = rrdtest($filename, $output, $error); $loopcount++; - if (($loopcount % 50) == 0 ) { + if (($loopcount % 50) == 0) { //This lets us update the previous status update without spamming in most consoles echo "\033[".$screenpad."D"; $test_status = 'Status: '.$loopcount.'/'.$rrd_total; @@ -332,51 +314,53 @@ foreach ($modules as $module) { } // A non zero result means there was some kind of error - if ($rrd_test_result > 0) { + if ($rrd_test_result > 0) { echo "\033[".$screenpad."D"; print_fail('Error parsing "'.$filename.'" RRD '.trim($error)); $screenpad = 0; } - } - echo "\033[".$screenpad."D"; - echo "Status: ".$loopcount."/".$rrd_total." - Complete\n"; + } + echo "\033[".$screenpad."D"; + echo "Status: ".$loopcount."/".$rrd_total." - Complete\n"; - break; + break; }//end switch }//end foreach // End -function print_ok($msg) { +function print_ok($msg) +{ echo "[OK] $msg\n"; }//end print_ok() -function print_fail($msg) { +function print_fail($msg) +{ echo "[FAIL] $msg\n"; }//end print_fail() -function print_warn($msg) { +function print_warn($msg) +{ echo "[WARN] $msg\n"; }//end print_warn() -function check_rrdcached() { +function check_rrdcached() +{ global $config; - list($host,$port) = explode(':',$config['rrdcached']); + list($host,$port) = explode(':', $config['rrdcached']); if ($host == 'unix') { // Using socket, check that file exists if (!file_exists($port)) { print_fail("$port doesn't appear to exist, rrdcached test failed"); } - } - else { + } else { $connection = @fsockopen($host, $port); if (is_resource($connection)) { fclose($connection); - } - else { + } else { print_fail('Cannot connect to rrdcached instance'); } }