/
mrtg
executable file
·2844 lines (2565 loc) · 110 KB
/
mrtg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/perl -w
# -*- mode: cperl -*-
###################################################################
# MRTG 2.17.7 Multi Router Traffic Grapher
###################################################################
# Created by Tobias Oetiker <tobi@oetiker.ch>
# and Dave Rand <dlr@bungi.com>
#
# For individual Contributers check the CHANGES file
#
###################################################################
#
# Distributed under the GNU General Public License
#
###################################################################
my @STARTARGS=($0,@ARGV);
@main::DEBUG=qw();
# DEBUG TARGETS
# cfg - watch the config file reading
# dir - directory mangeling
# base - basic program flow
# tarp - target parser
# snpo - snmp polling
# snpo2 - more snmp debug
# coca - confcache operations
# repo - track confcache repopulation
# fork - forking view
# time - some timing info
# log - logging of data via rateup or rrdtool
# eval - trace eval experssions
# prof - add timeing info some interesting bits of code
$main::GRAPHFMT="png";
# There older perls tend to behave peculiar with
# large integers ...
require 5.005;
use strict;
# addon jpt
BEGIN {
# Automatic OS detection ... do NOT touch
if ( $^O =~ /^(ms)?(dos|win(32|nt)?)/i ) {
$main::OS = 'NT';
$main::SL = '\\';
$main::PS = ';';
} elsif ( $^O =~ /^NetWare$/i ) {
$main::OS = 'NW';
$main::SL = '/';
$main::PS = ';';
} elsif ( $^O =~ /^VMS$/i ) {
$main::OS = 'VMS';
$main::SL = '.';
$main::PS = ':';
} elsif ( $^O =~ /^os2$/i ) {
$main::OS = 'OS2';
$main::SL = '/';
$main::PS = ';';
} else {
$main::OS = 'UNIX';
$main::SL = '/';
$main::PS = ':';
}
if ( $ENV{LANG} and $ENV{LANG} =~ /UTF.*8/i ){
my $args = join " ", map { /\s/ ? "\"$_\"" : $_ } @ARGV;
$args ||= "";
print <<ERR;
-----------------------------------------------------------------------
ERROR: Mrtg will most likely not work properly when the environment
variable LANG is set to UTF-8. Please run mrtg in an environment
where this is not the case. Try the following command to start:
env LANG=C ${0} $args
-----------------------------------------------------------------------
ERR
exit 0;
}
}
use FindBin;
use lib "${FindBin::Bin}";
use lib "${FindBin::Bin}${main::SL}..${main::SL}lib${main::SL}mrtg2";
use Getopt::Long;
use Math::BigFloat;
# search for binaries in the bin and bin/../lib directory
use MRTG_lib "2.100016";
my $NOW = timestamp;
my $graphiteObj;
# $SNMP_Session::suppress_warnings = 2;
use locales_mrtg "0.07";
# Do not Flash Console Windows for the forked rateup process
BEGIN {
if ($^O eq 'MSWin32'){
eval {local $SIG{__DIE__};require Win32; Win32::SetChildShowWindow(0)};
warn "WARNING: $@\n" if $@;
}
}
$main::STARTTIME = time;
%main::verified_rrd = ();
if ($MRTG_lib::OS eq 'OS2') {
# in daemon mode we will pause 3 seconds to be sure that parent died
require OS2::Process;
if (OS2::Process::my_type() eq 'DETACH') {sleep(3);}
}
if ($MRTG_lib::OS eq 'UNIX') {
$SIG{INT} = $SIG{TERM} =
sub { unlink ${main::Cleanfile}
if defined $main::Cleanfile;
unlink ${main::Cleanfile2}
if defined $main::Cleanfile2;
unlink ${main::Cleanfile3}
if defined $main::Cleanfile3;
warn "$NOW: ERROR: Bailout after SIG $_[0]\n";
exit 1;
};
$SIG{HUP} = sub {
unlink ${main::Cleanfile}
if defined $main::Cleanfile;
unlink ${main::Cleanfile2}
if defined $main::Cleanfile2;
unlink ${main::Cleanfile3}
if defined $main::Cleanfile3;
die "$NOW: ERROR: Bailout after SIG $_[0]\n";
};
}
END {
local($?, $!);
unlink ${main::Cleanfile} if defined $main::Cleanfile;
unlink ${main::Cleanfile2} if defined $main::Cleanfile2;
}
&main;
exit(0);
#### Functions ################################################
sub main {
# read in the config file
my @routers;
my %cfg;
my %rcfg;
my %opts;
my $EXITCODE = 0;
GetOptions(\%opts, 'user=s', 'group=s', 'lock-file=s','confcache-file=s','logging=s', 'check', 'fhs', 'daemon', 'pid-file=s','debug=s', 'log-only') or die "Please use valid Options\n";
if (defined $opts{debug}){
@main::DEBUG = split /\s*,\s*/, $opts{debug};
if (defined $SNMP_util::Debug){
$SNMP_util::Debug = 1 if grep /^snpo2$/, @main::DEBUG;
}
}
if (grep /^prof$/, @main::DEBUG){
require Time::HiRes;
eval "sub gettimeofday() {return Time::HiRes::time()}";
# note this will crash if the module is missing
# so only use the --debug=prof if you have Time::HiRes installed
} else {
eval "sub gettimeofday() {return time()}";
}
debug 'time', "prog start ".localtime(time);
my $uid = $<;
my $gid = $(;
if (defined $opts{group}) {
$gid = getgrnam($opts{group});
die "$NOW: ERROR: Unknown Group: $opts{group})\n" if not defined $gid;
}
if (defined $opts{user}) {
$uid = getpwnam($opts{user});
die "$NOW: ERROR: Unknown User: $opts{user})\n" if not defined $uid;
}
# If we've specified using FHS (http://www.pathname.com/fhs/) on the command line,
# use the relevant path definitions (can be overridden later):
my $confcachefile;
my $pidfile;
my $lockfile;
my $templock;
my $logfile;
if (defined $opts{"fhs"}) {
$confcachefile = "/var/cache/mrtg/mrtg.ok";
$pidfile = "/var/run/mrtg.pid";
$lockfile = "/var/cache/mrtg/mrtg.lck";
$templock = "/var/cache/mrtg/mrtg.lck.$$";
$logfile = "/var/log/mrtg.log";
}
my $cfgfile = shift @ARGV;
if ( !defined $cfgfile and -r "/etc/mrtg.cfg" ) { $cfgfile = "/etc/mrtg.cfg"; }
printusage() unless defined $cfgfile;
# PID file code, used later if daemonizing...
if ( !defined($pidfile) ) {
$pidfile = $cfgfile;
$pidfile =~ s/\.[^.\/]+$//;
$pidfile .= '.pid';
}
$pidfile = $opts{"pid-file"} || $pidfile;
# Run as a daemon, specified on command line (required for FHS compliant daemon)
if (defined $opts{"daemon"}) {
# Create a pidfile, then chown it so we can use it once we change user
&create_pid($pidfile);
chown $uid, $gid, $pidfile;
}
($(,$)) = ($gid,$gid) ;
($<,$>) = ($uid,$uid) ;
die "$NOW: ERROR failed to set UID to $uid\n" unless ($< == $uid and $> == $uid);
$logfile = $opts{logging} || $logfile;
if (defined $logfile){
setup_loghandlers $logfile;
warn "Started mrtg with config \'$cfgfile\'\n";
}
# lets make sure that there are not two mrtgs running in parallel.
# so we lock on the cfg file. Nothing fancy, just a lockfile
$lockfile = $opts{"lock-file"} || $lockfile;
if (! defined $lockfile) {
$lockfile = $cfgfile."_l";
}
if (! defined $templock) {
$templock = $lockfile."_" . $$ ;
}
debug('base', "Creating Lockfiles $lockfile,$templock");
&lockit($lockfile,$templock);
debug('base', "Reading Config File: $cfgfile");
my $cfgfile_age = -M $cfgfile;
readcfg($cfgfile,\@routers,\%cfg,\%rcfg);
imggen($cfg{icondir} || $cfg{imagedir} || $cfg{workdir});
# Enable or disable snmpv3
if(defined $cfg{enablesnmpv3}) {
$cfg{enablesnmpv3} = lc($cfg{enablesnmpv3});
} else {
$cfg{enablesnmpv3} = 'no';
}
if ($cfg{threshmailserver}) {
if (eval {local $SIG{__DIE__};require Net::SMTP;}) {
import Net::SMTP;
debug('base', "Loaded Net::SMTP module for ThreshMail.");
} else {
die "$NOW: WARNING: Can't load Net::SMTP module. This is required for ThreshMail.";
}
}
# Check we have the necessary libraries for IPv6 support
if ($cfg{enablesnmpv3} eq 'yes') {
if (eval {local $SIG{__DIE__};require Net_SNMP_util;}) {
import Net_SNMP_util;
debug('base', "SNMP V3 libraries found, SNMP V3 enabled.");
} else {
warn "$NOW: WARNING: SNMP V3 libraries not found, SNMP V3 disabled.\n";
$cfg{enablesnmpv3} = 'no';
require SNMP_util;
import SNMP_util;
}
}
else { # load V1/V2 libraries
require SNMP_util;
import SNMP_util;
}
# Enable or disable IPv6
if(defined $cfg{enableipv6}) {
$cfg{enableipv6} = lc($cfg{enableipv6});
} else {
$cfg{enableipv6} = 'no';
}
# Check we have the necessary libraries for IPv6 support
if ($cfg{enableipv6} eq 'yes') {
if ( eval {local $SIG{__DIE__};require Socket; require Socket6; require IO::Socket::INET6;}) {
import Socket;
import Socket6;
debug('base', "IPv6 libraries found, IPv6 enabled.");
} else {
warn "$NOW: WARNING: IPv6 libraries not found, IPv6 disabled.\n";
$cfg{enableipv6} = 'no';
}
}
# Module invocation for sending a copy of the time series data to graphite.
if(defined $cfg{sendtographite}) {
require Net::Graphite;
}
# from our last run we kept some info about
# the configuration of our devices around
debug('base', "Reading Interface Config cache");
$confcachefile = $opts{"confcache-file"} || $confcachefile;
if ( !defined($confcachefile) ) {
$confcachefile = $cfgfile;
$confcachefile =~ s/\.[^.\/]+$//;
$confcachefile .= ".ok";
}
my $confcache = readconfcache($confcachefile);
# Check the config and create the target object
debug('base', "Checking Config File");
my @target;
cfgcheck(\@routers, \%cfg, \%rcfg, \@target, \%opts);
# exit here if we only check the config file
# in case of an error, cfgcheck() already exited
if (defined $opts{check}) {
debug('base', "Remove Lock Files");
close LOCK; unlink ($templock, $lockfile);
debug('base', "Exit after successful config file check");
exit 0;
}
# postload rrdtool support
if ($cfg{logformat} eq 'rrdtool'){
debug('base', "Loading RRD support");
require 'RRDs.pm';
}
# set the locale
my $LOC;
if ( $cfg{'language'} and defined($lang2tran::LOCALE{"\L$cfg{'language'}\E"})) {
debug('base', "Loading Locale for ".$cfg{'language'});
$LOC=$lang2tran::LOCALE{"\L$cfg{'language'}\E"};
} else {
debug('base', "Loading default Locale");
$LOC=$lang2tran::LOCALE{'default'};
}
# Daemon Code
my $last_time=0;
my $curent_time;
my $sleep_time;
if (defined $opts{"daemon"}) { $cfg{'runasdaemon'} = "yes"; }
&demonize_me($pidfile,$cfgfile) if defined $cfg{'runasdaemon'} and $cfg{'runasdaemon'} =~ /y/i and $MRTG_lib::OS ne 'VMS'
and not (defined $cfg{'nodetach'} and $cfg{'nodetach'} =~ /y/i);
# auto restart on die if running as demon
$SIG{__DIE__} = sub {
warn $_[0];
warn "*** Restarting after 10 seconds in an attempt to recover from the error above\n";
sleep 10;
exec @STARTARGS;
} if $cfg{'runasdaemon'};
debug('base', "Starting main Loop");
do { # Do this loop once for native mode and forever in daemon mode
my $router;
$NOW = timestamp; # get the time
debug 'time', "loop start ".localtime(time);
#if we run as daemon, we sleep in between collection cycles
$sleep_time= (int($cfg{interval}*60))-(time-$last_time);
if ($sleep_time > 0 ) { #If greater than 0 the sleep that amount of time
debug('time', "Sleep time $sleep_time seconds");
sleep ($sleep_time);
} elsif ($last_time > 0) {
warn "$NOW: WARNING: data collection did not complete within interval!\n";
}
$last_time=time;
# set meta expires if there is an index file
# 2000/05/03 Bill McGonigle <bill@zettabyte.net>
if (defined $cfg{'writeexpires'}) {
my $exp = &expistr($cfg{'interval'});
my $fil;
$fil = "$cfg{'htmldir'}index.html" if -e "$cfg{'htmldir'}index.html";
$fil = "$cfg{'htmldir'}index.htm" if -e "$cfg{'htmldir'}index.htm";
if (defined $fil) {
open(META, ">$fil.meta");
print META "Expires: $exp\n";
close(META);
}
}
# Use SNMP to populate the target object
debug('base', "Populate Target object by polling SNMP and".
" external Datasources");
debug 'time', "snmp read start ".localtime(time);
readtargets($confcache,\@target, \%cfg);
$NOW = timestamp; # get the time
# collect data for each router or pseudo target (`executable`)
debug 'time', "target loop start ".localtime(time);
foreach $router (@routers) {
debug('base', "Act on Router/Target $router");
if (defined $rcfg{'setenv'}{$router}) {
my $line = $rcfg{'setenv'}{$router};
while ( $line =~ s/([^=]+)=\"([^\"]*)\"\s*// ) # " - unconfuse the highliter
{
$ENV{$1}=$2;
}
}
my($savetz) = $ENV{'TZ'};
if (defined $rcfg{'timezone'}{$router}) {
$ENV{'TZ'} = $rcfg{'timezone'}{$router};
if ( $main::OS eq 'UNIX' ){
require 'POSIX.pm';
POSIX::tzset();
}
}
my ($inlast, $outlast, $uptime, $name, $time) =
getcurrent(\@target, $router, \%rcfg, \%cfg);
if ( defined($inlast) and defined($outlast)) {
$EXITCODE = $EXITCODE | 1;
}
else {
$EXITCODE = $EXITCODE | 2;
}
debug('base', "Get Current values: in:".( defined $inlast ? $inlast : "undef").", out:".
( defined $outlast? $outlast : "undef").", up:".
( defined $uptime ? $uptime : "undef").", name:".
( defined $name ? $name : "undef").", time:".
( defined $time ? $time : "undef"));
#abort, if the router is not responding.
if ($cfg{'logformat'} ne 'rrdtool') {
# undefined values are ok for rrdtool !
#if ( not defined $inlast or not defined $outlast){
# warn "$NOW: WARNING: Skipping Update of $router, inlast is not defined\n"
# unless defined $inlast;
# warn "$NOW: WARNING: Skipping Update of $router, outlast is not defined\n"
# unless defined $outlast;
# next;
#}
if (defined $inlast and $inlast < 0) {
$inlast += 2**31;
# this is likely to be a broken snmp counter ... lets compensate
}
if (defined $outlast and $outlast < 0) {
$outlast += 2**31;
# this is likely to be a broken snmp counter ... lets compensate
}
}
my ($maxin, $maxout, $maxpercent, $avin, $avout, $avpercent,$avmxin, $avmxout,
$cuin, $cuout, $cupercent);
debug('base', "Create Graphics");
if ($rcfg{'options'}{'dorelpercent'}{$router}) {
($maxin, $maxout, $maxpercent, $avin, $avout, $avpercent,
$cuin, $cuout, $cupercent, $avmxin, $avmxout) =
writegraphics($router, \%cfg, \%rcfg, $inlast, $outlast, $time,$LOC, \%opts);
} else {
($maxin, $maxout ,$avin, $avout, $cuin, $cuout, $avmxin, $avmxout) =
writegraphics($router, \%cfg, \%rcfg, $inlast, $outlast, $time,$LOC, \%opts);
}
# skip this update if we did not get anything usefull out of
# writegraphics
next if not defined $maxin;
debug('base', "Check for Thresholds");
threshcheck(\%cfg,\%rcfg,$cfgfile,$router,$cuin,$cuout);
if (defined $opts{'log-only'}){
debug('base', "Disable Graph and HTML generation");
}
if ($cfg{logformat} eq 'rateup' and not defined $opts{'log-only'} ){
debug('base', "Check for Write HTML Pages");
writehtml($router, \%cfg, \%rcfg,
$maxin, $maxout, $maxpercent, $avin, $avout, $avmxin, $avmxout, $avpercent,
$cuin, $cuout, $cupercent, $uptime, $name, $LOC)
}
#
clonedirectory($router,\%cfg, \%rcfg);
#
#put TZ things back in shape ...
if ($savetz) {
$ENV{'TZ'} = $savetz;
} else {
delete $ENV{'TZ'};
}
if ( $main::OS eq 'UNIX' ){
require 'POSIX.pm';
POSIX::tzset();
};
}
# Has the cfg file been modified since we started? if so, reload it.
if ( -M $cfgfile < $cfgfile_age and
$cfg{'runasdaemon'} and $cfg{'runasdaemon'} =~ /y/i ) {
# reload the configuration
$cfgfile_age = -M $cfgfile;
debug('base', "Re-reading Config File: $cfgfile");
@routers = (); %cfg = (); %rcfg = ();
readcfg($cfgfile,\@routers,\%cfg,\%rcfg);
cfgcheck(\@routers, \%cfg, \%rcfg, \@target, \%opts);
}
debug('base', "End of main Loop");
} while ($cfg{'runasdaemon'} and $cfg{'runasdaemon'} =~ /y/i ); #In daemon mode run forever
debug('base', "Exit main Loop");
# OK we are done, remove the lock files ...
debug('base', "Remove Lock Files");
close LOCK; unlink ($templock, $lockfile);
debug('base', "Store Interface Config Cache");
delete $$confcache{___updated} if exists $$confcache{___updated}; # make sure everything gets written out not only the updated entries
writeconfcache($confcache,$confcachefile);
if ( ! $cfg{'runasdaemon'} or $cfg{'runasdaemon'} !~ /y/i ) {
if ( ($EXITCODE & 1) and ($EXITCODE & 2) ) {
# At least one target was sucessful
exit 91;
}
elsif ( not ($EXITCODE & 1) and ($EXITCODE & 2) ) {
# All targets failed
exit 92;
}
}
}
# ( $inlast, $outlast, $uptime, $name, $time ) =
# &getcurrent( $target, $rou, $rcfg, $cfg )
# Calculate monitored data for device $rou based on information in @$target
# and referring to configuration data in %$rcfg and %$cfg. In the returned
# list, $inlast and $outlast are the input and output monitored data values,
# $uptime is the device uptime, $name is the device name, and $time is the
# current time when the calculation was performed.
sub getcurrent {
my( $target, $rou, $rcfg, $cfg ) = @_;
# Hash indexed by $mode for conveniently saving $inlast and $outlast
my %last;
# Initialize uptime, device name, and data collection time to empty strings
my $uptime = '';
my $name = '';
my $time = '';
# Calculate input and output monitored data
foreach my $mode( qw( _IN_ _OUT_ ) ) {
# Initialize monitored data, warning message, and death message
# to empty strings
my $data;
my $warning;
my $death;
{
# Code block used to calculate monitoring data
# Localize warning and death exception handlers to capture
# error message less any leading and trailing white space
local $SIG{ __WARN__ } =
sub { $_[0] =~ /^\s*(.+?)\s*$/; $warning = $1; };
local $SIG{ __DIE__ } =
sub { $_[0] =~ /^\s*(.+?)\s*$/; $death = $1; };
# Calculate monitoring data. $rcfg->{ target }{ $rou } contains
# a Perl expression for the calculation.
$data = eval "$rcfg->{target}{$rou}";
}
# Test for various exceptions occurring in the calculation
if( $warning ) {
warn "$NOW: ERROR: Target[$rou][$mode] '$$rcfg{target}{$rou}' (warn): $warning\n";
$data = undef;
} elsif( $death ) {
warn "$NOW: ERROR: Target[$rou][$mode] '$$rcfg{target}{$rou}' (kill): $death\n";
$data = undef;
} elsif( $@ ) {
warn "$NOW: ERROR: Target[$rou][$mode] '$$rcfg{target}{$rou}' (eval): $@\n";
$data = undef;
} elsif( not defined $data ) {
warn "$NOW: ERROR: Target[$rou][$mode] '$$rcfg{target}{$rou}' did not eval into defined data\n";
$data = undef;
} elsif( $data and $data !~ /^[-+]?\d+(\.\d*)?([eE][+-]?[0-9]+)?$/ ) {
warn "$NOW: ERROR: Target[$rou][$mode] '$$rcfg{target}{$rou}' evaluated to '$data' instead of a number\n";
$data = undef;
} elsif( length( $data ) > 190 ) {
warn "$NOW: ERROR: $mode value: '$data' is way to long ...\n";
$data = undef;
} else {
# At this point data is considered valid. Round to an integer
# unless RRDTool is in use and this is a gauge
if (not ( $cfg->{ logformat } eq 'rrdtool'
and defined $rcfg->{ options }{ gauge }{ $rou })){
if (ref $data and ref $data eq 'Math::BigFloat') {
$data->ffround( 0 )
} else {
$data = sprintf "%.0f", $data;
}
}
# Remove any leading plus sign
$data =~ s/^\+//;
}
$last{ $mode } = $data;
}
# Set $u to the unique index of the @$target array referred to in the
# monitored data calculation for the current device. $u will be set to
# -1 if that index is not unique.
my $u = $rcfg->{ uniqueTarget }{ $rou };
# Get the uptime, device name, and data collection time from the @$target
# array if the monitored data calculation refers only to one target.
# Otherwise it doesn't make sense to do this.
if( $u >= 0 ) {
$uptime = $target->[ $u ]{ _UPTIME_ };
$name = $target->[ $u ]{ _NAME_ };
$time = $target->[ $u ]{ _TIME_ };
if ($time =~ /^([-0-9.]+)$/) {
$time = $1;
}
}
# Set the time to the current time if it was not set above
$time = time unless $time;
# Cache uptime location for reading name
my( $uploc );
# Get the uptime and device name from the alternate location (community@host or
# (OID:community@host or OID) that may have been specified with the RouterUptime
# target keyword
if( defined $rcfg->{ routeruptime }{ $rou } ) {
my( $noid, $nloc ) = split( /:/, $rcfg->{ routeruptime }{ $rou }, 2 );
# If only location (community@host) was specified then
# move the location details into the right place
if( $noid =~ /@/ ) {
$nloc = $noid;
$noid = undef;
}
# If no OID (community@host) was specified use the hardcoded default
if( not $noid ) {
$noid = 'sysUptime';
}
# If no location (community@host) was specified use values from the
# unique target referred to in the monitored data calculation
if( not $nloc ){
if ($u >= 0) {
my $comm = $target->[ $u ]{ Community };
my $host = $target->[ $u ]{ Host };
my $opt = $target->[ $u ]{ SnmpOpt };
$nloc = "$comm\@$host$opt";
} else {
die "$NOW: ERROR: You must specify the location part of the RouterUptime oid for non unique targets! ($rou)\n";
}
}
$uploc = $nloc;
# Get the device uptime if $noid(OID) and $nloc (community@host) have been specified
# one way or the other
debug('base', "Fetching sysUptime and sysName from: $noid:$nloc");
( $uptime, $name ) = snmpget( $uploc, $rcfg->{ snmpoptions }{ $rou }, $noid, 'sysName');
}
# Get the device name from the alternate location (OID or
# OID:community@host) that may have been specified with the RouterName
# target keyword
if( defined $rcfg->{ routername }{ $rou } ) {
my( $noid, $nloc ) = split( /:/, $rcfg->{ routername }{ $rou }, 2 );
# If no location (community@host) was specified use values from the
# unique target referred to in the monitored data calculation
if( $u >= 0 and not $nloc ) {
my $comm = $target->[ $u ]{ Community };
my $host = $target->[ $u ]{ Host };
my $opt = $target->[ $u ]{ SnmpOpt };
$nloc = "$comm\@$host$opt";
}
# Get the location from the RouterUptime keyword if that is defined
# and $nloc has not otherwise been specified
$nloc = $uploc if $uploc and not $nloc;
# Get the device name if $nloc (community@host) has been specified
# one way or the other
debug('base', "Fetching sysName from: $noid:$nloc");
( $name ) = snmpget( $nloc, $$rcfg{snmpoptions}{ $rou }, $noid ) if $nloc;
}
return ( $last{ _IN_ }, $last{ _OUT_ }, $uptime, $name, $time );
}
sub rateupcheck ($) {
my $router = shift;
if ($?) {
my $value = $?;
my $signal = $? & 127; #ignore the most significant bit
#as it is always one when it is a returning
#child says dave ...
if (($MRTG_lib::OS ne 'UNIX') || ($signal != 127)) {
my $exitval = $? >> 8;
warn "$NOW: WARNING: rateup died from Signal $signal\n".
" with Exit Value $exitval when doing router '$router'\n".
" Signal was $signal, Returncode was $exitval\n"
}
}
}
sub clonedirectory {
my($router,$cfg, $rcfg) = @_;
require File::Copy;
import File::Copy;
return unless ( $$rcfg{'clonedirectory'}{$router} );
my ($clonedstdir, $clonedsttarget ,$srcname, $dstname);
($clonedstdir, $clonedsttarget ) = split (/,|\s+/, $$rcfg{'clonedirectory'}{$router}) if ( $$rcfg{'clonedirectory'}{$router} =~ /,|\S\s+\S/ );
if ( defined $clonedsttarget ) {
$clonedsttarget =~ s/\s+//;
$clonedsttarget = lc($clonedsttarget);
} else {
$clonedstdir = $$rcfg{'clonedirectory'}{$router};
}
if ( $$rcfg{'directory'}{$router} ne $clonedstdir) {
$clonedstdir =~ s/\s+$//;
$clonedstdir .= "/" unless ($clonedstdir =~ /\/$/);
my $fullpathsrcdir = "$$cfg{'logdir'}$$rcfg{'directory'}{$router}";
my $fullpathdstdir = "$$cfg{'logdir'}$clonedstdir";
die "$NOW: ERROR: Destination dir: $fullpathdstdir not found for cloning process\n" unless ( -e $fullpathdstdir );
die "$NOW: ERROR: Destination dir: $fullpathdstdir is not a directory destination for cloning process\n" unless ( -d $fullpathdstdir );
die "$NOW: ERROR: Destination dir: $fullpathdstdir is not writeable for cloning process\n" unless ( -w $fullpathdstdir );
if ( defined $clonedsttarget ) {
debug('base', "Clone directory $fullpathsrcdir to $fullpathdstdir " .
"renaming target $router to $clonedsttarget");
} else {
debug('base', "Clone directory $fullpathsrcdir to $fullpathdstdir");
}
foreach my $srcfile (<$fullpathsrcdir$router\[.-\]*>) {
debug('base', "copying $srcfile $fullpathdstdir");
copy("$srcfile","$fullpathdstdir") or warn "$NOW: WARNING: Cloning $srcfile to $fullpathdstdir unsuccessful; $!\n";
if ($srcfile =~ /\.html/i) {
debug('base', "altering $fullpathdstdir/$router.$$rcfg{'extension'}{$router}");
#
my $dirrel = "../" x ($$rcfg{'clonedirectory'}{$router} =~ tr|/|/|);
#
debug('base', "dirrel $dirrel $clonedstdir");
open(HTML,"$fullpathdstdir/$router.$$rcfg{'extension'}{$router}");
my @CLONEHTML = <HTML>;
close(HTML);
foreach ( @CLONEHTML ) {
if ( defined $clonedsttarget and /$router/ ) {
debug('base', "altering $router to $clonedsttarget in html file");
s/$router/$clonedsttarget/i;
}
if ( /SRC=/i and /$$rcfg{'directory'}{$router}/ ) {
debug('base', "altering from $_");
s|(\.\./)+|$dirrel|;
s|$$rcfg{'directory'}{$router}|$clonedstdir|;
debug('base', "altering to $_");
}
}
open(HTML,">$fullpathdstdir/$router.$$rcfg{'extension'}{$router}");
print HTML $_ for ( @CLONEHTML );
close(HTML);
}
if ( defined $clonedsttarget ) {
$srcfile =~ /.+\/(.+)?$/;
$srcname = $1;
$dstname = $srcname;
$dstname =~ s/$router/$clonedsttarget/;
debug('base', "Clone renaming $srcname to $dstname at $fullpathdstdir");
rename("$fullpathdstdir/$srcname","$fullpathdstdir/$dstname") or
warn "$NOW: WARNING: Renaming $fullpathdstdir/$srcname to $fullpathdstdir/$dstname unsuccessful; $!\n";
}
}
} else {
warn "$NOW: WARNING: Cloning to the same place suspended. ; $!\n";
}
}
sub writegraphics {
my($router, $cfg, $rcfg, $inlast, $outlast, $time,$LOC, $opts) = @_;
my($absmax,$maxv, $maxvi, $maxvo, $i, $period, $res);
my(@exec, @mxvls, @metas);
my(%maxin, %maxout, %maxpercent, %avin, %avout, %avmxin, %avmxout, %avpercent, %cuin, %cuout, %cupercent);
my($rrdinfo);
@metas = ();
$maxvi = $$rcfg{'maxbytes1'}{$router};
$maxvo = $$rcfg{'maxbytes2'}{$router};
if ($maxvi > $maxvo) {
$maxv = $maxvi;
} else {
$maxv = $maxvo;
}
$absmax = $$rcfg{'absmax'}{$router};
$absmax = $maxv unless defined $absmax;
if ($absmax < $maxv) {
die "$NOW: ERROR: AbsMax: $absmax is smaller than MaxBytes: $maxv\n";
}
# select whether the datasource gives relative or absolute return values.
my $up_abs="u";
$up_abs='m' if defined $$rcfg{'options'}{'perminute'}{$router};
$up_abs='h' if defined $$rcfg{'options'}{'perhour'}{$router};
$up_abs='d' if defined $$rcfg{'options'}{'derive'}{$router};
$up_abs='a' if defined $$rcfg{'options'}{'absolute'}{$router};
$up_abs='g' if defined $$rcfg{'options'}{'gauge'}{$router};
my $dotrrd = "$$cfg{'logdir'}$$rcfg{'directory'}{$router}$router.rrd";
my $dotlog = "$$cfg{'logdir'}$$rcfg{'directory'}{$router}$router.log";
my $reallog = $$cfg{logformat} eq 'rrdtool' ? $dotrrd : $dotlog;
if (defined $$cfg{maxage} and -e $reallog and time()-$$cfg{maxage} > (stat($reallog))[9]){
warn "$NOW: ERROR: skipping update of $router. As $reallog is older than MaxAge ($$cfg{maxage} s)\n";
return undef;
}
if ($$cfg{logformat} eq 'rrdtool') {
debug('base',"start RRDtool section");
# make sure we got some sane default here
my %dstype = qw/u COUNTER a ABSOLUTE g GAUGE h COUNTER m COUNTER d DERIVE/;
$up_abs = $dstype{$up_abs};
# update the database.
# set minimum/maximum values. use 'U' if we cannot get good values
# the lower bound is hardcoded to 0
my $absi = $maxvi;
my $abso = $maxvo;
$absi = $abso = $$rcfg{'absmax'}{$router}
if defined $$rcfg{'absmax'}{$router};
debug('base',"maxi:$absi, maxo:$abso");
$absi = 'U' if $absi == 0;
$abso = 'U' if $abso == 0;
# check to see if we already have an RRD file or have to create it
# maybe we can convert an .log file to the new rrd format
if( $RRDs::VERSION >= 1.4 and $$cfg{rrdcached} and $$cfg{rrdcached} !~ /^unix:/ ) {
# rrdcached in network mode. No log conversion possible.
# In this mode, we cannot use absolute paths. So, we strip logdir from the name.
$dotrrd = "$$rcfg{'directory'}{$router}$router.rrd";
if( $RRDs::VERSION < 1.49 ) {
# This version of RRD doesnt support info, create and tune
debug('base',"Unable to verify RRD file with this version of rrdcached");
if( !$main::verified_rrd{$dotrrd} ) {
warn "WARN: Unable to verify $dotrrd with this version of RRDTool\n";
$main::verified_rrd{$dotrrd} = 1;
}
} elsif( !$main::verified_rrd{$dotrrd} ) {
# Test to see if it exists
debug('base',"Attempting to verify RRD file via rrdcached");
$rrdinfo = RRDs::info($dotrrd,'--daemon',$$cfg{rrdcached},'--noflush');
if(!$rrdinfo) { # doesnt exist, or cannot be accessed
my $e = RRDs::error();
warn "$NOW: Cannot access $dotrrd; will attempt to (re)create it: $e\n" if $e;
# don't fail if interval is not set
my $interval = $$cfg{interval};
my $minhb = int($$cfg{interval} * 60)*2;
$minhb = 600 if ($minhb <600);
my $rows = $$rcfg{'rrdrowcount'}{$router} || int( 4000 / $interval);
my $rows30m = $$rcfg{'rrdrowcount30m'}{$router} || 800;
my $rows2h = $$rcfg{'rrdrowcount2h'}{$router} || 800;
my $rows1d = $$rcfg{'rrdrowcount1d'}{$router} || 800;
my @args = ($dotrrd, '-b', $time-10, '-s', int($interval * 60),
"DS:ds0:$up_abs:$minhb:0:$absi",
"DS:ds1:$up_abs:$minhb:0:$abso",
"RRA:AVERAGE:0.5:1:$rows",
( $interval < 30 ? ("RRA:AVERAGE:0.5:".int(30/$interval).":".$rows30m):()),
"RRA:AVERAGE:0.5:".int(120/$interval).":".$rows2h,
"RRA:AVERAGE:0.5:".int(1440/$interval).":".$rows1d,
"RRA:MAX:0.5:1:$rows",
( $interval < 30 ? ("RRA:MAX:0.5:".int(30/$interval).":".$rows30m):()),
"RRA:MAX:0.5:".int(120/$interval).":".$rows2h,
"RRA:MAX:0.5:".int(1440/$interval).":".$rows1d);
# do we have holt winters rras defined here ?
if (defined $$rcfg{'rrdhwrras'} and defined $$rcfg{'rrdhwrras'}{$router}){
push @args, split(/\s+/, $$rcfg{'rrdhwrras'}{$router});
}
push @args,"--daemon", $$cfg{rrdcached};
debug('base',"create $dotrrd via rrdcached");
debug('log', "RRDs::create(".join(',',@args).")");
RRDs::create(@args);
$e = RRDs::error();
die "$NOW: ERROR: Cannot create RRD ".join(',',@args)."- $e\n" if $e;
} else {
# Does the RRD file need to be tuned?
if(
($rrdinfo->{"ds[ds0].max"} != $absi)
||($rrdinfo->{"ds[ds1].max"} != $abso)
||($rrdinfo->{"ds[ds0].type"} ne $up_abs)
||($rrdinfo->{"ds[ds1].type"} ne $up_abs)
) {
debug('base',"RRD file needs to be tuned");
warn "$NOW: RRDFile $dotrrd needs to be tuned but cannot do this remotely.\n";
}
}
$main::verified_rrd{$dotrrd} = 1;
} else {
debug('base',"No need to verify this file again");
}
} elsif (-e $dotlog and not -e $dotrrd) {
debug('base',"converting $dotlog to RRD format");
if(defined $RRDs::VERSION and $RRDs::VERSION < 1.000271){
die "$NOW: ERROR: RRDtool version 1.0.27 or later required to perform log2rrd conversion\n";
}
log2rrd($router,$cfg,$rcfg);
} elsif (! -e $dotrrd) {
#nope it seems we have to create a new one
debug('base',"create $dotrrd");
# create the rrd if it doesn't exist
# don't fail if interval is not set
my $interval = $$cfg{interval};
my $minhb = int($$cfg{interval} * 60)*2;
$minhb = 600 if ($minhb <600);
my $rows = $$rcfg{'rrdrowcount'}{$router} || int( 4000 / $interval);
my $rows30m = $$rcfg{'rrdrowcount30m'}{$router} || 800;
my $rows2h = $$rcfg{'rrdrowcount2h'}{$router} || 800;
my $rows1d = $$rcfg{'rrdrowcount1d'}{$router} || 800;
my @args = ($dotrrd, '-b', $time-10, '-s', int($interval * 60),
"DS:ds0:$up_abs:$minhb:0:$absi",
"DS:ds1:$up_abs:$minhb:0:$abso",
"RRA:AVERAGE:0.5:1:$rows",
( $interval < 30 ? ("RRA:AVERAGE:0.5:".int(30/$interval).":".$rows30m):()),
"RRA:AVERAGE:0.5:".int(120/$interval).":".$rows2h,
"RRA:AVERAGE:0.5:".int(1440/$interval).":".$rows1d,
"RRA:MAX:0.5:1:$rows",
( $interval < 30 ? ("RRA:MAX:0.5:".int(30/$interval).":".$rows30m):()),
"RRA:MAX:0.5:".int(120/$interval).":".$rows2h,
"RRA:MAX:0.5:".int(1440/$interval).":".$rows1d);
# do we have holt winters rras defined here ?
if (defined $$rcfg{'rrdhwrras'} and defined $$rcfg{'rrdhwrras'}{$router}){
push @args, split(/\s+/, $$rcfg{'rrdhwrras'}{$router});
}
debug('log', "RRDs::create(".join(',',@args).")");
RRDs::create(@args);
my $e = RRDs::error();
die "$NOW: ERROR: Cannot create RRD ".join(',',@args)."- $e\n" if $e;
} elsif ( -M $dotrrd > 0 ) {
# update the minimum/maximum according to maxbytes/absmax
# and (re)set the data-source-type to reflect cfg changes
# cost: 1 read/write cycle, but update will reuse the buffered data
# in daemon mode this will only happen in the first round
my @args = ($dotrrd, '-a', "ds0:$absi", '-a', "ds1:$abso",
'-d', "ds0:$up_abs", '-d', "ds1:$up_abs");
debug('log', "RRDs::tune(@args)");
my $start = gettimeofday();
RRDs::tune(@args);
debug('prof',sprintf("RRDs::tune $dotrrd - %.3fs",gettimeofday()-$start));
my $e = RRDs::error();
warn "$NOW: ERROR: Cannot tune logfile: $e\n" if $e;
}
# update the rrd
$inlast = 'U' unless defined $inlast and $inlast =~ /\S/ and $inlast ne '##UNDEF##';
$outlast = 'U' unless defined $outlast and $outlast =~ /\S/ and $outlast ne '##UNDEF##';
debug('log', "RRDs::update($dotrrd, '$time:$inlast:$outlast')");
my $start = gettimeofday();
my $rrddata = 0;
if ( $RRDs::VERSION >= 1.4 and $$cfg{rrdcached} ){
RRDs::update($dotrrd, '--daemon', $$cfg{rrdcached}, "$time:$inlast:$outlast");
debug('prof',sprintf("RRDs::update $dotrrd (rrdcached) - %.3fs",gettimeofday()-$start));
$rrddata = \{ dummy => "" };
} elsif ( $RRDs::VERSION >= 1.2 ){
$rrddata=RRDs::updatev($dotrrd, "$time:$inlast:$outlast");
debug('prof',sprintf("RRDs::updatev $dotrrd - %.3fs",gettimeofday()-$start));
} else {
RRDs::update($dotrrd, "$time:$inlast:$outlast");
debug('prof',sprintf("RRDs::update $dotrrd - %.3fs",gettimeofday()-$start));
}
my $e = RRDs::error();
warn "$NOW: ERROR: Cannot update $dotrrd with '$time:$inlast:$outlast' $e\n" if ($e);
# Send a copy of the time series data to graphite
if(defined $$cfg{sendtographite}) {
my @a = split ",",$$cfg{sendtographite};
if (not $graphiteObj) {
$graphiteObj = Net::Graphite->new(
host => $a[0],
port => $a[1],
trace => 0,