diff --git a/application/clicommands/MibCommand.php b/application/clicommands/MibCommand.php index 5b42af0..72a3c3a 100644 --- a/application/clicommands/MibCommand.php +++ b/application/clicommands/MibCommand.php @@ -141,7 +141,8 @@ public function purgeAction() $dbresource=$this->Config()->get('config', 'database'); echo "DB name : $dbresource\n"; - $db = IcingaDbConnection::fromResourceName($dbresource)->getConnection(); +// $db = IcingaDbConnection::fromResourceName($dbresource)->getConnection(); + $db = IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter(); $query = $db->delete( $Config->getMIBCacheTableName(), diff --git a/application/clicommands/StatusCommand.php b/application/clicommands/StatusCommand.php index 4491b6d..89954b1 100644 --- a/application/clicommands/StatusCommand.php +++ b/application/clicommands/StatusCommand.php @@ -31,7 +31,8 @@ public function dbAction() $dbresource=$this->Config()->get('config', 'database'); printf("DB name : %s\n",$dbresource); - $dataBase = IcingaDbConnection::fromResourceName($dbresource)->getConnection(); +// $dataBase = IcingaDbConnection::fromResourceName($dbresource)->getConnection(); + $dataBase = IcingaDbConnection::fromResourceName($dbresource)->getDbAdapter(); $query = $dataBase->select()->from($Config->getTrapTableName(),array('COUNT(*)')); printf("Number of traps : %s\n", $dataBase->fetchOne($query) ); diff --git a/application/controllers/HandlerController.php b/application/controllers/HandlerController.php index f229ee8..118d39d 100644 --- a/application/controllers/HandlerController.php +++ b/application/controllers/HandlerController.php @@ -32,7 +32,8 @@ public function indexAction() $this->moduleConfig->getHandlerListTitles(), $this->moduleConfig->getHandlerListDisplayColumns(), $this->moduleConfig->getHandlerColumns(), - $dbConn->getConnection(), + $dbConn->getDbAdapter(), +// $dbConn->getConnection(), $this->view, $this->moduleConfig->urlPath()); @@ -546,7 +547,7 @@ protected function handlerformAction() if ($this->apiMode == TRUE) { $object=$this->getIdoConn()->getHostGroupById($params['hostid']['val']); - if (count($object) == 0 || $params['host_name']['val'] != $object->__name) + if (empty($object) || $params['host_name']['val'] != $object->__name) { $this->_helper->json(array('status'=>"Invalid object group id : Please re enter service")); return; @@ -708,4 +709,4 @@ protected function prepareTabs() ); } -} \ No newline at end of file +} diff --git a/application/controllers/ReceivedController.php b/application/controllers/ReceivedController.php index 0867f71..477e74c 100644 --- a/application/controllers/ReceivedController.php +++ b/application/controllers/ReceivedController.php @@ -2,10 +2,13 @@ namespace Icinga\Module\TrapDirector\Controllers; +use Icinga\Date\DateFormatter; + use Icinga\Web\Url; use Exception; + use Icinga\Module\Trapdirector\TrapsController; /** @@ -89,7 +92,7 @@ public function trapdetailAction() // Store result in array (with Titles). foreach ($queryArray as $key => $val) { if ($key == 'timestamp') { - $cval=strftime('%c',$trapDetail->$key); + $cval=DateFormatter::formatDateTime($trapDetail->$key); } else { $cval=$trapDetail->$key; } @@ -228,4 +231,4 @@ public function deletelinesAction() $this->_helper->json(array('status'=>'unknown action')); } -} \ No newline at end of file +} diff --git a/application/controllers/SettingsController.php b/application/controllers/SettingsController.php index fa11d07..8d7add6 100644 --- a/application/controllers/SettingsController.php +++ b/application/controllers/SettingsController.php @@ -121,6 +121,7 @@ private function check_db() $this->view->ido_db_error=$dberror[0]; $this->view->ido_message='IDO Database : ' . $dberror[1]; + $this->view->ido_message .='
=> Default to API use. Make sure it is configured and check is returning OK!'; } /** @@ -250,10 +251,10 @@ public function indexAction() // Test Database $this->check_db(); - //********* Test API + // Test API $this->check_api(); - //*********** Test snmptrapd alive and options + //Test snmptrapd alive and options list ($this->view->snmptrapdError, $this->view->snmptrapdMessage) = $this->checkSnmpTrapd(); // List DB in $ressources @@ -464,7 +465,9 @@ private function checkSnmpTrapd() exec("$sspath -lun | grep ':162 '",$psOutput); if (count($psOutput) == 0) { - return array(1,'Port UDP/162 is not open : is snmptrapd running?'); + $extra = ""; + if (is_file("/.dockerenv")){ $extra = '
=> ignore if Trapdirector is running in a different Docker container'; } + return array(1,'Port UDP/162 is not open : is snmptrapd running?'. $extra); } $psOutput=array(); $selinux_state = ''; diff --git a/application/controllers/StatusController.php b/application/controllers/StatusController.php index 6f91241..0f5a54c 100644 --- a/application/controllers/StatusController.php +++ b/application/controllers/StatusController.php @@ -131,7 +131,7 @@ public function mibAction() /** Check for mib file UPLOAD */ if (isset($_FILES['mibfile'])) { - $name=filter_var($_FILES['mibfile']['name'],FILTER_SANITIZE_STRING); + $name=htmlspecialchars($_FILES['mibfile']['name']); $DirConf=explode(':',$this->Config()->get('config', 'snmptranslate_dirs')); $destDir=array_shift($DirConf); if (!is_dir($destDir)) @@ -147,7 +147,7 @@ public function mibAction() else { $destination = $destDir .'/'.$name; //$this->Module()->getBaseDir() . "/mibs/$name"; - $sourceTmpNam=filter_var($_FILES['mibfile']['tmp_name'],FILTER_SANITIZE_STRING); + $sourceTmpNam=htmlspecialchars($_FILES['mibfile']['tmp_name']); if (move_uploaded_file($sourceTmpNam,$destination)===false) { $this->view->uploadStatus="ERROR, file $destination not loaded. Check file and path name or selinux violations"; diff --git a/library/Trapdirector/Config/MIBLoader.php b/library/Trapdirector/Config/MIBLoader.php index b1ac98a..3b0197d 100644 --- a/library/Trapdirector/Config/MIBLoader.php +++ b/library/Trapdirector/Config/MIBLoader.php @@ -174,7 +174,7 @@ public function translateOID($oid) } $retArray['description']=null; /* TODO : put in DB (but maybe only in trap_class). - $query=$db->getConnection()->insert( + $query=$db->getDbAdapter()->insert( $this->getModuleConfig()->getTrapRuleName(), $array( 'oid' => diff --git a/library/Trapdirector/Icinga2API.php b/library/Trapdirector/Icinga2API.php index 55a3d30..8983118 100644 --- a/library/Trapdirector/Icinga2API.php +++ b/library/Trapdirector/Icinga2API.php @@ -285,6 +285,28 @@ public function getServiceById($name) return $services; } + + /** Get services object by id (host!name) + * does not catch exceptions + * @param $name string service __name (host!name) + * @return array service id + */ + public function getNOKService() + { + $filter = 'service.state != ServiceOK && !(service.acknowledgement || service.downtime_depth || service.host.downtime_depth)'; + $services = $this->standardQuery( + 'service', + $filter, + array('__name','name','last_check','host_name','state') + ); + + foreach ( array_keys($services) as $key ) + { + $services[$key]->id = $services[$key]->__name; + } + + return $services; + } } diff --git a/library/Trapdirector/Tables/TrapTable.php b/library/Trapdirector/Tables/TrapTable.php index 88f3741..1eba276 100644 --- a/library/Trapdirector/Tables/TrapTable.php +++ b/library/Trapdirector/Tables/TrapTable.php @@ -7,6 +7,8 @@ use Icinga\Data\Selectable; use Icinga\Data\Paginatable; +use Icinga\Date\DateFormatter; + use Icinga\Web\Request; use Icinga\Web\Widget; @@ -50,7 +52,7 @@ protected function renderDayIfNew($timestamp) if (in_array(setlocale(LC_ALL, 0), array('en_US.UTF-8', 'C'))) { $day = date('l, jS F Y', (int) $timestamp); } else { - $day = strftime('%A, %e. %B, %Y', (int) $timestamp); + $day = DateFormatter::formatDate((int) $timestamp); } if ($this->lastDay === $day) { @@ -134,7 +136,7 @@ public function getOffset() { return $this->offset; } - + #[\ReturnTypeWillChange] abstract function count(); public function getPaginator() @@ -233,4 +235,4 @@ protected function applyFiltersToQuery($query) return $query; } -} \ No newline at end of file +} diff --git a/library/Trapdirector/Tables/TrapTableHostList.php b/library/Trapdirector/Tables/TrapTableHostList.php index 19cc380..260fcc8 100644 --- a/library/Trapdirector/Tables/TrapTableHostList.php +++ b/library/Trapdirector/Tables/TrapTableHostList.php @@ -2,6 +2,7 @@ namespace Icinga\Module\TrapDirector\Tables; +use Icinga\Date\DateFormatter; use Icinga\Web\Request; use Icinga\Web\Url; @@ -112,7 +113,7 @@ public function render() // Check missing value if (property_exists($row, $rowkey)) { - $val = ($rowkey=='last_sent') ? strftime('%c',$row->$rowkey) : $row->$rowkey; + $val = ($rowkey=='last_sent') ? DateFormatter::formatDateTime($row->$rowkey) : $row->$rowkey; } else { $val = '-'; } diff --git a/library/Trapdirector/Tables/TrapTableList.php b/library/Trapdirector/Tables/TrapTableList.php index d5ebf5e..685fb41 100644 --- a/library/Trapdirector/Tables/TrapTableList.php +++ b/library/Trapdirector/Tables/TrapTableList.php @@ -2,6 +2,7 @@ namespace Icinga\Module\TrapDirector\Tables; +use Icinga\Date\DateFormatter; use Icinga\Web\Request; use Icinga\Web\Url; @@ -68,7 +69,7 @@ public function render() // Check missing value if (property_exists($row, $rowkey)) { - $val = ($rowkey=='timestamp') ? strftime('%T',$row->$rowkey) : $row->$rowkey; + $val = ($rowkey=='timestamp') ? DateFormatter::formatTime($row->$rowkey) : $row->$rowkey; } else { $val = '-'; } @@ -227,4 +228,4 @@ protected function applyFiltersToQuery($query) return $query; } -} \ No newline at end of file +} diff --git a/library/Trapdirector/TrapsActions/UIDatabase.php b/library/Trapdirector/TrapsActions/UIDatabase.php index 395e3e0..17edc09 100644 --- a/library/Trapdirector/TrapsActions/UIDatabase.php +++ b/library/Trapdirector/TrapsActions/UIDatabase.php @@ -29,7 +29,7 @@ class DBException extends Exception * @param int $code * @param Exception $previous */ - public function __construct(array $retarray, string $message = null, int $code = 0, Exception $previous = null) + public function __construct(array $retarray, string $message = "", int $code = 0, Exception $previous = null) { parent::__construct($message,$code,$previous); $this->returnArray = $retarray; @@ -224,7 +224,8 @@ public function getDb() public function getDbConn() { if ($this->getDb() == null) return null; - return $this->getDb()->getConnection(); + return $this->getDb()->getDbAdapter(); +// return $this->getDb()->getConnection(); } /** @@ -330,4 +331,4 @@ public function testGetIdoDb() return; } -} \ No newline at end of file +} diff --git a/library/Trapdirector/TrapsProcess/MibDatabase.php b/library/Trapdirector/TrapsProcess/MibDatabase.php index 3031984..f6a5b16 100644 --- a/library/Trapdirector/TrapsProcess/MibDatabase.php +++ b/library/Trapdirector/TrapsProcess/MibDatabase.php @@ -80,7 +80,8 @@ private function update_oid_update() ':syntax' => $this->oidDesc['syntax']==null??'null', ':type_enum' => $this->oidDesc['type_enum']??'null', ':description' => $this->oidDesc['description']??'null', - ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']] + ':id' => $this->dbOidIndex[$this->oidDesc['oid']]['id'] +// ':id' => $this->dbOidAll[$this->dbOidIndex[$this->oidDesc['oid']]['id']] ); if ($sqlQuery->execute($sqlParam) === false) { @@ -191,4 +192,4 @@ private function cache_db_objects($trapId) } -} \ No newline at end of file +} diff --git a/library/Trapdirector/TrapsProcess/Trap.php b/library/Trapdirector/TrapsProcess/Trap.php index 3cb1170..fb2b7d9 100644 --- a/library/Trapdirector/TrapsProcess/Trap.php +++ b/library/Trapdirector/TrapsProcess/Trap.php @@ -92,7 +92,7 @@ function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode=' $this->trapModuleConfig=$this->icingaweb2Etc."/modules/trapdirector/config.ini"; $this->icingaweb2Ressources=$this->icingaweb2Etc."/resources.ini"; - //************* Setup logging + // Setup logging $this->logging = new Logging(); if ($baseLogLevel != null) { @@ -110,7 +110,7 @@ function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode=' $this->trapApiClass = new TrapApi($this->logging); - //*************** Get options from ini files + // Get options from ini files if (! is_file($this->trapModuleConfig)) { throw new Exception("Ini file ".$this->trapModuleConfig." does not exists"); @@ -123,18 +123,19 @@ function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode=' } $this->getMainOptions($trapConfig); // Get main options from ini file - //*************** Setup database class & get options + try { + // Setup database class & get options $this->setupDatabase($trapConfig); $this->getDatabaseOptions(); // Get options in database - //*************** Setup API + // Setup API if ($this->apiUse === true) $this->getAPI(); // Setup API - //*************** Setup MIB + // Setup MIB $this->mibClass = new Mib($this->logging,$this->trapsDB,$this->snmptranslate,$this->snmptranslate_dirs); // Create Mib class - //*************** Setup Rule + // Setup Rule $this->ruleClass = new Rule($this); //< Create Rule class $this->trapData=array( // TODO : put this in a reset function (DAEMON_MODE) @@ -145,10 +146,10 @@ function __construct($etcDir='/etc/icingaweb2',$baseLogLevel=null,$baseLogMode=' 'trap_oid' => 'unknown' ); - //*************** Setup Plugins + // Setup Plugins //Create plugin class. Plugins are not loaded here, but by calling registerAllPlugins $this->pluginClass = new Plugins($this); - + }catch (Exception $e){ return; } } @@ -323,10 +324,9 @@ public function translateOID($oid) if (($ret_code=$db_conn->query($sql)) === false) { $this->logging->log('No result in query : ' . $sql,ERROR,''); } - $name=$ret_code->fetch(); - if ($name['name'] != null) - { - return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']); + else { + if (($name=$ret_code->fetch()) !== false) + return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']); } // Also check if it is an instance of OID @@ -337,10 +337,9 @@ public function translateOID($oid) if (($ret_code=$db_conn->query($sql)) === false) { $this->logging->log('No result in query : ' . $sql,ERROR,''); } - $name=$ret_code->fetch(); - if ($name['name'] != null) - { - return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']); + else { + if (($name=$ret_code->fetch()) !== false) + return array('trap_name_mib'=>$name['mib'],'trap_name'=>$name['name']); } // Try to get oid name from snmptranslate @@ -575,35 +574,44 @@ protected function getRules($ip,$oid) $rule_ret_key++; continue; } - // TODO : get hosts IP by API + if (isset($rule['host_group_name']) && $rule['host_group_name']!=null) { // get ips of group members by oid - $db_conn2=$this->trapsDB->db_connect_ido(); - $sql="SELECT m.host_object_id, a.address as ip4, a.address6 as ip6, b.name1 as host_name + if ($this->apiUse === false) + { + $db_conn2=$this->trapsDB->db_connect_ido(); + $sql="SELECT m.host_object_id, a.address, a.address6, b.name1 as name FROM icinga_objects as o LEFT JOIN icinga_hostgroups as h ON o.object_id=h.hostgroup_object_id LEFT JOIN icinga_hostgroup_members as m ON h.hostgroup_id=m.hostgroup_id LEFT JOIN icinga_hosts as a ON a.host_object_id = m.host_object_id LEFT JOIN icinga_objects as b ON b.object_id = a.host_object_id WHERE o.name1='".$rule['host_group_name']."';"; - if (($ret_code2=$db_conn2->query($sql)) === false) { - $this->logging->log('No result in query : ' . $sql,WARN,''); - continue; + if (($ret_code2=$db_conn2->query($sql)) === false) { + $this->logging->log('No result in query : ' . $sql,WARN,''); + continue; + } + $grouphosts=$ret_code2->fetchAll(); + }else{ + $api = $this->getAPI(); + $api->setCredentials($this->apiUsername, $this->apiPassword); + $grouphosts=$api->getHostsIPByHostGroup($rule['host_group_name']); } - $grouphosts=$ret_code2->fetchAll(); //echo "rule grp :\n";print_r($grouphosts);echo "\n"; foreach ( $grouphosts as $host) { - //echo $host['ip4']."\n"; - if ($host['ip4']==$ip || $host['ip6']==$ip) + if( is_object( $host ) ) $host=(array)$host; + //echo $host['address']."\n"; + if ($host['address']==$ip || $host['address6']==$ip) { //echo "Rule added \n"; $rules_ret[$rule_ret_key]=$rules_all[$key]; - $rules_ret[$rule_ret_key]['host_name']=$host['host_name']; + $rules_ret[$rule_ret_key]['host_name']=$host['name']; $rule_ret_key++; } } } + } //echo "rule rest :\n";print_r($rules_ret);echo "\n";exit(0); return $rules_ret; @@ -856,20 +864,27 @@ public function add_rule_final($time) public function reset_services() { // Get all services not in 'ok' state - $sql_query="SELECT s.service_object_id, - UNIX_TIMESTAMP(s.last_check) AS last_check, - s.current_state as state, - v.name1 as host_name, - v.name2 as service_name - FROM icinga_servicestatus AS s - LEFT JOIN icinga_objects as v ON s.service_object_id=v.object_id - WHERE s.current_state != 0;"; - $db_conn=$this->trapsDB->db_connect_ido(); - if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception. - $this->logging->log('No result in query : ' . $sql_query,ERROR,''); - return 0; + if ($this->apiUse === false) + { + $sql_query="SELECT s.service_object_id, + UNIX_TIMESTAMP(s.last_check) AS last_check, + s.current_state as state, + v.name1 as host_name, + v.name2 as name + FROM icinga_servicestatus AS s + LEFT JOIN icinga_objects as v ON s.service_object_id=v.object_id + WHERE s.current_state != 0;"; + $db_conn=$this->trapsDB->db_connect_ido(); + if (($services_db=$db_conn->query($sql_query)) === false) { // set err to 1 to throw exception. + $this->logging->log('No result in query : ' . $sql_query,ERROR,''); + return 0; + } + $services=$services_db->fetchAll(); + }else{ + $api = $this->getAPI(); + $api->setCredentials($this->apiUsername, $this->apiPassword); + $services=$api->getNOKservice(); } - $services=$services_db->fetchAll(); // Get all rules $sql_query="SELECT host_name, service_name, revert_ok FROM ".$this->dbPrefix."rules where revert_ok != 0;"; @@ -885,13 +900,14 @@ public function reset_services() $numreset=0; foreach ($rules as $rule) { + if( is_object( $services ) ) $services=(array)$services; foreach ($services as $service) { - if ($service['service_name'] == $rule['service_name'] && + if ($service['name'] == $rule['service_name'] && $service['host_name'] == $rule['host_name'] && ($service['last_check'] + $rule['revert_ok']) < $now) { - $this->serviceCheckResult($service['host_name'],$service['service_name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds'); + $this->serviceCheckResult($service['host_name'],$service['name'],0,'Reset service to OK after '.$rule['revert_ok'].' seconds'); $numreset++; } } @@ -903,4 +919,4 @@ public function reset_services() } -} \ No newline at end of file +} diff --git a/library/Trapdirector/TrapsProcess/TrapConfig.php b/library/Trapdirector/TrapsProcess/TrapConfig.php index 9f05902..ceb32a5 100644 --- a/library/Trapdirector/TrapsProcess/TrapConfig.php +++ b/library/Trapdirector/TrapsProcess/TrapConfig.php @@ -189,7 +189,7 @@ protected function setupDatabase($trapConfig) $this->logging->log("API Use : ".print_r($this->apiUse,true),DEBUG ); //TODO enable this again when API queries are all done : - //if ($this->apiUse === true) return; // In case of API use, no IDO is necessary + if ($this->apiUse === true) return; // In case of API use, no IDO is necessary // IDO Database if (!array_key_exists('IDOdatabase',$trapConfig['config'])) @@ -208,4 +208,4 @@ protected function setupDatabase($trapConfig) $this->trapsDB->setupIDO($dbConfig[$dbIdoName]); } -} \ No newline at end of file +} diff --git a/module.info b/module.info index 757db27..cc236ea 100644 --- a/module.info +++ b/module.info @@ -1,5 +1,4 @@ Name: Icinga SNMP trap director -Version: 1.0.7a -Depends: monitoring +Version: 1.0.7b Description: SNMP traps configuration tool for Icinga 2 Receives traps and updates service state based on rules