#!/usr/bin/perl -w
# Script that checks the oldest pg deep scrub


use strict;
use Getopt::Long;
use Monitoring::Plugin;
use JSON qw(decode_json);
use Date::Parse qw(str2time);
use Time::Duration qw(duration);
use POSIX qw(ceil);


my $plugin = Monitoring::Plugin->new( usage => '',);

$plugin->add_arg(
    spec => 'warning|w=s',
    help => '',
    label => 'days old',
    default => 8,
);

$plugin->add_arg(
    spec => 'critical|c=s',
    help => '',
    label => 'days old',
    default => 12,
);

$plugin->getopts;

# Maximum day for deep scrub

my $oldest_deep_scrub;
my $oldest_deep_scrub_time;

my %cmd = (
	ceph => '/usr/bin/ceph',
);

my $ceph_pg_dump = `$cmd{ceph} --id nagios pg dump -f json 2> /dev/null`;
if ( $? != 0 ) {
    $plugin->nagios_exit(CRITICAL, "error getting ceph pg dump: $!");
}
my $ceph_pg_data = decode_json($ceph_pg_dump);

my $pg_stats = ( $ceph_pg_data->{pg_map} ) ? $ceph_pg_data->{pg_map}->{pg_stats} : $ceph_pg_data->{pg_stats};

foreach my $pg ( sort {str2time($a->{last_deep_scrub_stamp}) <=> str2time($b->{last_deep_scrub_stamp})} @$pg_stats) {
    $oldest_deep_scrub = $pg->{last_deep_scrub_stamp};
    $oldest_deep_scrub_time = str2time($pg->{last_deep_scrub_stamp});
    last;
}

my $oldest_deep_scrub_human = duration(time - $oldest_deep_scrub_time);
my $oldest_deep_scrub_days = (time - $oldest_deep_scrub_time) / (3600 * 24);

my $code = $plugin->check_threshold(
     check => $oldest_deep_scrub_days,
     warning => $plugin->opts->warning,
     critical => $plugin->opts->critical,
);

$plugin->nagios_exit($code, "oldest is $oldest_deep_scrub_human old");
