#!/opt/circonus/perl/bin/perl

use warnings;
use strict;
use Cwd qw(abs_path getcwd);
use File::Basename;
use File::Copy;
use File::Path qw(make_path remove_tree);
use File::Temp;
use Getopt::Long;
use HTTP::Tiny;
use JSON;
use List::Util qw(first max);
use Pod::Usage;
use POSIX qw(floor);

my $current_dir = getcwd;
my @shards;
my $url_prefix = "http://";
my ($help, $mapfile, $progress, $shard_dir, $port, $lmdb_tool_path, $use_tls);
GetOptions (
    'd:s'              => \$shard_dir,
    'shard|s:s{1,}'    => \@shards,
    'map|m:s'          => \$mapfile,
    'progress|p'       => \$progress,
    'port:s'           => \$port,
    'lmdb_tool_path:s' => \$lmdb_tool_path,
    'tls|t'            => \$use_tls,
    'help|h'           => \$help);

pod2usage(-exitval => 0,
          -verbose => 99,
          -sections => "NAME|SYNOPSIS|OPTIONS|EXAMPLES|CAVEATS") if $help;

if ($> == 0) {
    logmsg("Error: running as superuser not supported.");
    exit 1;
}

if (! defined $port) {
    $port = 8112;
}

if (! defined $lmdb_tool_path) {
    $lmdb_tool_path = "/opt/circonus/bin"
}

if (defined $use_tls) {
    $url_prefix = "https://";
}

if (! defined $shard_dir) {
    logmsg("Error: shard directory (-d) is required.");
    pod2usage(-exitval => 1, -verbose => 0);
} elsif (! -d $shard_dir) {
    logmsg("Error: shard directory $shard_dir does not exist.");
    exit 1;
}

if (scalar @shards < 1) {
    logmsg("Error: no shard(s) specified.");
    pod2usage(-exitval => 1, -verbose => 0);
}

my $remove_smap = defined $mapfile ? 0 : 1;

$shard_dir =~ s/\/$//;
my $shard_errors = 0;

foreach my $shard (@shards) {
    my $shardp = join('/', $shard_dir, $shard);

    if (! -f "$shardp/data.mdb") {
        logmsg("Error: $shardp does not appear to be an NNTBS timeshard.");
        $shard_errors++;
    }

    if ($current_dir eq $shardp) {
        logmsg("Error: cannot perform compaction when CWD is $shardp. Please change directories before running the tool again.");
        $shard_errors++;
    }
}
pod2usage(-exitval => 1, -verbose => 0) if $shard_errors > 0;

# Get a bitmap of existing surrogate IDs, if not specified.
# NNTBS keys are the numeric surrogate IDs. Any key in the shard
# that does not appear in the bitmap is skipped during the copy.
if (! defined $mapfile) {
    my $map_fh = File::Temp->new(
        DIR => '/var/tmp',
        TEMPLATE => 'shard_compactor_XXXX',
        SUFFIX => '.smap',
        UNLINK => 0);
    $mapfile = $map_fh->filename;

    logmsg("Fetching temporary copy of surrogate database map: $mapfile");
    my $api_url = "$url_prefix" . "127.0.0.1:$port/surrogate/all.smap";
    my @curlit = qw(/usr/bin/curl -k -s -o);
    push(@curlit, $mapfile, $api_url);
    system(@curlit) == 0 or do {
        logmsg("Failed to fetch surrogate map to $mapfile");
        clean_up();
        exit 1;
    }
}

$mapfile = abs_path($mapfile);
logmsg("Using surrogate map file $mapfile\n===");

# So that remove_tree will not try to change into a directory
# that the unprivileged user can't access
chdir $shard_dir;

my $min_output_map = 10000 * 4096; # minimum amount of output mapsize

