#!/usr/bin/env perl

###  check_rabbitmq_aliveness.pl

# Use the management overview to check server statistics

##############################################################################
# prologue
use strict;
use warnings;

use Nagios::Plugin qw(%STATUS_TEXT OK CRITICAL WARNING UNKNOWN);
use LWP::UserAgent;
use URI::Escape;
use JSON;

use Data::Dumper;

use vars qw($VERSION $PROGNAME  $verbose $timeout $code $message);
$VERSION = '1.0';

# get the base name of this script for use in the examples
use File::Basename;
$PROGNAME = basename($0);


##############################################################################
# define and get the command line options.
#   see the command line option guidelines at
#   http://nagiosplug.sourceforge.net/developer-guidelines.html#PLUGOPTIONS


# Instantiate Nagios::Plugin object (the 'usage' parameter is mandatory)
my $p = Nagios::Plugin->new(
    usage => "Usage: %s [options] -H hostname",
    license => "",
    version => $VERSION,
    blurb => 'This plugin uses the RabbitMQ management node API to check server process parameters.',
);

$p->add_arg(spec => 'host|H=s',
    help => "Specify the host to connect to",
    required => 1
);
$p->add_arg(spec => 'port|p=i',
    help => "Specify the port to connect to (default: %s)",
    default => 55672
);

$p->add_arg(
    spec => 'warning|w=s',

    help =>
qq{-w, --warning=INTEGER,INTEGER,INTEGER
   Warning thresholds specified in order that the metrics are returned.
   (Default : %s)},
#   required => 1,
   default => "80,80,80",
);

$p->add_arg(
    spec => 'critical|c=s',
    help =>
qq{-c, --critical=INTEGER,INTEGER,INTEGER
   Warning thresholds specified in order that the metrics are returned.
   (Default: %s) },
   default => "90,90,90",
);

$p->add_arg(spec => 'user|u=s',
    help => "Username (default: %s)",
    default => "guest",
);
$p->add_arg(spec => 'password|p=s',
    help => "Password (default: %s)",
    default => "guest"
);

# Parse arguments and process standard ones (e.g. usage, help, version)
$p->getopts;


# Check we have three values for warning and critical thresholds
my @warning = split(',', $p->opts->warning);
$p->nagios_die("You should specify three ranges for --warning argument") unless $#warning == 2;

my @critical = split(',', $p->opts->critical);
$p->nagios_die("You should specify three ranges for --critical argument") unless $#critical == 2;

##############################################################################
# check stuff.

my $hostname = $p->opts->host;
$hostname =~ /^([a-zA-Z0-9-]*)/;
my $shortname=$1;
my $port = $p->opts->port;

my $path = "nodes/rabbit\@$shortname";
my $url = "http://$hostname:$port/api/$path";

my $ua = LWP::UserAgent->new(env_proxy=>1);
$ua->agent($PROGNAME.' ');
$ua->timeout($p->opts->timeout);
$ua->credentials("$hostname:$port",
    "Management: Web UI", $p->opts->user, $p->opts->password);
my $req = HTTP::Request->new(GET => $url);
my $res = $ua->request($req);

if (!$res->is_success) {
    # Deal with standard error conditions - make the messages more sensible
    if ($res->code == 400) {
        my $bodyref = decode_json $res->content;
        $p->nagios_exit(CRITICAL, $bodyref->{'reason'});
    }
    $res->code == 404 and $p->nagios_die("Not found: ".$path);
    $res->code == 401 and $p->nagios_die("Access refused: ".$path);
    if ($res->code < 200 or $res->code > 400 ) {
        $p->nagios_exit(CRITICAL, "Received ".$res->status_line." for path: ".$path);
    }
}

my $bodyref = decode_json $res->content;
check($p, "Memory", $bodyref->{'mem_used'}, $bodyref->{'mem_limit'}, $warning[0], $critical[0]);
check($p, "Process", $bodyref->{'proc_used'}, $bodyref->{'proc_total'}, $warning[1], $critical[1]);
check($p, "FD", $bodyref->{'fd_used'}, $bodyref->{'fd_total'}, $warning[2], $critical[2]);

