#!/usr/bin/perl -w
#
# Wildcard plugin to monitor sensor by using ipmitool sensor program.
#
# Contributed by Jun Futagawa
# This script is based on sensors_ plugin.
#
# Usage:
#       ln -s /usr/share/munin/plugins/ipmitool_sensor_ /etc/munin/plugins/ipmitool_sensor_fan
#       ln -s /usr/share/munin/plugins/ipmitool_sensor_ /etc/munin/plugins/ipmitool_sensor_temp
#       ln -s /usr/share/munin/plugins/ipmitool_sensor_ /etc/munin/plugins/ipmitool_sensor_volt
#
# Requirements:
#       - OpenIPMI tool (ipmitool command)
#
# Note:
#       - Sensor names are read from the output of the ipmitool sensor program.
#
# Add the following to your /etc/munin/plugin-conf.d/munin-node:
#       [ipmitool_sensor*]
#       user root
#       timeout 20
#
# Parameters supported:
#
#       config
#       autoconf
#       suggest
#
# Configurable variables
#
#       ipmitool            - ipmitool command (default: ipmitool)
#       ipmitool_options    - ipmitool command options (default: sensor)
#       cache_file          - cache file
#                             (default: /var/lib/munin/plugin-state/plugin-ipmitool_sensor.cache)
#       cache_expires       - cache expires (default: 275)
#
#       fan_warn_percent    - Percentage over mininum for warning (default: 5)
#       fan_lower_critical  - Preferred lower critical value for fan
#       fan_upper_critical  - Preferred upper critical value for fan
#       temp_lower_critical - Preferred lower critical value for temp
#       temp_lower_warning  - Preferred lower warining value for temp
#       temp_upper_warning  - Preferred upper warning value for temp
#       temp_upper_critical - Preferred upper critical value for temp
#       volt_warn_percent   - Percentage over mininum/under maximum for warning
#                             Narrow the voltage bracket by this. (default: 20)
#
# $Log$
# Revision 1.3  2008/11/11 13:55:00  jfut
# Added infinity value check for HP ProLiant DL160.
# Added preferred value option for fan and temp.
#
# Revision 1.2  2008/10/28 19:21:22  jfut
# Added file check.
#
# Revision 1.1  2008/10/27 18:52:31  jfut
# Added cache mechanism.
#
# Revision 1.0  2008/10/27 14:25:12  jfut
# Initial release.
#
# Magic markers:
#%# family=manual
#%# capabilities=autoconf suggest

use strict;

$ENV{'LANG'} = "C"; # Force parseable output from sensors.
$ENV{'LC_ALL'} = "C"; # Force parseable output from sensors.
my $IPMITOOL = $ENV{'ipmitool'} || 'ipmitool';
my @IPMITOOL_OPTS = exists $ENV{'ipmitool_options'} ? split(/\s+/, $ENV{'ipmitool_options'}) : ('sensor');

my $CACHE_DIR = "/var/lib/munin/plugin-state";
my $CACHE_FILE = $ENV{'cache_file'} || "$CACHE_DIR/plugin-ipmitool_sensor.cache";
my $CACHE_EXPIRES = $ENV{cache_expires} || 275;

my %config = (
               fan => {
                         regex => qr/^(.+?)\s+\|\s+(\d+(\.\d+)?)\s+\|\s+RPM\s+\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\s/m,
                         title => 'IPMITool Sensor: Fans',
                         vtitle => 'RPM',
                         print_threshold => \&fan_threshold,
                         graph_args => '--base 1000 -l 0'
                       },
               temp => {
                         regex => qr/^(.+?)\s+\|\s+(\d+(\.\d+)?)\s+\|\s+degrees C\s+\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\s/m,
                         title => 'IPMITool Sensor: Temperatures',
                         vtitle => 'Celsius',
                         print_threshold => \&temp_threshold,
                         graph_args => '--base 1000 -l 0'
                       },
               volt => {
                         regex => qr/^(.+?)\s+\|\s+(\d+(\.\d+)?)\s+\|\s+Volts\s+\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\|(.+)\s/m,
                         title => 'IPMITool Sensor: Voltages',
                         vtitle => 'Volt',
                         print_threshold => \&volt_threshold,
                         graph_args => '--base 1000'
                       },
             );

