Debian Codegraph @

local/checkbandwidth

raw
1 #!/usr/bin/perl
2
3 =pod
4
5 =head1 NAME
6
7 checkbandwidth - Alert on bandwidth high/low levels for a host/interface
8
9 =head1 DESCRIPTION
10
11 The checkbandwidth script uses the perl SNMP module to collect, store
12 and analyze date from the IF-MIB::ifXTable for the ifHCInOctets and
13 ifHCOutOctets counters. It can be configured with high/low levels and
14 issue warnings, either through email or via output text and exit
15 codes. Specifically, the exit codes (1 = warning, 2 = error) and text
16 output are designed to be used with Nagios. It calculates bandwidth
17 by comparing the values from the last run against the values from the
18 current run and the amonut of time that has passeed between the two
19 runs [i.e. bandwidth = (this_run - last_run)/time]. Because we need
20 data from two runs, the first time it is run after configuration will
21 never detect an error until the second run.
22
23 Data is stored in ~/.snmp/checkbandwidth.json, which can be
24 removed/unlinked to reset the command's data store if needed. Or the
25 -r switch can be used to just reset the data without wiping the
26 configuration.
27
28 =head1 SYNOPSIS
29
30 1) Setup your snmp.conf file with authentication parameters for your system:
31
32 # snmpconf -g basic_setup
33
34 2) Add the interface on the host you want monitor, along with an optional
35 "threshold" parameters that you want to be warned about:
36
37 # checkbandwidth --add-interface eth0 \
38 --max-in-bandwidth [email protected] \
39 foo.example.com
40
41 3A) Then run the tool against the host on a regular basis (eg, every 5
42 minutes in cron):
43
44 # checkbandwidth foo.example.com
45 foo.example.com wlan1 49200.1426 in 5538.7522 out (B/s) IO
46
47 The numbers reported are the measured bandwidth during this run. The
48 "IO" letters are flags letting you know that the (I)nput or (O)utput
49 values are out of expected range.
50
51 3B) Run the tool inside of nagios:
52
53 define command {
54 command_name checkbandwidth
55 # specific path to vendor_perl is to fix vir's /usr/local installation
56 command_line /usr/bin/perl /usr/local/bin/checkbandwidth -L /var/spool/nagios/.snmp/checkbandwidth.json.lock -N -s $ARG1$
57 }
58
59 =head1 OPTIONS
60
61 =head2 Configuration and setup:
62
63 =over
64
65 =item -i STRING
66
67 =item --add-interface=STRING
68
69 Add this interface to the list of things to report data for.
70
71 =item -I INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
72
73 =item --max-in-bandwidth=INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
74
75 =item -O INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
76
77 =item --max-out-bandwidth=INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
78
79 These setup options specify an maximum input and/or output bandwidth that will:
80
81 1) When running as a nagios script (using the --nagios flag), the
82 script will display an appropriate message and exit with a return
83 code based on whether the string passed to the flag is 'nagioswarn'
84 or 'nagioscritical'.
85
86 2) When run manually or via cron, then the checkbandwidth will send an
87 email address to ADDRESS about the error.
88
89 The INT field should be the bandwidth above which the error or warning
90 should occur. If the :COUNT field is included, no messages will be
91 sent/generated until at least the COUNT'th time is seen (default: 1).
92 The frequency of the count is dependent on often often the script gets
93 called or the loop frequency occurs (--loop).
94
95 Note that the --add-interface (-i) flag is required for this flag to be useful.
96
97 See the EXAMPLES section below for more usage.
98
99 =item -J INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
100
101 =item --min-in-bandwidth=INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
102
103 =item -Q INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
104
105 =item --min-out-bandwidth=INT[:COUNT]=( 'nagioswarn' | 'nagioscritical' | ADDRESS )
106
107 These two are similar to --max-in-bandwidth and --max-out-bandwidth,
108 but set the low-water mark thresholds for an interface.
109
110 =back
111
112 =head2 Operation:
113
114 =over
115
116 =item -c STRING
117
118 =item --cache-file=STRING
119
120 Location to store persistent data file, which is a JSON encoded structure.
121 This defaults to ~/.snmp/checkbandwidth.json.
122
123 =item -r
124
125 =item --reset
126
127 Ignore all past data and restart the statists collection from scratch
128 for all hosts/interfaces. This wipes the collected data without
129 wiping the configuration min/max warning/critical levels.
130
131
132
133 =item -l INTEGER
134
135 =item --loop=INTEGER
136
137 Run as a daemon and loop forever, displaying bandwidth performing
138 checks every INTEGER seconds and displaying an output summary line.
139
140 =back
141
142 =head2 Nagios mode:
143
144 The following options only make sense when acting as an interface with
145 nagios. An example nagios command definition is as follows:
146
147 define command {
148 command_name checkbandwidth
149 command_line /usr/local/bin/checkbandwidth -c /var/spool/nagios/.snmp/checkbandwidth.nagios.json -L /var/spool/nagios/.snmp/checkbandwidth.nagios.json.lock -N $ARG1
150 }
151
152 Note that if you need to specify perl module paths, you'll need to call it as:
153
154 /usr/bin/perl -I /usr/lib64/perl5/vendor_perl/ /usr/local/bin/checkbandwidth
155
156 You can then use a service definition such as this one:
157
158 define service {
159 service_description bandwidth
160 host_name localhost
161 check_command checkbandwidth!localhost
162 use ...
163
164 }
165
166 Recommendation: Use a different configuration file for nagios hosts
167 than other command line usage.
168
169 Recommendation: Use a lock file (-L) to ensure that data from two
170 parallel calls in nagios won't be written to at once, causing the file
171 to be corrupted.
172
173 Recommendation: If you're monitoring a large number of hosts, use a
174 sepearate configuration file (and lock file) for each host by passing
175 an argument like -c /var/spool/nagios/.snmp/checkbandwidth.nagios.$ARG1.json
176
177 =over
178
179 =item -N
180
181 =item --nagios
182
183 Operate in nagios mode, which will display appropriate nagios display
184 error codes and exit with an exit code that nagios will process.
185
186 =item -s
187
188 =item --nagios-summary
189
190 Place a basic summary line of bandwidth in the output even when no
191 errors are currently present. Otherwise, the output will simply be
192 "All interfaces ok"
193
194
195
196 =item -L LOCKFILE
197
198 =item --lock-file LOCKFILE
199
200 Use this file as a lockfile to ensure multiple checkbandwidth's
201 running won't try to write to the file at the same time.
202
203 =back
204
205 =head2 Sending mail on errors from cron
206
207 When not in nagios mode, checkbandwidth will send mail if an error
208 condition is reached. The following options specify the SMTP server
209 parameters used to send mail.
210
211 =over
212
213 =item -S STRING
214
215 =item --smtp-server=STRING
216
217 The hostname or IP address of the SMTP serve to use.
218
219
220
221 =item -P INTEGER
222
223 =item --port=INTEGER
224
225 The port number of the SMTP server to use.
226
227
228
229 =item -F STRING
230
231 =item --from=STRING
232
233 The email address to put in the From: line.
234
235
236 =item -q
237
238 =item --quiet
239
240 Don't output data to the terminal (i.e., email only).
241
242 =back
243
244 =head2 Debugging:
245
246 =over
247
248 =item -d
249
250 =item --dump
251
252 Dump the raw JSON data when finished.
253
254 =item -v
255
256 =item --verbose
257
258 Log (debugging) messages to stderr about what is being done
259
260 =item -n
261
262 =item --noop
263
264 Don't store the collected information from the SNMP agent to the
265 persistent data storage file. I.E., only compare the results to last time.
266
267 [This is highly useful when you just want to check the server from the
268 command line using a data store configuration cache that is being used
269 by another daemon (--loop mode) or by nagios], without affecting the
270 timing between runs]
271
272 =back
273
274 =head1 EXAMPLES
275
276 =head2 Example Setup
277
278 With these goals:
279
280 * monitor eth0
281 * send a message to root@localhost when the input bandwidth goes above 50000 B/s
282 * send a message to ops@localhost when the input bandwidth goes above 100000 B/s
283
284 This can be configured as following:
285
286 # checkbandwidth -i eth0 -I 50000=root@localhost localhost
287 # checkbandwidth -i eth0 -I 100000=ops@localhost localhost
288
289 If we want to add new configuration in the future, say for the output
290 interface at 50000 but with a minimum number of 3 "times seen", we can do so:
291
292 # checkbandwidth -i eth0 -O 50000:3=root@localhost localhost
293
294 Testing it on a regalur basis is as simple as running:
295
296 # checkbandwidth
297 localhost eth0 3907.2973 in 1638.1081 out (B/s)
298
299 =head2 Nagios usage example
300
301 * monitor eth0
302 * Alert at nagios 'warning' when the input bandwidth goes above 50000 B/s
303 * Alert at nagios 'critical' when the input bandwidth goes above 100000 B/s
304
305 # checkbandwidth -i eth0 -I 50000=nagioswarning -O 50000=nagioswarning localhost
306 # checkbandwidth -i eth0 -I 50000=nagioscritical -O 50000=nagioscritical localhost
307
308 (and you may or may not want to add -s to always include summary information)
309
310 =head1 BUGS / TODO
311
312 * There is no way to automatically remove a configured option. IE,
313 once an delivery address is designated, there is no way to remove it
314 without manually editing the json file.
315
316 =head1 AUTHOR
317
318 Wes Hardaker <[email protected]>
319 USC/ISI
320
321 =head1 COPYRIGHT and LICENSING
322
323 See the Net-SNMP COPYING file for licensing information for this script.
324
325 =cut
326
327 use JSON;
328 use Data::Dumper;
329 use Mail::Sender;
330 use SNMP;
331 use Fcntl ':flock';
332
333 use strict;
334
335 my %opts = (
336 c => "$ENV{HOME}/.snmp/checkbandwidth.json",
337 S => 'localhost',
338 F => 'root',
339 P => 25,
340 );
341 my %storage;
342 my ($NAGIOS_NORMAL, $NAGIOS_WARNING, $NAGIOS_CRITICAL) = (0,1,2);
343 my $nagiosexit = $NAGIOS_NORMAL;
344 my $nagiosstr = "";
345
346 LocalGetOptions(\%opts,
347 ["GUI:separator", "Configuration and setup:"],
348 ["i|add-interface=s", "Add this interface to the list of things to monitor"],
349 ["I|max-in-bandwidth=s", "Alert to ADDRESS on bandwidth > INT, COUNT times; STRING format: INT[:COUNT]=ADDRESS"],
350 ["O|max-out-bandwidth=s", "Alert to ADDRESS on bandwidth > INT, COUNT times; STRING format: INT[:COUNT]=ADDRESS"],
351 ["J|min-in-bandwidth=s", "Alert to ADDRESS on bandwidth < INT, COUNT times; STRING format: INT[:COUNT]=ADDRESS"],
352 ["Q|min-out-bandwidth=s", "Alert to ADDRESS on bandwidth < INT, COUNT times; STRING format: INT[:COUNT]=ADDRESS"],
353
354 ["GUI:separator", "Operation:"],
355 ["c|cache-file=s", "Location to store persistent data"],
356 ["r|reset", "Ignore all past data and start from scratch for all hosts/interfaces"],
357 ["l|loop=i", "Loop forever, displaying bandwidth every INTEGER seconds"],
358
359 ["GUI:separator", "Nagios mode:"],
360 ["N|nagios", "Operate in nagios mode, displaying errors/exit code for a given host"],
361 ["s|nagios-summary", "Always include summary information in the nagios output"],
362 ["L|lock-file=s", "Use a lockfile to ensure no simultaneous runs"],
363
364 ["GUI:separator", "Sending mail:"],
365 ["S|smtp-server=s", "SMTP server to use"],
366 ["P|port=i", "SMTP port to use"],
367 ["F|from=s", "From address to use"],
368
369 ["GUI:separator", "Debugging:"],
370 ["q|quiet", "Don't output data to the terminal (i.e., email only)"],
371 ["d|dump", "Dump the raw JSON data when finished"],
372 ["v|verbose", "Log (debugging) messages to stderr about what is being done"],
373 ["n|noop", "Don\'t store persistent data ; compare only to last time"],
374 ) || die "Illegal usage; see -h for help";
375
376 my @hosts = @ARGV; # remaining arguments should be hosts
377
378 my $cache = read_cache();
379
380 if ($#hosts == -1) {
381 @hosts = keys(%{$cache->{'hosts'}});
382 Verbose("loading hosts from cache: ", join(", ", @hosts));
383 }
384
385 my $lockfileh;
386
387 if ($opts{'d'}) {
388 print to_json($cache, { ascii => 1, pretty => 1}),"\n";
389 } elsif ($opts{'i'}) {
390 add_interface($cache, $opts{'i'}, $opts{'I'}, $opts{'O'}, $opts{'J'}, $opts{'Q'}, \@hosts);
391 } else {
392 # just process per norm
393 do {
394 if ($opts{'L'}) {
395 open($lockfileh, ">>$opts{L}");
396 my $have_lock = flock($lockfileh, LOCK_EX | LOCK_NB);
397 if (! $have_lock) {
398 print STDERR "failed to get lock on $opts{L}\n";
399 print "failed to get lock on $opts{L}\n";
400 exit($NAGIOS_NORMAL);
401 }
402 }
403 $cache = process_hosts($cache, \@hosts);
404 if (defined($opts{'l'})) {
405 Output("");
406 save_cache($cache);
407 sleep($opts{'l'});
408 }
409 } while ($opts{'l'});
410 }
411
412 save_cache($cache);
413 if ($lockfileh) {
414 unlink($lockfileh);
415 flock($lockfileh, LOCK_UN); # it's ok if it fails
416 }
417 nagios_exit() if ($opts{'N'});
418
419 sub read_cache {
420 # read in the json-based cache file
421 my $cache = {};
422 my ($buf, $content);
423
424 if (-f $opts{'c'}) {
425 Verbose("Reading cache file from '$opts{c}'");
426
427 open(my $cacheh, "<", $opts{'c'});
428 while (read($cacheh, $buf, 4096 * 16) > 0) {
429 $content .= $buf;
430 }
431 close($cacheh);
432
433 $cache = from_json($content); # cheap hack
434 }
435 return $cache;
436 }
437
438 sub process_hosts($$) {
439 my ($cache, $hosts) = @_;
440
441 # process hosts
442 foreach my $host (sort @$hosts) {
443 Verbose("Procesing host '$host'");
444
445 my $sess = get_snmp_session($host);
446
447 # we always want the uptime
448 my @vars;
449 push @vars, ['sysUpTime',0];
450
451 foreach my $interface (sort keys(%{$cache->{'hosts'}{$host}{'interfaces'}})) {
452 push @vars, ['ifHCInOctets', $cache->{'hosts'}{$host}{'interfaces'}{$interface}{'index'}];
453 push @vars, ['ifHCOutOctets', $cache->{'hosts'}{$host}{'interfaces'}{$interface}{'index'}];
454 }
455
456 my $list = new SNMP::VarList(@vars);
457 my $res = $sess->get($list);
458
459 my $sysUpTime = shift @$list;
460 my $sysUpTime = $sysUpTime->[2];
461
462 my $sysUpTimeDiff = $sysUpTime - $cache->{'hosts'}{$host}{'sysUpTime'};
463
464 foreach my $interface (sort keys(%{$cache->{'hosts'}{$host}{'interfaces'}})) {
465 my $ifHCInOctets = shift @$list;
466 my $ifHCOutOctets = shift @$list;
467
468 my $ifData = $cache->{'hosts'}{$host}{'interfaces'}{$interface};
469
470 if ($opts{'r'} ||
471 !exists($ifData->{'data'}{'ifHCInOctets'}) ||
472 !exists($cache->{'hosts'}{$host}{'sysUpTime'}) ||
473 $sysUpTimeDiff < 0) {
474 # reset all past data or...
475 # no data is collected yet -- just store the sysUpTime
476 # XXX: should collect engine boots too
477 $ifData->{'data'}{'ifHCInOctets'} = $ifHCInOctets->[2];
478 $ifData->{'data'}{'ifHCOutOctets'} = $ifHCOutOctets->[2];
479 Verbose("interface $interface on $host needs to start with new data");
480 } else {
481 # the great analysis
482
483 my $diffIn = $ifHCInOctets->[2] - $ifData->{'data'}{'ifHCInOctets'};
484 my $diffOut = $ifHCOutOctets->[2] - $ifData->{'data'}{'ifHCOutOctets'};
485
486 Verbose("$interface in: $ifHCInOctets->[2] - $ifData->{'data'}{'ifHCInOctets'}");
487 Verbose("$interface diff: $diffIn/$sysUpTimeDiff = " . (100 * $diffIn/$sysUpTimeDiff) . " B/s");
488
489 Verbose("$interface out: $ifHCOutOctets->[2] - $ifData->{'data'}{'ifHCOutOctets'}");
490 Verbose("$interface diff: $diffOut/$sysUpTimeDiff = " . (100 * $diffOut/$sysUpTimeDiff) . " B/s");
491
492 my $inRate = (100 * $diffIn/$sysUpTimeDiff);
493 my $outRate = (100 * $diffOut/$sysUpTimeDiff);
494
495 my $inMarker = " ";
496 my $outMarker = " ";
497
498 # check maximum bandwidth limits
499 if (defined($ifData->{'maxInBandwidth'})) {
500 foreach my $limit (@{$ifData->{'maxInBandwidth'}}) {
501 if ($inRate > 0 && $inRate > $limit->{'rate'}) {
502 $inMarker = "I";
503 $ifData->{'maxInBandwidthCount'} ++;
504
505 if ($ifData->{'maxInBandwidthCount'} == $limit->{'maxcount'} || $opts{'N'}) {
506 Verbose(" input too high!!! $inRate > $limit->{'rate'} ; emailing $limit->{'email'}");
507 send_rate_message($limit->{'email'},
508 $host, $interface, 'in', 'gt',
509 $ifData->{'maxInBandwidthCount'},
510 $inRate, $limit->{'rate'});
511 }
512 } else {
513 $ifData->{'maxInBandwidthCount'} = 0;
514 }
515 }
516 }
517
518 if (defined($ifData->{'maxOutBandwidth'})) {
519 foreach my $limit (@{$ifData->{'maxOutBandwidth'}}) {
520 if ($outRate > 0 && $outRate > $limit->{'rate'}) {
521 $outMarker = "O";
522 $ifData->{'maxOutBandwidthCount'} ++;
523
524 if ($ifData->{'maxOutBandwidthCount'} == $limit->{'maxcount'} || $opts{'N'}) {
525 Verbose(" output too high!!! $outRate > $limit->{'rate'} ; emailing $limit->{'email'}");
526
527 send_rate_message($limit->{'email'},
528 $host, $interface, 'out', 'gt',
529 $ifData->{'maxOutBandwidthCount'},
530 $outRate, $limit->{'rate'});
531 }
532 } else {
533 $ifData->{'maxOutBandwidthCount'} = 0;
534 }
535 }
536 }
537
538 # check minimum bandwidth limits
539 if (defined($ifData->{'minInBandwidth'})) {
540 foreach my $limit (@{$ifData->{'minInBandwidth'}}) {
541 if ($inRate > 0 && $inRate < $limit->{'rate'}) {
542 $inMarker = "I";
543 $ifData->{'minInBandwidthCount'} ++;
544
545 if ($ifData->{'minInBandwidthCount'} == $limit->{'maxcount'} || $opts{'N'}) {
546 Verbose(" input too low!!! $inRate < $limit->{'rate'} ; emailing $limit->{'email'}");
547 send_rate_message($limit->{'email'},
548 $host, $interface, 'in', 'lt',
549 $ifData->{'minInBandwidthCount'},
550 $inRate, $limit->{'rate'});
551 }
552 } else {
553 $ifData->{'minInBandwidthCount'} = 0;
554 }
555 }
556 }
557
558 if (defined($ifData->{'minOutBandwidth'})) {
559 foreach my $limit (@{$ifData->{'minOutBandwidth'}}) {
560 if ($outRate > 0 && $outRate < $limit->{'rate'}) {
561 $outMarker = "O";
562 $ifData->{'minOutBandwidthCount'} ++;
563
564 if ($ifData->{'minOutBandwidthCount'} == $limit->{'maxcount'} || $opts{'N'}) {
565 Verbose(" output too low!!! $outRate < $limit->{'rate'} ; emailing $limit->{'email'}");
566
567 send_rate_message($limit->{'email'},
568 $host, $interface, 'out', 'lt',
569 $ifData->{'minOutBandwidthCount'},
570 $outRate, $limit->{'rate'});
571 }
572 } else {
573 $ifData->{'minOutBandwidthCount'} = 0;
574 }
575 }
576 }
577
578 Output(sprintf("%-15s %-8s %16.0f in %16.0f out (B/s) %s%s",
579 $host, $interface,
580 $inRate, $outRate,
581 $inMarker, $outMarker));
582
583 # Update the cache data. Maybe.
584 if (! $opts{'n'}) {
585 $ifData->{'data'}{'ifHCInOctets'} = $ifHCInOctets->[2];
586 $ifData->{'data'}{'ifHCOutOctets'} = $ifHCOutOctets->[2];
587 }
588 }
589 }
590
591 # store the sysUpTime
592 $cache->{'hosts'}{$host}{'sysUpTime'} = $sysUpTime unless ($opts{'n'});
593 }
594
595 return $cache;
596 }
597
598 sub add_interface($$$$$) {
599 my ($cache, $interface, $maxInBandwidth, $maxOutBandwidth, $minInBandwidth, $minOutBandwidth, $hosts) = @_;
600 foreach my $host (@$hosts) {
601 Verbose("adding interface $interface to $host");
602
603 my $session = get_snmp_session($host);
604 my $tabledata = $session->gettable('ifTable');
605 my $found = 0;
606
607 foreach my $key (keys(%$tabledata)) {
608 # each key is an interface number; find the matching interface
609 if ($tabledata->{$key}{'ifDescr'} eq $interface) {
610 # found it!
611
612 Verbose("found $interface on $host at $key; adding it");
613
614 $cache->{'hosts'}{$host}{'interfaces'}{$interface}{'index'} = $key;
615 if ($maxInBandwidth) {
616 my ($ratespec, $email) = split(/=/, $maxInBandwidth);
617 my ($rate, $count) = split(/:/, $ratespec);
618 if (!defined($count)) {
619 $rate = $ratespec;
620 $count = 1;
621 }
622 push @{$cache->{'hosts'}{$host}{'interfaces'}{$interface}{'maxInBandwidth'}},
623 { rate => $rate,
624 email => $email,
625 maxcount => $count };
626 }
627 if ($maxOutBandwidth) {
628 my ($ratespec, $email) = split(/=/, $maxOutBandwidth);
629 my ($rate, $count) = split(/:/, $ratespec);
630 if (!defined($count)) {
631 $rate = $ratespec;
632 $count = 1;
633 }
634 push @{$cache->{'hosts'}{$host}{'interfaces'}{$interface}{'maxOutBandwidth'}},
635 { rate => $rate,
636 email => $email,
637 maxcount => $count};
638 }
639 if ($minInBandwidth) {
640 my ($ratespec, $email) = split(/=/, $minInBandwidth);
641 my ($rate, $count) = split(/:/, $ratespec);
642 if (!defined($count)) {
643 $rate = $ratespec;
644 $count = 1;
645 }
646 push @{$cache->{'hosts'}{$host}{'interfaces'}{$interface}{'minInBandwidth'}},
647 { rate => $rate,
648 email => $email,
649 maxcount => $count };
650 }
651 if ($minOutBandwidth) {
652 my ($ratespec, $email) = split(/=/, $minOutBandwidth);
653 my ($rate, $count) = split(/:/, $ratespec);
654 if (!defined($count)) {
655 $rate = $ratespec;
656 $count = 1;
657 }
658 push @{$cache->{'hosts'}{$host}{'interfaces'}{$interface}{'minOutBandwidth'}},
659 { rate => $rate,
660 email => $email,
661 maxcount => $count};
662 }
663 $found = 1;
664 Output("Configured $interface for $host");
665 }
666 }
667
668 if (!$found) {
669 Log(" failed to find interface '$interface' on '$host'");
670 }
671 }
672 }
673
674 my %session_cache;
675 sub get_snmp_session($) {
676 my ($host) = @_;
677 if (exists($session_cache{$host})) {
678 return $session_cache{$host};
679 }
680
681 my @args;
682
683 if (-f "/etc/snmp/perl/$host.conf") {
684 open(CC, "/etc/snmp/perl/$host.conf");
685 while (<CC>) {
686 next if (/^\s*#/);
687 chomp;
688 push @args, split();
689 }
690 }
691
692 # hack to work around perl not handling per-host files correctly
693 $session_cache{$host} = new SNMP::Session(DestHost => $host, @args);
694 return $session_cache{$host};
695 }
696
697 sub save_cache($) {
698 my ($cache) = @_;
699
700 # save data to the json cache (maybe)
701 if (!$opts{'n'}) {
702 my $dir = $opts{'c'};
703 $dir =~ s/(.*)\/.*/$1/;
704 if (! -d $dir) {
705 mkdir($dir);
706 if (! -d $dir) {
707 Log("failed to create directory $dir");
708 } else {
709 Verbose("note: created directory $dir");
710 }
711 }
712 # XXX: mkdir
713
714 Verbose("Writing cache file to '$opts{c}'");
715
716 my $jsondata = to_json($cache);
717 open(my $outh, ">", $opts{'c'} . $$);
718 print $outh $jsondata,"\n";
719 $outh->close();
720 rename($opts{'c'} . $$, $opts{'c'});
721 }
722 }
723
724 sub send_rate_message($$$$$$) {
725 my ($to, $host, $interface, $direction, $highlow, $count, $measured, $max) = @_;
726
727 if ($opts{'N'} && ($to eq 'nagioswarn' || $to eq 'nagioscritical')) {
728 # nagios mode ; collect simple output for later
729 nagios_collect($to, $host, $interface, $direction, $highlow, $count, $measured, $max);
730 } elsif($to ne 'nagioswarn' && $to ne 'nagioscritical') {
731 # send email
732 my $word = ($highlow eq '>' ? 'exceeded' : 'too low');
733 send_message($to,
734 "rate $word: $host/$interface=$direction ($count times)",
735 "Rate limit $word for:\n\n" .
736 "\thost:\t\t$host\n" .
737 "\tinterface:\t$interface ($direction)\n" .
738 "\trate:\t\t$measured\n" .
739 "\tmax allowed:\t$max\n" .
740 "\tcount:\t\t$count times in a row\n");
741 }
742 }
743
744 sub send_message($$$) {
745 my ($to, $subject, $text) = @_;
746
747 my $sender = new Mail::Sender { smtp => $opts{'S'} ,
748 port => $opts{'P'},
749 from => $opts{'F'},
750 };
751
752 my $status =
753 $sender->MailMsg({
754 to => $to,
755 subject => $subject,
756 msg => $text
757 });
758 if ($status < 0) {
759 Log("Failed to send mail with error code $status: $Mail::Sender::Error");
760 }
761 }
762
763 sub nagios_collect($$$$$$) {
764 my ($to, $host, $interface, $direction, $highlow, $count, $measured, $max) = @_;
765
766 if ($to eq 'nagioscritical') {
767 $nagiosexit = $NAGIOS_CRITICAL;
768 } elsif ($to eq 'nagioswarn' && $nagiosexit < $NAGIOS_CRITICAL) {
769 $nagiosexit = $NAGIOS_WARNING;
770 }
771
772 $nagiosstr .= sprintf(", %s $direction %16.0f B/s $highlow %s", $interface, $measured, $max);
773 }
774
775 sub nagios_exit() {
776 if ($nagiosstr eq '') {
777 $nagiosstr = "All interfaces ok: " . join(", ", keys(%{$cache->{'hosts'}{$hosts[0]}{'interfaces'}}));
778 } else {
779 $nagiosstr =~ s/^, //;
780 }
781
782 print $nagiosstr, "\n";
783 exit $nagiosexit;
784 }
785
786 sub Verbose {
787 if ($opts{'v'}) {
788 print STDERR @_, "\n";
789 }
790 }
791
792 sub Log {
793 print STDERR @_,"\n";
794 }
795
796 sub Output {
797 if (! $opts{'q'} && !$opts{'N'}) {
798 print @_, "\n";
799 }
800 if ($opts{'N'} && $opts{'s'}) {
801 $nagiosstr .= ", " . join(" ", @_);
802 }
803 }
804
805 #### portability for not requiring Getopt::GUI::Long directly
806 sub LocalGetOptions {
807 if (eval {require Getopt::GUI::Long;}) {
808 import Getopt::GUI::Long;
809 # optional configure call
810 Getopt::GUI::Long::Configure(qw(display_help no_ignore_case allow_zero));
811 return GetOptions(@_);
812 }
813 require Getopt::Long;
814 import Getopt::Long;
815 # optional configure call
816 Getopt::Long::Configure(qw(auto_help no_ignore_case));
817 GetOptions(LocalOptionsMap(@_));
818 }
819
820 sub LocalOptionsMap {
821 my ($st, $cb, @opts) = ((ref($_[0]) eq 'HASH')
822 ? (1, 1, $_[0]) : (0, 2));
823 for (my $i = $st; $i <= $#_; $i += $cb) {
824 if ($_[$i]) {
825 next if (ref($_[$i]) eq 'ARRAY' && $_[$i][0] =~ /^GUI:/);
826 push @opts, ((ref($_[$i]) eq 'ARRAY') ? $_[$i][0] : $_[$i]);
827 push @opts, $_[$i+1] if ($cb == 2);
828 }
829 }
830 return @opts;
831 }
832
833 # Local Variables:
834 # tab-width: 4
835 # End: