# -*- perl -*-
#
# $Revision: 1.4 $
#/s/nagios/bin/nagioscmd service post <host> <service> \
# <result_code> <service_message>

package semaphores;

require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&print_usage &print_version &service_test);

use lib $main::runtimedir;
use csl_utils qw($TIMEOUT %ERRORS);
use strict;
use POSIX;

sub print_usage ();
sub print_version ();
sub service_test (%);

sub print_usage () {

    print <<__Eof__
Usage:  Check semaphore usage
Options:
    [--verbose]
    [--help]
    [--version]
    [--usage]
__Eof__
  ;
    return $ERRORS{WARNING};
}

sub print_version () {
  my $version = '$Revision: 1.4 $ ';
    $version =~ s/^\$Revision: //;
    $version =~ s/ \$\s*$//;

    print "csl_semaphores.pm - $version\n";
    return $ERRORS{WARNING};
}

sub service_test (%) {
  my %options = @_;

  my $WARNING_THRESHOLD = 70;
  my $CRITICAL_THRESHOLD = 75;

  `ipcs -ls` =~ /max number of arrays = (\d+)/;
  my $configured_max_semaphores = $1;

  my $current_used_semaphores = `cat /proc/sysvipc/sem | wc -l`; 
  chomp($current_used_semaphores);
  $current_used_semaphores--;

  my $used_semaphore_percentage = floor($current_used_semaphores / $configured_max_semaphores * 100);
  
  if ($used_semaphore_percentage >= $CRITICAL_THRESHOLD) {
    print "semaphore usage above $CRITICAL_THRESHOLD%, using $used_semaphore_percentage% ($current_used_semaphores of $configured_max_semaphores).\n";
    return $ERRORS{CRITICAL};
  } elsif ($used_semaphore_percentage >= $WARNING_THRESHOLD ) {
    print "semaphore usage above $WARNING_THRESHOLD%, using $used_semaphore_percentage% ($current_used_semaphores of $configured_max_semaphores).\n";
    return $ERRORS{WARNING};
  }

  print "semaphore usage OK, using $used_semaphore_percentage% ($current_used_semaphores of $configured_max_semaphores).\n";
  return $ERRORS{OK};
}

1;
