#!/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';

# 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');

my ($pool, $warn, $crit) = @ARGV;
usage() unless (defined $pool);

$warn ||= 90; $warn = parse_bytes $warn;
$crit ||= 95; $crit = parse_bytes $crit;

# Get quota
my $json = `ceph osd pool get-quota $pool --format=json`;
$json = decode_json $json;
my $bytes_quota = $json->{quota_max_bytes}; 

# Get usage
$json = `rbd 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> [warn] [crit]\n\nExample:\n$0 STOAW-153522-CLOUD 90 95\n";
    exit 0;
}


# 08:34 <stefan> jouw "cephfs" usage check, zouden we die ook kunnen uitbreiden met de check om pool quota in de gaten te houden?
# 08:34 <stefan> ceph df detail --format=json(-pretty)
# 08:34 <stefan> quota_objects (stellen we vooralsnog niet in)
# 08:34 <stefan> en quota_bytes
# 08:34 <stefan> die laatste wel, op pool niveau
#
# 08:46 <stefan> read only access ... ff testen
# 08:47 <stefan> root@monitoring2:~# ceph df detail --id BITED-152622-all --format=json
