Subversion Repositories vnag

Rev

Rev 39 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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