Ignore:
Timestamp:
Jan 8, 2016, 11:00:11 PM (9 years ago)
Author:
chronos
Message:
  • Modified: Network configure actions now can be executed through cmd.php interface using "php cmd.php config <action>".
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/Modules/NetworkConfigRouterOS/Generators/NetwatchImport.php

    r738 r781  
    11<?php
    22
    3 if(isset($_SERVER['REMOTE_ADDR'])) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
     3class ConfigRouterOSNetwatchImport extends NetworkConfigItem
     4{
     5  function NetwatchImport()
     6  {
     7    $StartTime = time();
    88
    9 function NetwatchImport()
    10 {
    11   global $System, $Config;
     9    // Load all interfaces to memory
     10    $Interfaces = array();
     11    $DbResult = $this->Database->select('NetworkInterface', '`Id`, `LocalIP` AS `IP`, `Online`, 0 AS `NewOnline`');
     12    while($DbRow = $DbResult->fetch_assoc())
     13      $Interfaces[$DbRow['IP']] = $DbRow;
    1214
    13   $StartTime = time();
     15      // Load netwatch status from all DHCP routers
     16      $DbResult3 = $this->Database->query('SELECT `DHCP`, `AddressRange`, `Mask` FROM `NetworkSubnet` '.
     17          'WHERE (`Configure` = 1) AND (`Member` IS NULL) GROUP BY DHCP');
     18      while($Subnet = $DbResult3->fetch_assoc())
     19      {
     20        echo($Subnet['AddressRange'].'/'.$Subnet['Mask'].' on router '.$Subnet['DHCP']."\n");
     21        $Routerboard = new RouterosAPI();
     22        $Routerboard->Connect($Subnet['DHCP'], $this->System->Config['API']['UserName'],
     23          $this->System->Config['API']['Password']);
     24        if(!$Routerboard->Connected) continue;
     25        $Routerboard->Write('/tool/netwatch/getall', false);
     26        $Routerboard->Write('=.proplist=host,status');
     27        $Read = $Routerboard->Read(false);
     28        $List = $Routerboard->ParseResponse($Read);
     29        foreach($List as $Properties)
     30        {
     31          $IP = $Properties['host'];
     32          if($Properties['status'] == 'up') $Online = 1;
     33          else $Online = 0;
    1434
    15   // Load all interfaces to memory
    16   $Interfaces = array();
    17   $DbResult = $System->Database->select('NetworkInterface', '`Id`, `LocalIP` AS `IP`, `Online`, 0 AS `NewOnline`');
    18   while($DbRow = $DbResult->fetch_assoc())
    19     $Interfaces[$DbRow['IP']] = $DbRow;
     35          if($Online)
     36          {
     37            if(array_key_exists($IP, $Interfaces))
     38              $Interfaces[$IP]['NewOnline'] = 1;
     39              else echo('IP '.$IP.' not found.'."\n");
     40          }
     41        }
     42      }
    2043
    21   // Load netwatch status from all DHCP routers
    22   $DbResult3 = $System->Database->query('SELECT `DHCP`, `AddressRange`, `Mask` FROM `NetworkSubnet` '.
    23     'WHERE (`Configure` = 1) AND (`Member` IS NULL) GROUP BY DHCP');
    24   while($Subnet = $DbResult3->fetch_assoc())
    25   {
    26     echo($Subnet['AddressRange'].'/'.$Subnet['Mask'].' on router '.$Subnet['DHCP']."\n");
    27     $Routerboard = new RouterosAPI();
    28     $Routerboard->Connect($Subnet['DHCP'], $Config['API']['UserName'], $Config['API']['Password']);
    29     if(!$Routerboard->Connected) continue;
    30     $Routerboard->Write('/tool/netwatch/getall', false);
    31     $Routerboard->Write('=.proplist=host,status');
    32     $Read = $Routerboard->Read(false);
    33     $List = $Routerboard->ParseResponse($Read);
    34     foreach($List as $Properties)
    35     {
    36       $IP = $Properties['host'];
    37       if($Properties['status'] == 'up') $Online = 1;
    38         else $Online = 0;
     44      foreach($Interfaces as $Index => $Interface)
     45      {
     46        // Update last online time if still online
     47        if($Interface['NewOnline'])
     48          $DbResult = $this->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
     49              array('LastOnline' => TimeToMysqlDateTime($StartTime)));
    3950
    40       if($Online)
     51          if($Interface['Online'] != $Interface['NewOnline'])
     52          {
     53            // Online state changed
     54            $DbResult = $this->Database->query('INSERT INTO `NetworkInterfaceUpDown` (`Interface`,
     55        `State`, `Time`, `Duration`) VALUES ('.$Interface['Id'].', '.$Interface['NewOnline'].', "'.
     56                TimeToMysqlDateTime($StartTime).'", NULL)');
     57            // Update previous record duration in UpDown table
     58            $System->Database->query('UPDATE `NetworkInterfaceUpDown` AS `TM` SET `Duration` = TIMESTAMPDIFF(SECOND, '.
     59                '`TM`.`Time`, (SELECT `Time` FROM (SELECT * FROM `NetworkInterfaceUpDown`) AS `TA` WHERE (`TA`.`Time` > `TM`.`Time`) '.
     60                'AND (`TA`.`Interface`=`TM`.`Interface`) ORDER BY `TA`.`Time` ASC LIMIT 1)) '.
     61                'WHERE (`TM`.`Duration` IS NULL) AND (`TM`.`Interface` ='.$Interface['Id'].')');
     62            $System->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
     63                array('Online' => $Interface['NewOnline']));
     64          }
     65      }
     66
     67      // Set offline all interfaces which were not updated as online
     68      $DbResult = $this->Database->select('NetworkInterface', '*', '(`Online` = 1) AND '.
     69          '(`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'")');
     70      while($DbRow = $DbResult->fetch_assoc())
    4171      {
    42         if(array_key_exists($IP, $Interfaces))
    43           $Interfaces[$IP]['NewOnline'] = 1;
    44           else echo('IP '.$IP.' not found.'."\n");
     72        echo('IP '.$DbRow['LocalIP'].' online but time not updated.'."\n");
    4573      }
    46     }
     74      $DbResult = $this->Database->select('NetworkInterface', '*', '(`Online` = 0) AND '.
     75          '(`LastOnline` >= "'.TimeToMysqlDateTime($StartTime).'")');
     76      while($DbRow = $DbResult->fetch_assoc())
     77      {
     78        echo('IP '.$DbRow['LocalIP'].' not online but time updated.'."\n");
     79      }
     80
     81      // Update device online state
     82      $DbResult = $this->Database->select('NetworkInterface', '`Device`, SUM(`Online`) AS `SumOnline`', '`Online` = 1 GROUP BY `Device`');
     83      while($Device = $DbResult->fetch_assoc())
     84      {
     85        if($Device['SumOnline'] > 0)
     86          $System->Database->update('NetworkDevice', 'Id='.$Device['Device'], array('LastOnline' => TimeToMysqlDateTime($StartTime), 'Online' => 1));
     87      }
     88      $DbResult = $this->Database->update('NetworkDevice', '`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'"', array('Online' => 0));
     89
     90      // Update interface online statistics
     91      $DbResult = $this->Database->select('NetworkInterface', 'Id', '`Online` = 1');
     92      while($Interface = $DbResult->fetch_assoc())
     93      {
     94        $DbResult2 = $this->Database->select('NetworkInterfaceStat', '*', '(`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
     95        if($DbResult2->num_rows == 0) $System->Database->query('REPLACE INTO `NetworkInterfaceStat` (`NetworkInterface`, `Time`, `PingCount`) VALUES ("'.$Interface['Id'].'", DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"), 1)');
     96        else $this->Database->query('UPDATE `NetworkInterfaceStat` SET `PingCount` = `PingCount` + 1 WHERE (`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
     97      }
    4798  }
    4899
    49   foreach($Interfaces as $Index => $Interface)
     100  function Run()
    50101  {
    51     // Update last online time if still online
    52     if($Interface['NewOnline'])
    53       $DbResult = $System->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
    54         array('LastOnline' => TimeToMysqlDateTime($StartTime)));
    55 
    56     if($Interface['Online'] != $Interface['NewOnline'])
    57     {
    58       // Online state changed
    59       $DbResult = $System->Database->query('INSERT INTO `NetworkInterfaceUpDown` (`Interface`,
    60         `State`, `Time`, `Duration`) VALUES ('.$Interface['Id'].', '.$Interface['NewOnline'].', "'.
    61          TimeToMysqlDateTime($StartTime).'", NULL)');
    62       // Update previous record duration in UpDown table
    63       $System->Database->query('UPDATE `NetworkInterfaceUpDown` AS `TM` SET `Duration` = TIMESTAMPDIFF(SECOND, '.
    64       '`TM`.`Time`, (SELECT `Time` FROM (SELECT * FROM `NetworkInterfaceUpDown`) AS `TA` WHERE (`TA`.`Time` > `TM`.`Time`) '.
    65       'AND (`TA`.`Interface`=`TM`.`Interface`) ORDER BY `TA`.`Time` ASC LIMIT 1)) '.
    66       'WHERE (`TM`.`Duration` IS NULL) AND (`TM`.`Interface` ='.$Interface['Id'].')');
    67       $System->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
    68         array('Online' => $Interface['NewOnline']));
    69     }
    70   }
    71 
    72   // Set offline all interfaces which were not updated as online
    73   $DbResult = $System->Database->select('NetworkInterface', '*', '(`Online` = 1) AND '.
    74     '(`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'")');
    75   while($DbRow = $DbResult->fetch_assoc())
    76   {
    77     echo('IP '.$DbRow['LocalIP'].' online but time not updated.'."\n");
    78   }
    79   $DbResult = $System->Database->select('NetworkInterface', '*', '(`Online` = 0) AND '.
    80     '(`LastOnline` >= "'.TimeToMysqlDateTime($StartTime).'")');
    81   while($DbRow = $DbResult->fetch_assoc())
    82   {
    83     echo('IP '.$DbRow['LocalIP'].' not online but time updated.'."\n");
    84   }
    85 
    86   // Update device online state
    87   $DbResult = $System->Database->select('NetworkInterface', '`Device`, SUM(`Online`) AS `SumOnline`', '`Online` = 1 GROUP BY `Device`');
    88   while($Device = $DbResult->fetch_assoc())
    89   {
    90     if($Device['SumOnline'] > 0)
    91       $System->Database->update('NetworkDevice', 'Id='.$Device['Device'], array('LastOnline' => TimeToMysqlDateTime($StartTime), 'Online' => 1));
    92   }
    93   $DbResult = $System->Database->update('NetworkDevice', '`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'"', array('Online' => 0));
    94 
    95   // Update interface online statistics
    96   $DbResult = $System->Database->select('NetworkInterface', 'Id', '`Online` = 1');
    97   while($Interface = $DbResult->fetch_assoc())
    98   {
    99     $DbResult2 = $System->Database->select('NetworkInterfaceStat', '*', '(`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
    100     if($DbResult2->num_rows == 0) $System->Database->query('REPLACE INTO `NetworkInterfaceStat` (`NetworkInterface`, `Time`, `PingCount`) VALUES ("'.$Interface['Id'].'", DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"), 1)');
    101       else $System->Database->query('UPDATE `NetworkInterfaceStat` SET `PingCount` = `PingCount` + 1 WHERE (`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
     102    RepeatFunction(60, array($this, 'NetwatchImport'));
    102103  }
    103104}
    104 
    105 RepeatFunction(60, 'NetwatchImport');
Note: See TracChangeset for help on using the changeset viewer.