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

use warnings;
use strict;
use Fcntl;
use File::Basename;
use File::Spec;
use Getopt::Long;
use HTTP::Tiny;
use IO::Handle;
use JSON;
use Pod::Usage;
use POSIX qw(strftime);
use Time::HiRes qw(time);
use XML::LibXML;

my ($debug, $help, $submit_mode, $reset_progress);
my $conffile = '/opt/circonus/etc/irondb.conf';
my $inventory = '/var/tmp/whisper_inventory';
GetOptions ('c=s' => \$conffile,
            'i=s' => \$inventory,
            's'   => \$submit_mode,
            'r'   => \$reset_progress,
            'd'   => \$debug,
            'h'   => \$help);

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

if (! -r $conffile) {
    pod2usage( { -message => "IRONdb configuration file $conffile does not exist or is not readable",
                 -verbose => 0,
                 -exitval => 1 } );
}

if (defined $submit_mode && ! -r $inventory) {
    pod2usage( { -message => "Cannot read inventory from $inventory",
                 -verbose => 0,
                 -exitval => 1 } );
}

# We only support average and sum.
# Unsupported functions will be imported as 'avg'.
my $aggtypes = {
    1 => { name => 'avg',  supported => 'true' },
    2 => { name => 'sum',  supported => 'true' },
    3 => { name => 'last', supported => undef },
    4 => { name => 'max',  supported => undef },
    5 => { name => 'min',  supported => undef }
};

my $IWFH = IO::Handle->new;
$IWFH->autoflush(1);
$| = 1;

my $whisper_config = get_whisper_config($conffile) or die "No whisper directories found in $conffile\n";

if (defined $submit_mode) {
    print "Submitting metrics from $inventory\n";

    # progress file, place in same dir as inventory
    my $progress = dirname($inventory) . '/.submit_progress_' . $inventory;
    if (defined $reset_progress && -f $progress) {
        unlink($progress) or die "Failed to reset progress file: $!";
    }
    print "Tracking progress in $progress\n";
    my $PFH = IO::Handle->new;
    $PFH->autoflush(1);
    sysopen($PFH, $progress, O_RDWR|O_CREAT) or die "Unable to open progress file: $!";
    my $start_count = <$PFH>;
    chomp $start_count if defined $start_count;

    my $http = HTTP::Tiny->new(
        default_headers => {
            'accept' => 'application/json',
            'x-snowth-can-create-new' => 1
        }
    );

    open(my $IRFH, '<', $inventory) or die "Unable to get metric list from $inventory: $!";
    while(<$IRFH>) {
        # todo: API submission and progress tracking
        chomp $_;

        my $cur_line = $.;

        # if we had partial progress, skip to the first unprocessed line
        if (defined $start_count) {
            if ($cur_line <= $start_count) {
                next;
            }
        }

        my ($metric_name, $act_start, $act_end, $egress_func, $account_id, $check_uuid) = split(/\s+/, $_);
        my @activity;
        my @this_active_range = ( int($act_start), int($act_end) );
        splice @activity, 0, 0, \@this_active_range;  # API expects AoA

        my $payload = { metric_name => $metric_name, uuid => $check_uuid,
                        account_id => int($account_id), type => 'numeric',
                        egress_function => $egress_func, activity => \@activity };

        create_surrogate($payload, $http) or die "Failed to submit entry for $metric_name\n";
        seek($PFH, 0, 0);
        print $PFH $cur_line;
    }
    close($IRFH);
} else {
    open($IWFH, '>', $inventory) or die "Could not open inventory file $inventory for writing: $!";

    foreach my $whisper_dir ( keys %$whisper_config ) {
        if (! -d $whisper_dir) {
            die "Error: $whisper_dir does not appear to be a directory\n";
        }
    
        print "Scanning files under $whisper_dir, saving inventory to $inventory\n";
        process_dir($whisper_dir);
    }

    close($IWFH);
}

# End of program

sub dbglog {
    if ($debug) {
        my $msg = shift;
        my $t = time;
        printf("[%s] %s\n", strftime("%Y-%m-%d %H:%M:%S", localtime $t) . sprintf(".%06d", ($t-int($t))*1000000), $msg);
    }
}

sub get_whisper_config {
    my $conffile = shift;
    my $parser = XML::LibXML->new();
    my $conf;
    open(my $CFH, '<', $conffile) or die "Failed to open config file:$!";
    binmode $CFH;
    eval {
        $conf = $parser->load_xml(IO => $CFH);
    };
    if ($@) {
        die "$@";
    }
    close($CFH);
    
    my $root = $conf->getDocumentElement();
    my @nodes = $root->childNodes();
    my $whispers = {};
    
    foreach my $node (@nodes) {
        next if (ref $node eq 'XML::LibXML::Text');
        if ( $node->nodeName eq 'graphite' ) {
            my @gnodes = $node->childNodes();
            foreach my $gnode ( @gnodes ) {    
                next if (ref $gnode eq 'XML::LibXML::Text');
                if ( $gnode->nodeName eq 'whisper' ) {
                    my $dir   = $gnode->attributes()->{NodeMap}->{'directory'}->value();
                    my $uuid  = $gnode->attributes()->{NodeMap}->{'check_uuid'}->value();
                    my $acct  = $gnode->attributes()->{NodeMap}->{'account_id'}->value();

                    $whispers->{$dir} = { check_uuid => $uuid, account_id => $acct };
                }
            }
        }
    }

    if (%$whispers) {
        return $whispers;
    } else {
        return undef;
    }
}

