#!/usr/bin/perl
# apt-get install libnumber-bytes-human-perl libjson-perl

use strict;
use warnings;
use Number::Bytes::Human qw'format_bytes parse_bytes'; 
use JSON qw'decode_json';
use Getopt::Long;

my $pool;
my $verbose;
my $warn;
my $crit;
my $ceph_conf;
my $ceph_keyring;
my $rbd_opts;

# Scheelt een ton aan dependencies op nagios-plugins
#use lib "/usr/lib/nagios/plugins";
#use utils qw(%ERRORS);
my %ERRORS = (
    OK       => 0,
    WARNING  => 1,
    CRITICAL => 2,
    UNKNOWN  => 3,
);

usage() if (@ARGV and $ARGV[0] eq '--help');

GetOptions (
    "pool=s"        => \$pool,
    "verbose"       => \$verbose,
    "warning=s"     => \$warn,
    "critical=s"    => \$crit,
    "conf=s"        => \$ceph_conf,
    "keyring=s"     => \$ceph_keyring,
);

usage() unless (defined $pool);

$warn ||= 90; $warn = parse_bytes $warn;
$crit ||= 95; $crit = parse_bytes $crit;
$ceph_conf ||= "/etc/ceph/ceph.conf";
$ceph_keyring ||= "/etc/ceph/ceph.client.admin.keyring";

# Get quota
if($verbose) { print "running: ceph -c $ceph_conf --keyring=$ceph_keyring osd pool get-quota $pool --format=json\n"; }
my $json = `ceph -c $ceph_conf --keyring=$ceph_keyring osd pool get-quota $pool --format=json`;
$json = decode_json $json;
my $bytes_quota = $json->{quota_max_bytes}; 

# Get usage
if($verbose) { print "running rbd -c $ceph_conf -k $ceph_keyring du -p $pool --format json\n"; }
$json = `rbd -c $ceph_conf -k $ceph_keyring du -p $pool --format json`;
$json = decode_json $json;
my $bytes_used = $json->{total_used_size};

## TODO: object quota
#my $objects_used = $stats->{objects};
#my $objects_quota = $stats->{quota_objects};

if ($bytes_quota == 0) {
    print "OK: no quota set\n";
    exit $ERRORS{"OK"};
}

unless (defined $bytes_used and $bytes_quota) {
    print "UNKNOWN: No data\n";
    exit $ERRORS{"UNKNOWN"};
}

my $bytes_free       = $bytes_quota - $bytes_used;
my $bytes_free_human = format_bytes $bytes_free;

my $bytes_used_perc       = $bytes_used * 100 / $bytes_quota;
my $bytes_used_perc_human = int($bytes_used_perc);

my $message = "$pool ${bytes_used_perc_human}% - $bytes_free_human free\n";

# Warn > 100 dan absoluut free space, warn < 100 dan percentage used
errExit("CRITICAL", $message) if (($warn > 100) and ($crit > 100) and ($bytes_free < $crit));
errExit("WARNING", $message)  if (($warn > 100) and ($crit > 100) and ($bytes_free < $warn));

errExit("CRITICAL", $message) if (($crit < 100) and ($bytes_used_perc >= $crit));
errExit("WARNING", $message)  if (($warn < 100) and ($bytes_used_perc >= $warn));

errExit("OK", $message);

sub errExit {
    my ($state, $msg) = @_;
    print "$state: $msg";
    exit $ERRORS{$state};
}
sub usage {
    print "USAGE:\n$0 --pool <pool> --warning [warn] --critical [crit] --conf [/etc/ceph/ceph.conf] --keyring [/etc/ceph/ceph.client.admin.keyring]\n\nExample:\n$0 STOAW-153522-CLOUD 90 95\n";
    exit 0;
}