if (defined $ARGV[0] and $ARGV[0] eq 'autoconf') {
  close(STDERR);
  my $ret = system($IPMITOOL);
  open (STDERR, ">&STDOUT");
  if ($ret == 0 || $ret == 256) {
    print "yes\n";
    exit 0;
  } else {
    print "no (program $IPMITOOL not found)\n";
  }
  exit 1;
}

if (defined $ARGV[0] and $ARGV[0] eq 'suggest') {
  my $text = get_sensor_data();
  my $alltext = join('\n', @{$text});
  foreach my $func (keys %config) {
    print $func, "\n" if $alltext =~ $config{$func}->{regex};
  }
  exit;
}

$0 =~ /ipmitool_sensor_(.+)*$/;
my $func = $1;
exit 2 unless defined $func;

my $text = get_sensor_data();
my $sensor = 1;

if (defined $ARGV[0] and $ARGV[0] eq 'config') {
  print "graph_title $config{$func}->{title}\n";
  print "graph_vtitle $config{$func}->{vtitle}\n";
  print "graph_args $config{$func}->{graph_args}\n";
  print "graph_category sensors\n";
  foreach my $line (@{$text}) {
    if ($line =~ /$config{$func}->{regex}/g) {
      my ($label, $value, $lcr, $lnc, $unc, $ucr) = ($1, $2, trim($6), trim($7), trim($8), trim($9));

      # some boards show data in incorrect order.
      # - HP ProLiant ML110 G5
      # CPU FAN     | 1434.309 | RPM | ok | 5537.099 | 4960.317 | 4859.086 | na | 937.383 | na
      # SYSTEM FAN  | 1506.932 | RPM | ok | 5952.381 | 5668.934 | 5411.255 | na | 937.383 | na
      # - HP ProLiant DL160
      # FAN1 ROTOR1 | 7680.492 | RPM | ok | na | inf | na | na | 1000.400 | na 
      if (&is_valid_value($lcr) && &is_valid_value($ucr) && $lcr > $ucr || $lcr eq 'inf') {
        ($lcr, $lnc, $unc, $ucr) = ($ucr, $unc, $lnc, $lcr);
      }
      if (&is_valid_value($lnc) && &is_valid_value($unc) && $lnc > $unc || $lnc eq 'inf') {
        ($lcr, $lnc, $unc, $ucr) = ($ucr, $unc, $lnc, $lcr);
      }

      print "$func$sensor.label $label\n";
      $config{$func}->{print_threshold}->($func.$sensor, $lcr, $lnc, $unc, $ucr);
      print "$func$sensor.graph no\n" if exists $ENV{"ignore_$func$sensor"};
      $sensor++;
    }
  }
  exit 0;
}

foreach my $line (@{$text}) {
  if ($line =~ /$config{$func}->{regex}/g) {
    my ($label, $value, $lcr, $lnc, $unc, $ucr) = ($1, $2, trim($6), trim($7), trim($8), trim($9));
    # print "$func$sensor.value [$label] [$value] [$lcr] [$lnc] [$unc] [$ucr]\n";
    print "$func$sensor.value $value\n";
    $sensor++;
  }
}

sub get_sensor_data {
  my $text = undef;
  if (-f $CACHE_FILE) {
    my $cache_timestamp = (stat($CACHE_FILE))[9];
    if (time - $cache_timestamp <= $CACHE_EXPIRES) {
      open(IN, "<", $CACHE_FILE) or die "Could not open \"$CACHE_FILE\" for reading\n";
      while (<IN>) {
        push (@{$text}, $_);
      }
      close(IN);
    }
  }
  if (! defined $text) {
    my $pid = open(EXE, '-|');
    if ($pid == 0) {
      exec($IPMITOOL, @IPMITOOL_OPTS);
    } elsif (defined $pid) {
      while(<EXE>) {
        push (@{$text}, $_);
      }
      close(EXE);
    } else {
      die "fork faled: $!";
    }
    if (-w $CACHE_DIR) {
      open(OUT, ">", $CACHE_FILE) or die "Could not open \"$CACHE_FILE\" for writing\n";
      foreach my $line (@{$text}) {
        print OUT "$line";
      }
      close OUT;
    }
  }
  return $text;
}