foreach my $shard (sort(@shards)) {
    my $work_dir = $shard_dir . '/.compacting_' . $shard;
    my $full_shard_path = join('/', $shard_dir, $shard);

    logmsg("Starting compaction on shard $shard");

    if (-d $work_dir) {
        logmsg("Existing working directory found, removing");
        remove_tree($work_dir);
    } else {
        logmsg("Using $work_dir for working copy");
        make_path($work_dir);
    }

    my @shard_spec = split(/[-_]/, $shard);
    my $period  = int($shard_spec[0]);
    my $floor   = int($shard_spec[1]);
    my $ceiling = int($shard_spec[2]);

    my $shard_maint = {
        'period'        => $period,
        'block_floor'   => $floor,
        'block_ceiling' => $ceiling
    };

    logmsg("Taking shard $shard offline");
    maintain_shard($shard_maint, 'offline') or do {
        logmsg("Unable to set $shard offline");
        clean_up();
        exit 1;
    };

    # Set output map size to the larger of:
    # 110% of on-disk logical input file size,
    # or 10K pages (40 MB)
    my $input_size = -s "$full_shard_path/data.mdb";
    my $new_map_size = floor($input_size * 1.1);
    my $output_size = max( $min_output_map, $new_map_size );

    my $progress_opt = defined $progress ? '-p' : '';
    my $mdb_file = join('/', $shard_dir, $shard, 'data.mdb');

    my @compact_shard = ("$lmdb_tool_path/snowth_lmdb_tool", $progress_opt,
                         "-f", $mdb_file, "-s", "nntbs_smap", "--",
                         "-m", "$mapfile", "-s", "$output_size", "-o", "$work_dir");

    logmsg("Compacting shard $shard");
    system(@compact_shard) == 0 or do {
        logmsg("Failed to compact shard");
        clean_up($shard_maint, $shard);
        exit 1;
    };

    # Make sure the shard hasn't come back online while we were compacting.
    # Shards are grouped by period, then as a list of objects with floor/ceiling/mode.
    my $shard_status = list_shards() or do {
        logmsg("Unable to query shard status before replacing $shard");
        clean_up($shard_maint, $shard);
        exit 1;
    };
    my $period_group = (first { $_->{'period'} == $period } @$shard_status)[0] or do {
        logmsg("Could not locate period $period in shard list");
        clean_up($shard_maint, $shard);
        exit 1;
    };
    my $checked_shard = (first { $_->{'block_floor'} == $floor &&
                                 $_->{'block_ceiling'} == $ceiling } @{$period_group->{'shard'}})[0] or do {
        logmsg("Could not locate shard with floor $floor to check its status");
        clean_up($shard_maint, $shard);
        exit 1;
    };
    if ($checked_shard->{'mode'} ne 'offline') {
        logmsg("Shard $shard came back online unexpectedly, cannot safely replace it.");
        clean_up($shard_maint, $shard);
        exit 1;
    }

    logmsg("Swapping compacted shard for original");
    my $old_orig = $shard_dir . '/.orig_' . $shard;

    move($full_shard_path,$old_orig) or do {
        logmsg("Relocating original shard failed: $!");
        clean_up($shard_maint, $shard);
        exit 1;
    };
    move($work_dir,$full_shard_path) or do {
        logmsg("Moving compacted shard into place failed: $!");
        # Can't online the shard here; we already moved the original aside
        # and can't put the compacted one in its place.
        clean_up();
        exit 1;
    };
    remove_tree($old_orig) or do {
        logmsg("Failed to remove original shard: $!");
        clean_up($shard_maint, $shard);
        exit 1;
    };

    logmsg("Bringing shard $shard back online");
    maintain_shard($shard_maint, 'online') or do {
        logmsg("Unable to set $shard online");
        clean_up();
        exit 1;
    };

    logmsg("Completed compaction on shard $shard\n===");
}

clean_up();

sub logmsg {
    my $msg = shift;
    printf("%s\n", $msg);
}

sub clean_up {
    my $shard_maint = shift;
    my $shard = shift;

    if ( $remove_smap > 0 ) {
        logmsg("Removing temporary map file $mapfile");
        unlink($mapfile);
    }

    if ( $shard ) {
        logmsg("Bringing shard $shard back online");
        maintain_shard($shard_maint, 'online') or die "Unable to set $shard online";
    }
}

sub maintain_shard {
    my $s_obj = shift;
    my $mode = shift;

    $s_obj->{'mode'} = $mode;

    my $http = HTTP::Tiny->new(
        default_headers => {
            'Accept' => 'application/json',
        },
        verify_SSL => 0
    );

    my $response = $http->request('POST', "$url_prefix" . "127.0.0.1:$port/nntbs_shard_maintenance", { content => encode_json($s_obj) });

    if ( ! $response->{'success'} ) {
        my $code    = $response->{'status'};
        my $reason  = $response->{'reason'};
        my $content;
        eval {
            $content = decode_json($response->{'content'});
        };
        if ($@) {
            logmsg("Error: $reason (HTTP $code)");
            return undef;
        } else {
            logmsg("$reason (HTTP $code): $content->{'error'}");
            return undef;
        }
    }

    return 1;
}

