#!/usr/bin/perl -w
#
# Nagios check for generating list of healthy nodes
# Copyright 2009 Emir Imamagic
#
# 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.

use strict;
use warnings;
use Nagios::Plugin;
use GridMon::Nagios;
use GridMon::Nagios qw(nagios_debug);
use No::Worries::Syslog qw(syslog_open);

$SIG{__WARN__} = \&No::Worries::Warn::handler;
$SIG{__DIE__}  = \&No::Worries::Die::handler;

syslog_open(ident => "refresh_proxy", facility => "user");
nagios_debug("started");

# Standard variables used in Nagios::Plugin constructor
use constant PROGNAME => "$0";
use constant VERSION => '1.0';
use constant DESCRIPTION => 'Nagios check for generating list of healthy nodes';
use constant EXTRA_DESC => "";
use constant LICENSE => 'This nagios plugin is free software, and comes with ABSOLUTELY NO WARRANTY.
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
Copyright 2009 Emir Imamagic';
use constant SHORTNAME => 'HealthyNodes';
use constant USAGE => "usage: $0 [ -v ] --file <file> --dir <directory> --metric <metric>\n";
use constant DEFAULT_METRIC => "org.sam.CE-JobSubmit";
use constant DEFAULT_DIR => "/var/lib/gridprobes";

# Create Nagios::Plugin instance
my $plugin = Nagios::Plugin->new (usage => USAGE,
                                  shortname => SHORTNAME,
                                  version => VERSION,
                                  blurb => DESCRIPTION,
                                  extra => EXTRA_DESC,
                                  license => LICENSE,
                                  plugin  => PROGNAME);
# Define additional arguments
$plugin->add_arg(
    spec => 'dir=s',
    help => "dir\n   Directory where to store list of hosts.
   If vo or vo-fqan is defined, they will be concatenated to path.
   (default: '".DEFAULT_DIR."')",
    required => 0,
    default => DEFAULT_DIR
);

$plugin->add_arg(
    spec => 'file|f=s',
    help => "f|file\n   Where to store list of hosts.\n   If dir is defined file is treated as relative path.",
    required => 1
);
$plugin->add_arg(
    spec => 'metric=s',
    help => "metric\n   Which metric state to check.\n   (default: '".DEFAULT_METRIC."')",
    required => 1,
    default => DEFAULT_METRIC
);
$plugin->add_arg(
    spec => 'vo=s',
    help => "vo\n   Virtual organization.\n",
    required => 0
);
$plugin->add_arg(
    spec => 'vo-fqan=s',
    help => "vo-fqan\n   Virtual organization FQAN.\n",
    required => 0
);

$plugin->getopts();

local $SIG{ALRM} = sub {
    $plugin->nagios_die("Timeout while fetching results.");
};

local $SIG{TERM} = sub {
    $plugin->nagios_die("Plugin received TERM signal.");
};

alarm ($plugin->opts->timeout);

my $vo;
$vo = $plugin->opts->vo;
$vo = $plugin->opts->get('vo-fqan') if ($plugin->opts->get('vo-fqan'));
my $voTidyDirectory;
if ($vo) {
    $voTidyDirectory = $vo;
    $voTidyDirectory =~ s/^\///;
    $voTidyDirectory =~ s/\//\./g;
}

my $file;
if ($plugin->opts->dir) {
    $file = $plugin->opts->dir;
    $file .= "/" . $voTidyDirectory if ($voTidyDirectory);
    $file .= "/" . $plugin->opts->file;
} else {
    $file = $plugin->opts->file;
}

my $nagios = GridMon::Nagios->new();
unless ($nagios) {
    alarm (0);
    $plugin->nagios_die("Error creating GridMon::Nagios object.");
}
my $statusHostAttrs = ["current_state","has_been_checked"];
my $statusServiceAttrs = ["current_state","has_been_checked"];
my $nagiosFilter;

$nagios->fetchStatusHostData($statusHostAttrs) || $plugin->nagios_die($nagios->{ERROR});
$nagios->fetchStatusServiceData($statusServiceAttrs) || $plugin->nagios_die($nagios->{ERROR});
$nagiosFilter = {};
$nagiosFilter->{current_state} = 0;
$nagiosFilter->{has_been_checked} = 1;
$nagios->filterHosts($nagiosFilter) || $plugin->nagios_die($nagios->{ERROR});

my $metric = $plugin->opts->metric;
$metric .= "-$vo" if ($vo);
$nagios->filterHostsByService( $plugin->opts->metric );

$nagiosFilter={};
$nagiosFilter->{service_description} = $plugin->opts->metric;
$nagiosFilter->{current_state} = 0;
$nagiosFilter->{has_been_checked} = 1;
$nagios->filterHostsByServiceAttrs($nagiosFilter);

unless(open(STD, ">".$file)) {
    $plugin->nagios_die("Creating local file ".$file." failed.");
}

my $count = 0;
foreach my $host (keys %{$nagios->{HOSTS}}) {
    print "Found host: $host\n" if ($plugin->opts->verbose);
    print STD "$host\n";
    $count++;
}
close STD;

$plugin->add_perfdata( label => "hosts", value => $count);

if ($count) {
    $plugin->nagios_exit(OK, "Successfully generated file with $count hosts.");
} else {
    $plugin->nagios_exit(CRITICAL, "No healthy hosts found.");
}

alarm (0);

=head1 NAME

gather_healthy_nodes - Nagios check for generating list of healthy nodes.

=head1 SYNOPSIS

B<gather_healthy_nodes> [-v] -f|--file I<filename> --metric I<metric>

=head1 DESCRIPTION

B<gather_healthy_nodes> is called as a Nagios check. It queries Nagios 
status file and fetches list of hosts in status UP which have metric
I<metric> in status OK.

=head1 SEE ALSO

GridMon::Nagios(3)
Nagios::Plugin(3)

=cut

