#!/usr/bin/perl -s
############################## check_jmx_wowzamediaserver ########################
# Version : 0.1
# Date : Jul 08 2009
# Author  : Alejandro Ferrari (alejandro at linuxiso.com.ar)
# Help : http://www.linuxiso.com.ar/wiki/
# Licence : GPL - http://www.fsf.org/licenses/gpl.txt
# Contrib : 
# TODO : Add the option to authenticate in JMX access
##################################################################################
# Based on:
# Nagios plugin to monitor Java JMX (http://java.sun.com/jmx)attributes.
#
##################################################################################
# This Plugins Check some aspect of WowzaMediaServer (http://www.wowzamedia.com) #
# over JMX protocol with Performance Data Output to integrate with Cacti         #
##################################################################################

#use strict;
use Getopt::Long;
use Math::Round;
use Scalar::Util;
use Switch;

####### Parameters for User modify #######

## In this path need exist jmxquery.jar
my $pluginsDir="/usr/local/nagios/libexec";

##This are the Default port in WowzaMediaServer Settings
my $portjmx="8084";
my $portjndi="8085";

# Nagios specific
use lib "/usr/local/nagios/libexec/";

####### Finish User modify #######

use utils qw(%ERRORS $TIMEOUT);      
my $ERRORS =                         
{                                    
       'OK'      => 0,               
       'WARNING' => 1,               
       'CRITICAL'=> 2,               
       'UNKNOWN' => 3                
};          
#my $TIMEOUT = 15;

# Functions

sub usage
{        
       print qq{Usage : $0 -host=<hostname> -check=<checkObjectName> -w=<warning> -c=<critical>
  		-host       : Hostname or IP                                                                                                                
  		-check      : Check Object Name (see -advanceHelp to list all available Objects)                                                                                                                
  		-w          : Warning value                                                                                               
  		-c          : Critical value \n                                                                                         
		}                                                                                                                                         
}                                                                                                                                         

sub usage_advance
{        
       print qq{Usage : $0 -host=<hostname> -check=<checkObjectName> -w=<warning> -c=<critical>
  		-host       : Hostname or IP                                                                                                                
  		-check      : Check Object Name
			    	|__ HeapMemoryUsed (Show in % the Heap Memory Used)                                                                                                                
			    	|__ TotalCurrentServerConnections (Show the number of active connection in all vHosts)                                                                                                                
			    	|__ CurrentServerVersion (Compare the Server and Build Version currently in use)                                                                                                               
  		-w          : Warning value  (Memory usage percent value, CurrentServerVersion usage Build Version )                                                                                                 
  		-c          : Critical value (Memory usage percent value always bigger than Warning value, CurrentServerVersion usage Server Version)\n                                                                                         
		}                                                                                                                                         
}                                                                                                                                         

# check user's inputs
sub check_arguments  
{                    
       if (!$host || !$check || !$w || !$c)
       {  
	        print ("\nERROR :: Invalid argument(s) !\n\n");                 
	        &usage;                                            
	        exit $ERRORS->{'UNKNOWN'};                         
       }else{
		if($c <= $w && $check ne CurrentServerVersion){ 
			print "\nERROR :: The Critical value has to be bigger than Warning value\n\n"; 
			&usage_advance; 
			exit $ERRORS->{'UNKNOWN'};
		}
		
		switch ($check)
		{
		        case "HeapMemoryUsed"          			{ &check_HeapMemoryUsed; }
		        case "TotalCurrentServerConnections"    	{ &check_TotalCurrentServerConnections; }
		        case "CurrentServerVersion" 		   	{ &check_CurrentServerVersion; }
		        else   				                { print "\nInvalid Check parameter\n\n"; &usage_advance; }
		}

	}                                                   
}                                                          

# print help
if (defined($h))
{               
       &usage;  
       exit $ERRORS->{'OK'};
}                           
# print Advance Help
if (defined($advanceHelp))
{               
       &usage_advance;  
       exit $ERRORS->{'OK'};
}                           


sub check_numeric_memory
{
       if (!Scalar::Util::looks_like_number("$usedMem") || !Scalar::Util::looks_like_number("$maxMem"))
       {
		print ("JMX CRITICAL Connection refused \n");
		exit $ERRORS->{'CRITICAL'};
       }
}

