# $Id: check_amq.pl,v 1.1 2009/01/06 11:35:18 cmr Exp $
#

use strict;

use constant TIMEOUT => 3;

use Nagios::Plugin;
use Net::Stomp;

my $np = Nagios::Plugin->new(usage => "Usage: %s  --host|-H <host> [--port|-P <port>] [--queue|-q <message queue>] [--login|-l <login namei>] [--pass|-l <login password>] ");

$np->add_arg( spec => 'host|H=s', help => q(IP-Address of AMQ broker), required => 1 );
$np->add_arg( spec => 'port|P=i', help => q(Port of AMQ broker), default => 61613 );
$np->add_arg( spec => 'queue|q=s', help => q(AMQ Message Queue Name) , default => '/queue/nagiosTestQueue' );
$np->add_arg( spec => 'login|l=s', help => q(AMQ Login Name) );
$np->add_arg( spec => 'pass|p=s', help => q(AMQ Login password) );
$np->getopts;

my $stomp;
eval {
	local $SIG{'ALRM'} = sub { die "Connect timed out!"; };
	local $SIG{'__DIE__'} = sub { alarm(0); };  # Reset the alarm when dead
	alarm(TIMEOUT);

	$stomp = Net::Stomp->new( {hostname => $np->opts->host, port => $np->opts->port, timeout => TIMEOUT} );
};
if ($@) {
	$np -> add_message( 2, "Connect timed out! Host: " . $np->opts->host . ", Port: " . $np->opts->port);
	&finish;
}
alarm(0);
my $message=time;

if ( defined($np->opts->login) && defined ($np->opts->pass) ) {
	$stomp->connect( { login => $np->opts->login, passscode => $np->opts->pass });
} else {
	$stomp->connect();
}
$stomp->send( { destination => $np->opts->queue, body => "$message" });

$stomp->subscribe( { destination => $np->opts->queue, 'ack' => 'client', 'activemq.prefetchSize' => 1 });
my $can_read = $stomp->can_read({ timeout => TIMEOUT });
if ( $can_read ) {
	my $frame = $stomp->receive_frame;
	$stomp->ack( { frame => $frame } );
	my $framebody=$frame->body;
	if ( $framebody eq "$message" ) {
		$np -> add_message( 0, "Message received: $message");
	} else {
		$np -> add_message( 1, "Incorrect message body; is $framebody, should be $message\n");
	}
} else {
	$np -> add_message( 1, "Timed out while trying to collect the message\n");
}
$stomp->disconnect;
&finish;


sub finish {
	my ($code, $message) = $np->check_messages( join_all => 1);
	$np->nagios_exit($code, $message);
}
