Subversion Repositories vnag

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

  1. <?php /* <ViaThinkSoftSignature>bVXNXMFkwzws1bw2aTgNQAwu+mCcFkvvhz9FqAKANysqdqSs9FdBjBYSFz7gAW9QyfvDHVfMUs+KcUOru3hgfNToru2AH8y/MAY2yTttNH1drSoKqcFPB0ciqLPt4kQ2kUEqMlFQLtU5Db4Op6ynEpr4b18N3Rpqia0BkdjmfVtJ2Z/q37hMkXkkGYmUXvezGaWuRvfRtTaUkO/G4Dn7XvcHyhiqAqP2YxHAWyNzhC3NV+UkeistXS+3RNDqEthuV/3TjXGGcxGbsXhMAKuZTwCuFnlRoHdHd5zanlyQtMzSSmqS/AhOVgoXFQMgNQgnf24XAtx+GOM55Bgr6hCaDruIE7HpIJ6fKuUU4MiRCTb6IDoeDo71HqZJCn2j4W5jbAFtx88P+jw4wdbhUt1CiCA2zobgnGkEBAZDhafjTS8xLz0mpBWe09aHVxbqKifKBw80w224LlnmiusrsuJCknOJkSnHrCQbccFwSmqDJS3nPGnreZpZG+wJ/vqI9sQhbLtw5tD81eaQoilL6pYmzVqAD2yXBDOjpYOZaxeHQX+rVYPIOle1Sbj7P/1ZeVdf+NENtmiSXA2kdLlDJlqT7l+/+47Dqyh2ebGZND0eB4IAVWqNFT0ofYu0XAuHujf+eFo67Hc/xUEihf5+Jzk/xM6MMhDbrU+drqWoz2mRC3sCGhKgzE/11h04yquozyhZtmxo6ZpdYiib+ttCNmObxa920aB4KPgZzhNfky+oCGPiYTlY+lR42chCxITHRatm4ohK9grUlUwvE8HBgHgXgGQSDZdG9+CjuU/DKz5xyRIuEVz2pAoQNwWVntGz1rgPFe5InljAwNgoVxRYyo3NtRFyxs60QuXwaXLOF4a6lLrTwIMMAMrbq0F1nkdDBRCz39E/60D7I9MQ3yZxwG0Vwi0RDrZRMTBbLDF05haKsdR0hFefoHjMpXi1kuNwRbKPRq+A+3oz+RqK0YNEqIN0K4R3iJ4jqO3EduWKhWxkXIgC2KZngVJqnuB/UWITc43Ge9+32ffjCRC71iK8FzX7i2kn5FSrIiSAU7S99at6AqhM5GgE/rRqmRgZHMte0io4cksGSp9tgsbH22/WK3tlCiJHWwu3JnDhRnI1+aELcBwHUuGoiwB+D0bkpJPXk9yaDJzcdEvskzA4zbOrdNDRPvjwxoAIGUx9gxfNUXDBafXyp6nAwGpm5obK08Kzsve9hU6iO+TAna0wuCptVWC+/ZKeBU+WvYQGntndRJrEntKftUzUsj0Vde8Bc8qcSxWSIgiT1aWsu6TYfMDniKlnWq+SSv3pc1BJX6YdGOgcorgbqLE+sqpQLMqWwwD0vzcC/7LTivSdrIqogz5NOLti2w==</ViaThinkSoftSignature> */ ?>
  2. <?php
  3.  
  4. /*
  5.  * VNag - Nagios Framework for PHP
  6.  * Developed by Daniel Marschall, ViaThinkSoft <www.viathinksoft.com>
  7.  * Licensed under the terms of the Apache 2.0 license
  8.  *
  9.  * Revision 2018-07-19
  10.  */
  11.  
  12. # IMPORTANT
  13. # The log files have to be named YYYY_MM_DD_HH.log and need to be cleared (zeroed) every hour and dumped at least every hour (every minute is also possible)
  14. # Please see the file INSTALL
  15.  
  16. # ---
  17.  
  18. # TODO: trennen zwischen server (ip1, ip2) ermöglichen...
  19. # TODO: prüfen lassen ob die config von ipfm korrekt ist (dumped every 1 hour)
  20. # TODO: monat vor/zurückscrollen? (mon/year)
  21. # TODO: anstelle "year .... overview" lieber "last 12 months"
  22. # TODO: Some hosts might reset the traffic counter at any other day of the month. Should we also support this?
  23.  
  24. # ---
  25.  
  26. declare(ticks=1);
  27.  
  28. # Attention: This constant must be a valid Nagios UOM!
  29. # TODO: Make it configurable via command line? Should we use the UOM from the w/c/l arguments?
  30. define('OUTPUT_UOM', 'GB');
  31.  
  32. # ---
  33.  
  34. class IpFlowMonitorCheck extends VNag {
  35.         protected $argLogDir = null;
  36.         protected $argLimit = null;
  37.  
  38.         public function __construct() {
  39.                 parent::__construct();
  40.  
  41.                 $this->registerExpectedStandardArguments('Vhtwc');
  42.  
  43.                 $this->getHelpManager()->setPluginName('check_ipfm');
  44.                 $this->getHelpManager()->setVersion('1.0');
  45.                 $this->getHelpManager()->setShortDescription('This plugin checks the network traffic monitored by ipfm.');
  46.                 $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.');
  47.                 $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-w currentGB[,expectedGB]] [-c currentGB[,expectedGB]] [-l limitGB] [-L path]');
  48.                 $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com');
  49.  
  50.                 // This is the amount of traffic which is free. Every byte above this limit will cost additional money.
  51.                 // You should therefore set your warning and critical limit below this limit.
  52.                 // Don't set this argument if you have an unlimited connection.
  53.                 // This value is only for visual output. It does not influence the OK/Warning/Critial result.
  54.                 $this->addExpectedArgument($this->argLimit = new VNagArgument('l', 'limit', VNagArgument::VALUE_REQUIRED, 'limit', '"Traffic inclusive" limit (e.g. 10TB)', null));
  55.  
  56.                 $this->addExpectedArgument($this->argLogDir = new VNagArgument('L', 'logdir', VNagArgument::VALUE_REQUIRED, 'path', 'Location of the ipfm log dir (Default: /var/log/ipfm)', '/var/log/ipfm'));
  57.  
  58.                 // When the user writes "-w 10GB" then he actually means "-w @10GB:~" or "-w ~:10GB", so these commands allow this notation:
  59.                 $this->warningSingleValueRangeBehaviors[0]  = self::SINGLEVALUE_RANGE_VAL_GT_X_BAD;
  60.                 $this->warningSingleValueRangeBehaviors[1]  = self::SINGLEVALUE_RANGE_VAL_GT_X_BAD;
  61.                 $this->criticalSingleValueRangeBehaviors[0] = self::SINGLEVALUE_RANGE_VAL_GT_X_BAD;
  62.                 $this->criticalSingleValueRangeBehaviors[1] = self::SINGLEVALUE_RANGE_VAL_GT_X_BAD;
  63.         }
  64.  
  65.         protected function interprete_ipfm_logfile($logfile) {
  66.                 $res = array();
  67.  
  68.                 $ary = file($logfile);
  69.                 foreach ($ary as $a) {
  70.                         $a = trim($a);
  71.                         if ($a == '') continue;
  72.                         if (substr($a, 0, 1) == '#') continue;
  73.                         $a = preg_replace("|\s+|ism", ' ', $a);
  74.                         $bry = explode(' ', $a);
  75.                         $res[$bry[0]] = array($bry[1], $bry[2], $bry[3]);
  76.                 }
  77.  
  78.                 return $res;
  79.         }
  80.  
  81.         protected function cbRun($optional_args=array()) {
  82.                 if (!defined('USE_DYGRAPH')) define('USE_DYGRAPH', false);
  83.  
  84.                 $logDir = $this->argLogDir->getValue();
  85.                 if (!is_dir($logDir)) throw new Exception("Log dir $logDir not found");
  86.  
  87.                 $monthLimit = $this->argLimit->getValue();
  88.                 if (!is_null($monthLimit)) {
  89.                         $p = (new VNagValueUomPair($monthLimit))->normalize(OUTPUT_UOM);
  90.                         $monthLimitValue = $p->getValue();
  91.                         $monthLimitUom = $p->getUom();
  92.                 }
  93.  
  94.                 ob_start();
  95.  
  96.                 ?>
  97.  
  98.                 <script type="text/javascript">
  99.                         google.load("visualization", "1", {packages:['imageareachart', 'corechart']});
  100.                         google.setOnLoadCallback(drawChart);
  101.                         function drawChart() {
  102.                                 var data = new google.visualization.DataTable();
  103.                                 data.addColumn('string', 'Year');
  104.                                 data.addColumn('number', 'Total');
  105.                                 data.addColumn('number', 'In');
  106.                                 data.addRows([
  107.  
  108.                 <?php
  109.  
  110.                 $day = date('d');
  111.                 $mon = date('m');
  112.                 $year = date('Y');
  113.  
  114.                 $didata = '';
  115.                 $logfiles = glob($logDir.'/*.log');
  116.                 sort($logfiles);
  117.  
  118.                 $monthtotal[$year][$mon] = 0;
  119.                 $daystotal = array();
  120.                 $max = 0;
  121.                 $first = true;
  122.                 foreach ($logfiles as $logfile) {
  123.                         $stat = $this->interprete_ipfm_logfile($logfile);
  124.  
  125.                         $date = '';
  126.                         if (preg_match('/^.*_00\.log$/', $logfile)) {
  127.                                 preg_match('@(\d{4})_(\d{2})_(\d{2})@ismU', $logfile, $m);
  128.                                 $t_day = $m[3];
  129.                                 $t_mon = $m[2];
  130.                                 $t_year = $m[1];
  131.                                 // $date = "$t_day.$t_mon.$t_year";
  132.                                 $date = $t_day;
  133.                         //} else if (preg_match('/^.*_(02|04|06|08|10|12|14|16|18|20|22)\.log$/', $logfile, $m)) {
  134.                         //      $date = $m[1].':00';
  135.                         }
  136.  
  137.                         $in = $out = $total = 0;
  138.                         foreach ($stat as $s) {
  139.                                 $in += $s[0];
  140.                                 $out += $s[1];
  141.                                 $total += $s[2];
  142.                         }
  143.  
  144.                         $in    = (new VNagValueUomPair($in.'B'))->normalize(OUTPUT_UOM)->getValue();
  145.                         $out   = (new VNagValueUomPair($out.'B'))->normalize(OUTPUT_UOM)->getValue();
  146.                         $total = (new VNagValueUomPair($total.'B'))->normalize(OUTPUT_UOM)->getValue();
  147.  
  148.                         if (preg_match('/^.*(\d{4})_(\d{2})_(\d{2})_(\d{2})\.log$/', $logfile, $m)) {
  149.                                 $t_year = $m[1];
  150.                                 $t_mon = $m[2];
  151.                                 $t_day = $m[3];
  152.                                 $t_hour = $m[4];
  153.                                 if (isset($monthtotal[$t_year][$t_mon])) {
  154.                                         $monthtotal[$t_year][$t_mon] += $total;
  155.                                 } else {
  156.                                         $monthtotal[$t_year][$t_mon] = $total;
  157.                                 }
  158.  
  159.                                 if (($t_year == $year) && ($t_mon == $mon)) {
  160.                                         if (isset($daystotal[$t_day])) {
  161.                                                 $daystotal[$t_day] += $total;
  162.                                         } else {
  163.                                                 $daystotal[$t_day] = $total;
  164.                                         }
  165.                                         if (!$first) echo ","; else $first = false;
  166.                                         echo "['$date', ".round($total,2).", ".round($in,2)."]\n";
  167.                                         $didata .= '"'.$t_year.'-'.$t_mon.'-'.$t_day.' '.$t_hour.':00:00,'.round($in,2).','.round($out,2).','.round($total,2).'\n" +'."\n";
  168.                                 }
  169.                         }
  170.  
  171.                         if ($total > $max) $max = $total;
  172.                 }
  173.  
  174.                 $num_days_in_month = date('t', mktime(0, 0, 0, $mon, 1, $year));
  175.                 $expected = $monthtotal[$year][$mon]/$day * $num_days_in_month;
  176.  
  177.                 ?>
  178.                         ]);
  179.  
  180.                         var chart = new google.visualization.ImageAreaChart(document.getElementById('chart_div'));
  181.                 <?php if (!USE_DYGRAPH) { ?>
  182.                         chart.draw(data, {width: 800, height: 440, min: 0, max: <?php echo $max; ?>, title: 'Traffic in <?php echo $mon.'/'.$year; ?> [in <?php echo OUTPUT_UOM; ?>/h]'});
  183.                 <?php } ?>
  184.  
  185.                         // ---
  186.  
  187.                         var data_month = new google.visualization.DataTable();
  188.                         data_month.addColumn('string', 'Day');
  189.                         data_month.addColumn('number', 'Total');
  190.  
  191.                         data_month.addRows([
  192.                 <?php
  193.  
  194.                 $first = true;
  195.                 foreach ($daystotal as $t_day => $traffic) {
  196.                         if (!$first) echo ","; else $first = false;
  197.                         echo "['$t_day.$mon.$year', ".round($traffic,2)."]\n";
  198.                 }
  199.  
  200.                 ?>
  201.                         ]);
  202.  
  203.                         var options_month = {
  204.                                 width: 800, height: 440,
  205.                                 vAxis: { viewWindow: { min: 0 } },
  206.                                 title: 'Month overview for <?php echo $mon.'/'.$year; ?> [GiB]'
  207.                         };
  208.  
  209.                         var chart_month = new google.visualization.ColumnChart(document.getElementById('chart_div3'));
  210.                         chart_month.draw(data_month, options_month);
  211.  
  212.                         // ---
  213.  
  214.                         var data_year = new google.visualization.DataTable();
  215.                         data_year.addColumn('string', 'Month/Year');
  216.                         data_year.addColumn('number', 'Total');
  217.  
  218.                         data_year.addRows([
  219.                 <?php
  220.  
  221.                 ksort($monthtotal); // First sort by year
  222.  
  223.                 $first = true;
  224.                 foreach ($monthtotal as $t_year => $x) {
  225.                         ksort($x); // Then sort by month
  226.                         foreach ($x as $t_mon => $traffic) {
  227.                                 if ($t_year != $year) continue; // Only this year
  228.  
  229.                                 $date = "$t_mon/$t_year";
  230.  
  231.                                 if (!$first) echo ","; else $first = false;
  232.                                 echo "['$date', ".round($traffic,2)."]\n";
  233.                         }
  234.                         echo ",['Expected in $mon/$year', $expected]\n";
  235.                 }
  236.  
  237.                 ?>
  238.                         ]);
  239.  
  240.                         var options_year = {
  241.                                 width: 800, height: 440,
  242.                                 vAxis: { viewWindow: { min: 0 } },
  243.                                 title: 'Year <?php echo $year; ?> overview [GiB]'
  244.                         };
  245.  
  246.                         var chart_year = new google.visualization.ColumnChart(document.getElementById('chart_div2'));
  247.                         chart_year.draw(data_year, options_year);
  248.                 }
  249.  
  250.                 </script>
  251.  
  252.                 <?php if (USE_DYGRAPH) { ?>
  253.                         <script type="text/javascript">
  254.                                 g = new Dygraph(
  255.                                         document.getElementById("graphdiv"),
  256.                                         "Date,In,Out,Total\n" +
  257.                                         <?php echo $didata; ?>""
  258.                                 );
  259.                         </script>
  260.                 <?php } ?>
  261.  
  262.                 <?php
  263.  
  264.                 if (!is_null($monthLimit)) {
  265.                         echo "<p>Constraint: Max ".$monthLimitValue.' '.OUTPUT_UOM."/Month</p>";
  266.                 }
  267.  
  268.                 $current = $monthtotal[$year][$mon];
  269.  
  270.                 $fontcolor = 'green';
  271.                 if ($this->checkAgainstCriticalRange($current.OUTPUT_UOM, false, true, 0)) $fontcolor = 'red';
  272.                 if ($this->checkAgainstWarningRange($current.OUTPUT_UOM, false, true, 0))  $fontcolor = '#FF8000';
  273.  
  274.                 if (!is_null($monthLimit)) {
  275.                         echo "<p>This month ($mon/$year): <font color=\"$fontcolor\">".round($current,0)." ".OUTPUT_UOM." (".round($current/$monthLimitValue*100,2)."%)</font></p>";
  276.                 } else {
  277.                         echo "<p>This month ($mon/$year): <font color=\"$fontcolor\">".round($current,0)." ".OUTPUT_UOM."</font></p>";
  278.                 }
  279.  
  280.                 $fontcolor = 'green';
  281.                 if ($this->checkAgainstCriticalRange($expected.OUTPUT_UOM, false, true, 1)) $fontcolor = 'red';
  282.                 if ($this->checkAgainstWarningRange($expected.OUTPUT_UOM, false, true, 1))  $fontcolor = '#FF8000';
  283.  
  284.                 if (!is_null($monthLimit)) {
  285.                         echo "<p>Expected for this month: <font color=\"$fontcolor\">".round($expected,0)." ".OUTPUT_UOM." (".round($expected/$monthLimitValue*100,2)."%)</font></p>";
  286.                 } else {
  287.                         echo "<p>Expected for this month: <font color=\"$fontcolor\">".round($expected,0)." ".OUTPUT_UOM."</font></p>";
  288.                 }
  289.  
  290.                 ?>
  291.  
  292.                 <div id="chart_div"></div>
  293.                 <div id="graphdiv"></div>
  294.                 <div id="chart_div3"></div>
  295.                 <div id="chart_div2"></div>
  296.  
  297.                 <?php
  298.  
  299.                 $html = ob_get_contents();
  300.                 ob_end_clean();
  301.  
  302.                 $this->outputHTML($html, true);
  303.  
  304.                 if (!is_null($monthLimit)) {
  305.                         // TODO: should we put a percentage at "expected"? or if it exceeds, should we show how much it would exceed?
  306.                         $this->setHeadline(round($current,0).' '.OUTPUT_UOM." / ".$monthLimitValue.' '.OUTPUT_UOM." (".round($current/$monthLimitValue*100,2)."%, expected ".round($expected,0).' '.OUTPUT_UOM.") traffic used this month ($mon/$year)", true);
  307.                 } else {
  308.                         $this->setHeadline(round($current,0).' '.OUTPUT_UOM." (expected ".round($expected,0).' '.OUTPUT_UOM.") traffic used this month ($mon/$year)", true);
  309.                 }
  310.  
  311.                 $warn = is_null($this->getWarningRange(0)) ? null : $this->getWarningRange(0)->end->normalize(OUTPUT_UOM)->getValue();
  312.                 $crit = is_null($this->getCriticalRange(0)) ? null : $this->getCriticalRange(0)->end->normalize(OUTPUT_UOM)->getValue();
  313.                 $this->addPerformanceData(new VNagPerformanceData('Current', $current.OUTPUT_UOM, $warn, $crit, 0, is_null($monthLimit) ? null : $monthLimitValue));
  314.  
  315.                 $warn = is_null($this->getWarningRange(1)) ? null : $this->getWarningRange(1)->end->normalize(OUTPUT_UOM)->getValue();
  316.                 $crit = is_null($this->getCriticalRange(1)) ? null : $this->getCriticalRange(1)->end->normalize(OUTPUT_UOM)->getValue();
  317.                 $this->addPerformanceData(new VNagPerformanceData('Expected', $expected.OUTPUT_UOM, $warn, $crit, 0, is_null($monthLimit) ? null : $monthLimitValue));
  318.         }
  319. }
  320.