#!/usr/bin/perl
# -----------------------------------------------------------------------------
#  check_cloudstorage_status : Nagios plugin for Stratus cloud storage health check
# -----------------------------------------------------------------------------
#  Created by: Andriy Fomenko
#  Authors: Alex Titov, Alex Tsibulnik, Andriy Fomenko
#  QA by:
#  Copyright: videoNEXT Federal, Inc., 2015
# -----------------------------------------------------------------------------

use strict;
use warnings;

use Nagios::Plugin;
use Nagios::Plugin::Getopt;

my $np = Nagios::Plugin->new( usage => "Usage: %s [ -v|--verbose ]" );
$np->getopts;

my $APL=$ENV{APL} || $np->nagios_exit( UNKNOWN, 'APL environment variable is not defined' );

use Master::Conf;
use Node::Conf ":all";

$np->nagios_exit( OK, 'skipped on slave node' ) if ! am_I_master();

# Try connecting to db
use SKM::DB;
my $dbh;
eval {
    $dbh = DBMaster({ PrintError=>0, RaiseError=>1, FetchHashKeyName=>'NAME_uc' });
};
$np->nagios_exit( CRITICAL, 'Database is DOWN' ) if $@;
my ($verbose_notes, $alert_notes, $critical_notes);

cloud_status();

$np->nagios_exit( CRITICAL, "Cloud storage is in CRITICAL state\nCritical notes:\n${critical_notes}Warnings:$alert_notes" ) if $critical_notes;
$np->nagios_exit( WARNING, "Cloud storage warnings detected:\n$alert_notes" ) if $alert_notes;
$np->nagios_exit( OK, 'Cloud storage is running normally' );

# -----------------------------------------------------------------------------

sub cloud_status {
    my %cloudconf;
    eval {
        my $c = $dbh->selectall_arrayref( qq {
            select attr,val 
              from _obj_attr 
             where obj=53 and attr in('CLOUD_STORAGE','CLOUD_STORAGE_ENABLED','CLOUD_KEY_ID', 'CLOUD_SECRET_KEY')
        });
        foreach my $av (@$c) {
            $cloudconf{$av->[0]} = $av->[1];
        }
    };
    $np->nagios_exit( CRITICAL, 'Can not read cloud storage status from DB' ) if $@;
    
    if ($cloudconf{CLOUD_STORAGE} ne 'none' && $cloudconf{CLOUD_STORAGE_ENABLED} eq 'yes') {
        eval {
            no strict 'subs';
            push @INC, "$APL/sm/lib";
            require SM::Cloud;
            SM::Cloud->import($cloudconf{CLOUD_STORAGE});
            Cloud_Init($cloudconf{CLOUD_KEY_ID}, $cloudconf{CLOUD_SECRET_KEY});
            my @buckets = Cloud_ListBuckets();
            die "Empty bucket list" if not @buckets;
        };
        $critical_notes.="Cloud connection failure: $@\n" if $@;
    } 
}