($code, $message) = $p->check_messages(join_all=>', ');
$p->nagios_exit( return_code=>$code, message=>$message);


sub check {
    my $p = shift;
    my $label = shift;
    my $used = shift;
    my $limit = shift;
    my $warning = shift;
    my $critical = shift;

    my $value = percent($used, $limit);
    my $code = $p->check_threshold(check => $value, warning => $warning, critical => $critical);
    $p->add_message($code, sprintf("$label ".$STATUS_TEXT{$code}." (%.2f%%)", $value)) ;
    $p->add_perfdata(label=>$label, value => $value, uom=>"%", warning=>$warning, critical=>$critical);
}

sub percent {
    my $num = shift;
    my $denom = shift;
    return (10000 * $num/ $denom)%1000/100;
}

sub structured {
    my $content = shift;
    $Data::Dumper::Terse = 1;          # don't output names where feasible
    $Data::Dumper::Indent = 2;
    return Dumper($content);
}

=head1 NAME

check_rabbitmq_server - Nagios plugin using RabbitMQ management API to
check the server resource usage (processes, memory and file descriptors)

=head1 SYNOPSIS

check_rabbitmq_server [options] -H hostname

=head1 DESCRIPTION

Use the management interface of RabbitMQ to check the resource usage of the
server.  This check looks at the node statistics for the rabbit node on
the host and examines the erlang memory, process and file descriptor usage.

It provides performance data for each of these variables and allows for
warning and criticality levels to be specified for each.

It uses Nagios::Plugin and accepts all standard Nagios options.

=head1 OPTIONS

=over

=item -h | --help

Display help text

=item -v | --verbose

Verbose output

=item -t | --timeout

Set a timeout for the check in seconds

=item -H | --host

The host to connect to

=item --port

The port to connect to (default: 55672)

=item -w | --warning

The warning levels, expressed as a percentage for each of memory, process
and file descriptor usage.  This field consists of three comma-separated
integers.  (default: 90,90,90)

=item -c | --critical

The critical levels, expressed as a percentage for each of memory, process
and file descriptor usage.  This field consists of three comma-separated
integers.  (default: 90,90,90)

=item --user

The user to connect as (default: guest)

=item --pass

The password for the user (default: guest)

=back

=head1 EXAMPLES

The defaults all work with a standard fresh install of RabbitMQ, and all that
is needed is to specify the host to connect to:

    check_rabbitmq_server -H rabbit.example.com

This returns a standard Nagios result:

    RABBITMQ_SERVER OK - Memory OK (6.19%) Process OK (0.01%)
        FD OK (2.53%) | Memory=6.19%;80;90 Process=0.01%;80;90 FD=2.53%;80;90

You can specify different warning and criticality levels.  B<-w> and B<-c>
both accept three comma-separated percentages which represent the
thresholds for memory, process and file descriptor usage respectively.  For
example, to specify warnings for memory at 60%, process at 80% and file
descriptors at 95%:

    check_rabbitmq_server -H rabbit.example.com  -w 60,80,95

=head1 ERRORS

The check tries to provide useful error messages on the status line for
standard error conditions.

Otherwise it returns the HTTP Error message returned by the management
interface.

=head1 EXIT STATUS

Returns zero if check is OK otherwise returns standard Nagios exit codes to
signify WARNING, UNKNOWN or CRITICAL state.

=head1 SEE ALSO

See Nagios::Plugin(3)

The RabbitMQ management plugin is described at
http://www.rabbitmq.com/management.html

=head1 LICENSE

This file is part of nagios-plugins-rabbitmq.

Copyright 2010, Platform 14.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=head1 AUTHOR

James Casey <jamesc.000@gmail.com>

=cut

1;