# Register routine with plugin registery
$DATAFUNCS{'rrd_la'} = \&data_rrd_la;

# Take the cpu status message and create rrd databases for load averages
# and number of users

# RRA to be created for each RRD
# "daily" 5min avg last 48hr
# "weekly" 30min avg last 12days
# "monthly 2hr avg last 48days
# "yearly" 24hr avg last 576days
$RRAS = "RRA:AVERAGE:0.5:1:576 RRA:AVERAGE:0.5:6:576 RRA:AVERAGE:0.5:24:576 " . 
        "RRA:AVERAGE:0.5:288:576";

$RRDTOOL = "/usr/local/rrdtool/bin/rrdtool";
$RRDDIR  = "/usr/local/spong/var/rrd";

sub data_rrd_la {
   my( $host, $service, $color, $start, $time, $sum, $message ) = @_;

   if ($service ne 'cpu' ) { return; }
   if ($color eq 'purple' ) { return; }
   $time = time;
   my( $line, $rawfs, $used, $pct, $name, %namemap, $target );

   &main::save_data('>', "$RRDDIR/$host/.rrd-la", "");

   if ( $sum =~ m/load\s+=\s+([^,]+),\s+([\d]+)\s+users,\s+(\d+)/ ) {
      $users = $2;
      $jobs = $3;
      $load = $1;
   } elsif ( $sum =~ m/(\d+)\s+users\,\s+(\d+)\s+procs\,\s+load=([^,]+)/ ) {
      $users = $1;
      $jobs = $2;
      $load = $3;
   } elsif ( $sum =~ m/up\s+(\d+)[^\,]+\,\s+(\d+)\s+procs\,\s+load = ([^,]+)%/ ) {
      $users = 1; # This one's for NT
      $jobs = $2;
      $load = $3;
   }
   $load =~ s/%//;
   
   if((defined $load) and (defined $jobs) and (defined $users)) {   
      # If .rrd file not found, built it
      if ( ! -f "$RRDDIR/$host/la.rrd" ) {
        &debug("$RRDDIR/$host/la.rrd not found creating it",4);
        {  local $SIG{'PIPE'} = 'IGNORE';
           local $SIG{'CHLD'} = 'IGNORE';

           eval {
              system "$RRDTOOL create $RRDDIR/$host/la.rrd " . 
                     "DS:loadavg:GAUGE:600:0:100 DS:users:GAUGE:600:0:U " .
                     "DS:jobs:GAUGE:600:0:U $RRAS";
           };
         }
         if (@?) { &error("Error: rrdtool create: $@"); }
      }

      # Update the .rrd file
      &debug("Updating $host Load Avg rrd file",4);
      {  local $SIG{'PIPE'} = 'IGNORE';
         local $SIG{'CHLD'} = 'IGNORE';
         system "$RRDTOOL update $RRDDIR/$host/la.rrd " .
                "$time:$load:$users:$jobs";
         if ($@) { &error("Error: rrdtool update: $@"); }
      }
   } else {
     &debug("Type cpu true but not parseable",4);
   }
}

# I'm include perl code, I need this line.
1;