sub list_shards {
    my $http = HTTP::Tiny->new(
        default_headers => {
            'Accept' => 'application/json'
        },
        verify_SSL => 0
    );

    my $response = $http->request('GET', $url_prefix ."127.0.0.1:$port/list_nntbs_shards");

    my $code    = $response->{'status'};
    my $reason  = $response->{'reason'};
    my $content;
    eval {
        $content = decode_json($response->{'content'});
    };
    if ($@) {
        logmsg("Error: $reason (HTTP $code)");
        return undef;
    } elsif ( ! $response->{'success'} ) {
        logmsg("$reason (HTTP $code): $content->{'error'}");
        return undef;
    }

    return $content;
}

__END__

=head1 NAME

shard_compactor - Reduce the on-disk size of an existing numeric (NNTBS) shard by filtering out deleted metrics

=head1 SYNOPSIS

shard_compactor -d <nntbs_dir> -s <shard> [<shard> [<shard>] ...] [-m <mapfile>] [-p] [-h]

=head1 OPTIONS

=over 4

=item B<< -d, <directory> >>

The path to the directory containing NNTBS timeshards. This is typically found
under C</irondb/nntbs>, or C</snowth/nntbs> on Circonus Inside deployments. The
directory name matches the node's cluster UUID.

=item B<< -s, --shard <timeshard> >>

The timeshard on which to perform the compaction. This is a directory under the
NNTBS directory specified with C<-d>. Shards are named for the granularity of
rollup they represent, and their start and end timestamps.

Compaction is performed while IRONdb is running. This shard will be marked
offline during the compaction, and requests for metrics in the shard will be
proxied to other cluster nodes until the compaction is complete, at which point
the shard will be returned to online status.

If multiple shards are specified, they will be compacted serially.

=item B<< -m, --map <mapfile> >>

The path to an existing surrogate ID map file. This file contains a bitmap of
active surrogate IDs, which are the keys used in NNTBS timeshards. IDs which do
not appear in the map file are skipped during the compaction.

Note: the surrogate map is only valid for the host from which it was obtained.

To obtain a surrogate map:

C<curl -s -o $(hostname).smap localhost:8112/surrogate/all.smap>

If this option is not provided, a temporary copy will be obtained, and removed
at the completion of the script. It may be advantageous to obtain the map once
and reuse it for subsequent invocations of the script.

=item B<-p, --progress>

Print progress during the operation. This is generally only useful when used
interactively, as opposed to piping the output to a log file.

=item B<-t, --tls>

Enable connections to a TLS-configured cluster.

=item B<-h, --help>

Show usage information.

=back

=head1 CAVEATS

Compaction should only be performed on shards that are no longer getting new
data. In other words, shards that are older than the raw database's
C<min_delete_age> plus C<delete_after_quiescent_age>.

A surrogate ID map is only valid for the host from which it was obtained, and
should I<NEVER> be used for compacting shards on a different host.

=head1 EXAMPLES

=head2 Typical Usage

    /opt/circonus/bin/shard_compactor \
        -d /irondb/nntbs/84d2979a-f233-47d3-9a15-d4f8885c9b7c \
        -s 60_1551432000-1552041600

=head2 Using A Map File

    curl -s -o this_host.smap http://localhost:8112/surrogate/all.smap

    /opt/circonus/bin/shard_compactor \
        -d /irondb/nntbs/84d2979a-f233-47d3-9a15-d4f8885c9b7c \
        -s 60_1551432000-1552041600 \
        -m ./this_host.smap

=head2 Multiple Shards With Map File

    curl -s -o this_host.smap http://localhost:8112/surrogate/all.smap

    /opt/circonus/bin/shard_compactor \
        -d /irondb/nntbs/84d2979a-f233-47d3-9a15-d4f8885c9b7c \
        -s 60_1551432000-1552041600 60_1552041600-1552651200 \
        -m ./this_host.smap

=cut