sub check_HeapMemoryUsed
{

	$usedMem=`java -cp $pluginsDir/jmxquery.jar org.nagios.JMXQuery -U service:jmx:rmi://$host:$portjmx/jndi/rmi://$host:$portjndi/jmxrmi -O java.lang:type=Memory -A HeapMemoryUsage -K used -I HeapMemoryUsage -J used -v`;

	$maxMem =`java -cp $pluginsDir/jmxquery.jar org.nagios.JMXQuery -U service:jmx:rmi://$host:$portjmx/jndi/rmi://$host:$portjndi/jmxrmi -O java.lang:type=Memory -A HeapMemoryUsage -K used -I HeapMemoryUsage -J max -v`;

	@usedMem=split /\s+/, "$usedMem";
	$usedMem=$usedMem[2];

	@maxMem=split /\s+/, "$maxMem";
	$maxMem=$maxMem[2];
	
	&check_numeric_memory;

	$usedPorcent = round(100-(($maxMem-$usedMem)/($maxMem)*100),0);

	if($usedPorcent < $w){

		print "OK :: HeapMemoryUsage $usedPorcent% | mem_used=$usedMem mem_max=$maxMem";
		exit $ERRORS->{'OK'};

	}elsif($usedPorcent >= $c){

		print "CRITICAL :: HeapMemoryUsage $usedPorcent% | mem_used=$usedMem mem_max=$maxMem";
		exit $ERRORS->{'CRITICAL'};

	}elsif($usedPorcent >= $w){

		print "WARNING :: HeapMemoryUsage $usedPorcent% | mem_used=$usedMem mem_max=$maxMem";
		exit $ERRORS->{'WARNING'};

	}
}		

sub check_TotalCurrentServerConnections
{

	$TotalCurrentServerConnections=`java -cp $pluginsDir/jmxquery.jar org.nagios.JMXQuery -U service:jmx:rmi://$host:$portjmx/jndi/rmi://$host:$portjndi/jmxrmi -O WowzaMediaServerPro:name=Connections -A current -v`;

	@TotalCurrentServerConnections=split("=",$TotalCurrentServerConnections);
	$TotalCurrentServerConnections=$TotalCurrentServerConnections[1];
	chomp($TotalCurrentServerConnections);

#### TODO: Hacer la funcion de checkeo si el server esta arriba
	#&check_numeric_memory;


	if($TotalCurrentServerConnections lt $w){

		print "OK :: TotalCurrentServerConnections $TotalCurrentServerConnections | TotalCurrentServerConnections=$TotalCurrentServerConnections";
		exit $ERRORS->{'OK'};

	}elsif($TotalCurrentServerConnections ge $c){

		print "CRITICAL :: TotalCurrentServerConnections $TotalCurrentServerConnections >= $c | TotalCurrentServerConnections=$TotalCurrentServerConnections";
		exit $ERRORS->{'CRITICAL'};

	}elsif($TotalCurrentServerConnections ge $w){

		print "WARNING :: TotalCurrentServerConnections $TotalCurrentServerConnections >= $w  | TotalCurrentServerConnections=$TotalCurrentServerConnections";
		exit $ERRORS->{'WARNING'};

	}
}		

sub check_CurrentServerVersion
{
### Pending to finish, wait to Wowza provide the information #####################
#	use XML::Simple;
#	use Data::Dumper;
#	use LWP::Simple;
#
#	my $url = 'http://www.wowzamedia.com/wowzamedaserver-current.xml';
#	my $content = get $url;
#		die "Couldn't get $url" unless defined $content;
#
#	# create object
#	$data = new XML::Simple;
#
#	# read XML file
#	$xml = $data->XMLin("$content");
#
#
#	#print $xml->{'VHost'}->{'Name'};
#	#print Dumper($xml);
###################################################################################

	$ServerVersion=`java -cp $pluginsDir/jmxquery.jar org.nagios.JMXQuery -U service:jmx:rmi://$host:$portjmx/jndi/rmi://$host:$portjndi/jmxrmi -O WowzaMediaServerPro:name=Server -A version -v`;
	@ServerVersion=split /\s+/, "$ServerVersion";
        $ServerVersion=$ServerVersion[12];
        $BuildVersion=substr($ServerVersion[13],5,5);

	if($ServerVersion eq $c && $BuildVersion == $w ){

               print "OK :: Server=$ServerVersion Build=$BuildVersion | $ServerVersion $BuildVersion"; 
               exit $ERRORS->{'OK'};
  
        }elsif($ServerVersion ne $c ){

                print "CRITICAL :: Server Version $ServerVersion not equal than $c | $ServerVersion $BuildVersion";
                exit $ERRORS->{'CRITICAL'};

        }elsif($ServerVersion eq $c && $BuildVersion != $w ){

                print "WARNING :: Build Version $BuildVersion not equal than $w | $ServerVersion $BuildVersion";
                exit $ERRORS->{'WARNING'};

        }

}

### Start the execution of script
&check_arguments;