sub fan_threshold {
  my ($name, $lcr, $lnc, $unc, $ucr) = @_;
  my $warn_percent = exists $ENV{fan_warn_percent} ? $ENV{fan_warn_percent} : 5;

  # lcr: lower critical
  if (exists $ENV{fan_lower_critical}) {
    $lcr = $ENV{fan_lower_critical};
  } elsif (! &is_valid_value($lcr)) {
    if ($lcr eq 'inf') { $lcr = ''; }
    else { $lcr = '50'; }
  }
  # lnc: lower warning
  if (! &is_valid_value($lnc)) {
    if ($lnc eq 'inf') { $lnc = ''; }
    else { $lnc = ($lcr eq '') ? '' : $lcr * (100 + $warn_percent) / 100; }
  }
  # ucr: upper critical
  if (exists $ENV{fan_upper_critical}) {
    $ucr = $ENV{fan_upper_critical};
  } elsif (! &is_valid_value($ucr)) {
    if ($ucr eq 'inf') { $ucr = ''; }
    else { $ucr = '6000'; }
  }
  # unc: upper warning
  if (! &is_valid_value($unc)) {
    if ($unc eq 'inf') { $unc = ''; }
    else { $unc = ($ucr eq '') ? '' : $ucr * (100 - $warn_percent) / 100; }
  }

  return unless ($lcr ne '' || $lnc ne '' || $unc ne '' || $ucr ne '');

  printf "$name.warning %d:%s\n", $lnc, $unc;
  printf "$name.critical %d:%s\n", $lcr, $ucr;
}

sub temp_threshold {
  my ($name, $lcr, $lnc, $unc, $ucr) = @_;

  # lcr: lower critical
  if (exists $ENV{temp_lower_critical}) {
    $lcr = $ENV{temp_lower_critical};
  } elsif (! &is_valid_value($lcr)) {
    if ($lcr eq 'inf') { $lcr = ''; }
    else { $lcr = 5; }
  }
  # lnc: lower warning
  if (exists $ENV{temp_lower_warningl}) {
    $lnc = $ENV{temp_lower_warning};
  } elsif (! &is_valid_value($lnc)) {
    if ($lnc eq 'inf') { $lnc = ''; }
    else { $lnc = 10; }
  }
  # unc: upper critical
  if (exists $ENV{fan_upper_critical}) {
    $unc = $ENV{fan_upper_critical};
  } elsif (! &is_valid_value($unc)) {
    if ($unc eq 'inf') { $unc = ''; }
    else { $unc = '65'; }
  }
  # ucr: upper warning
  if (exists $ENV{upper_critical}) {
    $ucr = $ENV{upper_critical};
  } elsif (! &is_valid_value($ucr)) {
    if ($ucr eq 'inf') { $ucr = ''; }
    else { $ucr = '70'; }
  }

  return unless ($lcr ne '' || $lnc ne '' || $unc ne '' || $ucr ne '');

  printf "$name.warning $lnc:$unc\n";
  printf "$name.critical $lcr:$ucr\n";
}

sub volt_threshold {
  my ($name, $lcr, $lnc, $unc, $ucr) = @_;
  my $warn_percent = exists $ENV{volt_warn_percent} ? $ENV{volt_warn_percent} : 20;

  if (! &is_valid_value($lcr)) { $lcr = ''; }
  if (! &is_valid_value($lnc)) { $lnc = ($lcr eq '') ? '' : $lcr * (100 + $warn_percent) / 100; }
  if (! &is_valid_value($ucr)) { $ucr = ''; }
  if (! &is_valid_value($unc)) { $unc = ($ucr eq '') ? '' : $ucr * (100 - $warn_percent) / 100; }

  return unless ($lcr ne '' || $lnc ne '' || $unc ne '' || $ucr ne '');

  printf "$name.warning $lnc:$unc\n";
  printf "$name.critical $lcr:$ucr\n";
}

sub trim {
  my $val = shift;
  $val =~ s/^\s*(.*?)\s*$/$1/;
  return $val;
}

sub is_valid_value() {
  my $value = shift;
  if ($value eq 'na' || $value eq 'inf' || $value eq '') {
    return 0;
  } else {
    return 1;
  }
}

# vim:syntax=perl
