#!/usr/bin/perl use strict; use FileHandle; use RRDs; use Glib; my $debug = 0; my $host = "loke"; my @eth = &gather_eth; my @outfile; my $loop = Glib::MainLoop->new; my $timer = Glib::Timeout -> add(10000, \&update_all); $loop -> run; sub update_all { my $i = 0; while($i < scalar(@eth)) { die "WTF??" if($eth[$i] eq ''); &debug("Found nic $eth[$i]\n"); &debug("Setting rrd-file to /var/www/apps/etherstats/$host/$eth[$i].rrd\n"); $outfile[$i] = "/var/www/apps/etherstats/$host/$eth[$i].rrd"; &update($outfile[$i],$eth[$i]); $i++; } return 1; } sub create { my $of = $_[0]; RRDs::create( "$of", "-s 10", 'DS:bytesIn:COUNTER:20:0:U', 'DS:bytesOut:COUNTER:20:0:U', 'RRA:AVERAGE:0.5:1:360', 'RRA:AVERAGE:0.5:6:1440', 'RRA:AVERAGE:0.5:30:2014', 'RRA:AVERAGE:0.5:360:672', 'RRA:AVERAGE:0.5:8640:365', ); &errorcheck; `chmod 640 "$of"`; `chown admin:www-data "$of"`; &debug("rrd-file $of created\n"); } sub update { my $of = $_[0]; my $if = $_[1]; if($if eq 'lo') { &debug("Ignoring loopback-device\n"); return 1; } unless( -e $of) { &create($of); } if( -e $of) { &debug("Updating stats for $if in $of..\n"); my ($in,$out) = split(',',&gather($if)); my $now = time; RRDs::update( "$of", "$now:$in:$out" ); &errorcheck; } return 1; } sub gather_eth { my @return; if(-e "/sys/class/net/") { &debug("/sys/class/net/ found\n"); open(ETH,"ls -1 /sys/class/net/|"); for (;;) { undef $!; my $line; unless(defined( $line = )) { print $! if $!; last; # EOF } else { chomp($line); &debug("Interface $line found\n"); push(@return,$line); } } close(ETH); return @return; } else { print "No /sys/class/net? Either no network cards, or no sysfs mounted..\n"; } } sub gather { my $if = $_[0]; if(defined($if)) { if(-e "/sys/class/net/$if/statistics/") { &debug(" statistics found in /sys/class/net/$if/statistics/\n"); my ($inbytes,$outbytes,$line); open(IN,"/sys/class/net/$if/statistics/rx_bytes"); for (;;) { undef $!; undef($line); unless(defined( $line = )) { print $! if $!; last; # EOF } else { $inbytes = $line; } } close(IN); open(OUT,"/sys/class/net/$if/statistics/tx_bytes"); for (;;) { undef $!; unless(defined( $line = )) { print $! if $!; last; # EOF } else { $outbytes = $line; } } close(OUT); chomp($inbytes); chomp($outbytes); &debug(" In : $inbytes\n Out : $outbytes\n"); return "$inbytes,$outbytes"; } } return 1; } sub errorcheck { my $ERR = RRDs::error; print "$ERR\n" if defined($ERR); } sub debug { if($debug == 1) { print $_[0]; } }