sub process_wsp {
    my $file = shift;
    my $base_dir = shift;
    my $account_id = shift;
    my $check_uuid = shift;

    # make metric name from path, relative to base_dir
    my $metric_name = File::Spec->abs2rel($file, $base_dir);
    $metric_name =~ s/\.wsp$//;
    $metric_name =~ s/\//\./g;

    # discover timestamp range that contains data
    my $cmdout = `/opt/circonus/bin/wsp-scan "$file"`;
    chomp $cmdout;
    my @result = split(/\t/, $cmdout);
    my $start = $result[1];
    my $end = $result[2];
    my $aggnum = $result[3];

    my $aggfunc = $aggtypes->{$aggnum}{name};

    if (! defined $aggtypes->{$aggnum}{supported}) {
        print STDOUT "Warning: unsupported aggregation function '$aggfunc' for $metric_name - importing as 'avg'\n";
        $aggfunc = 'avg';
    }

    if (defined $start && defined $end) {
        dbglog("$metric_name: $start-$end ($aggfunc)");
        print $IWFH "$metric_name $start $end $aggfunc $account_id $check_uuid\n";  # write out to inventory
    } else {
        dbglog("Incomplete activity range for $metric_name - skipping");
    }
}

sub process_dir {
    my $this_dir = shift;
    my $base_dir = shift;

    if (! defined $base_dir) {
        $base_dir = $this_dir;
    }

    opendir(my $DH, $this_dir) or die "Unable to open $this_dir: $!";
    my @contents = readdir($DH);
    closedir($DH);

    foreach my $item (sort { $a cmp $b } @contents) {
        next if $item eq '.' or $item eq '..';
        my $fullpath = File::Spec->rel2abs("$this_dir/$item");

        if (-f $fullpath) {
            next unless $fullpath =~ /\.wsp$/;
            my $account_id = $whisper_config->{$base_dir}{account_id};
            my $check_uuid = $whisper_config->{$base_dir}{check_uuid};
            process_wsp($fullpath, $base_dir, $account_id, $check_uuid);
        } elsif (-d $fullpath) {
            process_dir($fullpath, $base_dir);
        }
    }
}

sub create_surrogate {
    my $payload  = shift;
    my $http     = shift;
    my $metric   = $payload->{metric_name};
    my $response = $http->request('POST', 'http://127.0.0.1:8112/surrogate/put', { content => encode_json($payload) });
    my $code     = $response->{status};
    my $reason   = $response->{reason};
    
    my $content;
    eval {
        $content = decode_json($response->{content});
    };
    if ($@) {
        if ($code eq '599') {
            # 599 is HTTP::Tiny default for "something went wrong",
            # and the plaintext reason is in the response content field.
            dbglog("Error: $response->{content}");
        } else {
            dbglog("Error: failed to decode response (HTTP $code, $reason)");
        }
        return undef;
    }

    my $outcome = 'success';
    if ( ! $response->{success} ) {
        if ($code eq '404') {
            # metric not owned on this node, can move on
            $outcome = 'not-owned';
        } else {
            dbglog("$reason (HTTP $code): $content->{'error'}");
            return undef;
        }
    } elsif ($content->{errors} > 0) {
        dbglog("Error encountered, see errorlog for details.");
        return undef;
    }

    dbglog("$metric $outcome");
    return 1;
}

__END__

=head1 NAME

whisper_loader - Scans and indexes Whisper databases for use by IRONdb

=head1 SYNOPSIS

whisper_loader [-c <config_file>] [-i <inventory_file>] [-d] [-s [-r]] [-h]

=head1 OPTIONS

=over 4

=item B<-c <configfile>>

IRONdb configuration file containing Whisper directory locations.

Default: /opt/circonus/etc/irondb.conf

=item B<-i <inventory_file>>

Inventory file containing discovered Whisper databases. In discovery mode (-s
option not present), information about each Whisper database will be written to
this file. In submit mode (-s), this file is read and each entry is used to
create a metric name index on the local IRONdb node.

Default: /var/tmp/whisper_inventory

=item B<-s>

Submit mode. Do not scan for Whisper files, instead read inventory and submit
entries to IRONdb's metric index API.

=item B<-r>

Reset submission progress (start from beginning of inventory). Normally,
submission tracks the last successful entry, and can resume where it left off
if interrupted. If it is necessary to restart the submission process from the
beginning, use this option in addition to -s.

=item B<-d>

Verbosely log activity to standard output.

=item B<-h>

Show usage summary.

=back

=head1 EXAMPLES

=head2 Discovery Mode

Use this mode to build up an inventory. This only needs to be done once, after
which the same inventory must be distributed to each IRONdb node for
submission.

    /opt/circonus/bin/whisper_loader -c /opt/circonus/etc/irondb.conf \
        -i /var/tmp/whisper_inventory

=head2 Submit Mode

Using an existing inventory file, run submit mode on each IRONdb node to create
the local metric name index entries. All IRONdb nodes in a cluster must have
these entries in order to know about Whisper files.

    /opt/circonus/bin/whisper_loader -c /opt/circonus/etc/irondb.conf \
        -i /var/tmp/whisper_inventory -s

=head1 DOCUMENTATION

See the IRONdb manual for more details:

L<https://docs.circonus.com/irondb/integrations/graphite/#native-whisper-read-support>

=cut
