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

use warnings;
use strict;
use Snowth::Topo;
use Regexp::Common qw/net/;
use Getopt::Long;
use Pod::Usage;
use POSIX qw/ceil strftime/;
use File::Temp;
use IPC::Open3;
use Symbol qw/gensym/;
use WWW::Curl::Easy;
use WWW::Curl::Multi;
use JSON;
use Data::Dumper;

my ($help, $want_write_copies, $bootstrap_node, $assume_yes);
my @nodes_to_add;
my @nodes_to_remove;

GetOptions('a=s' => \@nodes_to_add,
           'r=s' => \@nodes_to_remove,
           'w=i' => \$want_write_copies,
           'b=s' => \$bootstrap_node,
           'y'   => \$assume_yes,
           'h'   => \$help);

pod2usage(0) if $help;

if (! $bootstrap_node) {
    pod2usage( { -message => 'Missing bootstrap node.',
                 -verbose => 0,
                 -exitval => 1 } );
}
if (! @nodes_to_add && ! @nodes_to_remove) {
    pod2usage( { -message => 'No cluster changes requested (no nodes to add or remove.)',
                 -verbose => 0,
                 -exitval => 1 } );
}

my ($bsip, $bsport) = split(':', $bootstrap_node);

if ($bsip !~ /^$RE{net}{IPv4}{strict}$/ ) {
    bail("ERROR: Invalid bootstrap node address: '$bsip'. IP address must be an IPv4 dotted-quad decimal string.");
}

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

my $topo = Snowth::Topo->new( join(':', $bsip, $bsport) );
my $state = $topo->initial_state;

bail("Unable to get info about current cluster. Is the bootstrap node up and running?") unless $state;

my $current_topo_hash = $state->{'current'};
my $current_topo = $topo->compile_topo($current_topo_hash);
my $existing_write_copies = $current_topo->{'n'};
my $new_write_copies = $want_write_copies ? $want_write_copies : $existing_write_copies;

my $existing_cluster = {};
my ($port, $apiport, $weight);

foreach my $node (@{ $current_topo->{'host_config'} }) {
    my $this_id = $node->{'id'};

    $existing_cluster->{$this_id}{'address'} = $node->{'address'};
    $existing_cluster->{$this_id}{'side'}    = $node->{'side'};
    $existing_cluster->{$this_id}{'port'}    = $node->{'port'};
    $existing_cluster->{$this_id}{'apiport'} = $node->{'apiport'};
    $existing_cluster->{$this_id}{'weight'}  = $node->{'weight'};

    # Siphon off port, apiport, and weight for use with any new nodes
    # May need to make these configurable in the future
    $port    = $node->{'port'} unless $port;
    $apiport = $node->{'apiport'} unless $apiport;
    $weight  = $node->{'weight'} unless $weight;
}

my $additions = {};
my $cluster_is_sided = $current_topo->{'use_side'};

if (@nodes_to_add) {

    foreach my $adding_node (@nodes_to_add) {
        my ($ip, $uuid, $side) = split(/,/, $adding_node, 3);

        if ( $uuid =~ /^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/ ) {
            $uuid = lc($uuid);
        } else {
            bail("ERROR: Invalid UUID: $uuid");
        }

        bail("ERROR: Node $uuid is already part of the cluster") if $existing_cluster->{$uuid};

        bail("ERROR: Attempt to add sided node $uuid to existing non-sided cluster") if ($side && $cluster_is_sided == 0);

        bail("ERROR: Node $uuid invalid value for 'side': $side") if ($side && ($side ne 'a' && $side ne 'b') );

        bail("ERROR: Attempt to add non-sided node $uuid to sided cluster") if ((!defined $side) && ($cluster_is_sided == 1));

        if ( $ip =~ /^$RE{net}{IPv4}{strict}$/ ) {
            $additions->{$uuid}{'address'} = $ip;
        } else {
            bail("ERROR: Invalid address: $ip . IP address must be an IPv4 dotted-quad decimal string.");
        }

        $additions->{$uuid}{'side'}    = $side ? $side : 'both';
        $additions->{$uuid}{'port'}    = $port;
        $additions->{$uuid}{'apiport'} = $apiport;
        $additions->{$uuid}{'weight'}  = $weight;
    }
}

my $removals = {};

if (@nodes_to_remove) {
    foreach my $removing_node (@nodes_to_remove) {
        $removing_node = lc($removing_node);

        bail("ERROR: Node $removing_node is not part of the current cluster") unless $existing_cluster->{$removing_node};

        # Use the side value as our indicator so we can account for the
        # balance of nodes per side after additions and removals
        $removals->{$removing_node} = $existing_cluster->{$removing_node}{'side'};
    }
}

my $cluster_size  = keys %$existing_cluster;
my $nodes_added   = keys %$additions;
my $nodes_removed = keys %$removals;

my $new_cluster_size = ($cluster_size + $nodes_added) - $nodes_removed;
my $allowed_removals = $existing_write_copies - 1;
my ( $side_a_count, $side_b_count );

if ($cluster_is_sided == 1) {
    my $existing_a = grep { $existing_cluster->{$_}{'side'} eq 'a'} keys %$existing_cluster;
    my $existing_b = grep { $existing_cluster->{$_}{'side'} eq 'b'} keys %$existing_cluster;
    my $new_a      = grep { $additions->{$_}{'side'} eq 'a'} keys %$additions;
    my $new_b      = grep { $additions->{$_}{'side'} eq 'b'} keys %$additions;
    my $removed_a  = grep { $removals->{$_} eq 'a'} keys %$removals;
    my $removed_b  = grep { $removals->{$_} eq 'b'} keys %$removals;

    $side_a_count = ($existing_a + $new_a) - $removed_a;
    $side_b_count = ($existing_b + $new_b) - $removed_b;
}

# Some sanity checks

if ($new_cluster_size >= 6 && $new_write_copies < 3) {
    if (ask_to_continue("WARNING: Write copies should be at least 3 for clusters of 6 or more nodes; currently set to $new_write_copies.")) {
        print "Proceeding despite warning.\n";
    } else {
        bail("Stopping per user request.");
    }
}
if ($new_cluster_size >= 100 && $new_write_copies < 4) {
    if (ask_to_continue("WARNING: Write copies should be at least 4 for clusters of 100 or more nodes; currently set to $new_write_copies.")) {
        print "Proceeding despite warning.\n";
    } else {
        bail("Stopping per user request.");
    }
}
if ($new_cluster_size < $new_write_copies) {
    bail("ERROR: New cluster is too small ($new_cluster_size) for the number of write copies ($new_write_copies); cannot continue.");
}
if ($new_write_copies < 2) {
    bail("ERROR: Write copies must be at least 2, current value is $new_write_copies; cannot continue.");
}
if ($nodes_removed > $allowed_removals) {
    bail("ERROR: May not remove more than W-1 ($allowed_removals) nodes from the existing cluster per resize operation.");
}
if ($cluster_is_sided == 1) { 
    my $min_side_members = ceil($new_write_copies / 2);

    if ($side_a_count < $min_side_members) {
        bail("ERROR: New cluster's side 'a' has too few members ($side_a_count). Must have at least W/2 ($min_side_members) per side.");
    } elsif ($side_b_count < $min_side_members) {
        bail("ERROR: New cluster's side 'b' has too few members ($side_b_count). Must have at least W/2 ($min_side_members) per side.");
    }
}

# End sanity checks

printf("Revised cluster will have %d nodes, %d write copies.\n", $new_cluster_size, $new_write_copies);

print "\nExisting cluster:\n";
printf("Write copies: %d\n", $existing_write_copies);
printf("%-36s %-15s %s\n", 'NODE ID', 'ADDRESS', 'SIDE');
map { printf("%-36s %-15s %s\n",$_, $existing_cluster->{$_}{'address'}, $existing_cluster->{$_}{'side'}) } keys %$existing_cluster;

print "\nProposed changes:\n";

if ($new_write_copies != $existing_write_copies) {
    printf("Write copies: %d\n", $new_write_copies);
}

if ($nodes_added > 0) {
    print "\nAdditions:\n";
    printf("%-36s %-15s %s\n", 'NODE ID', 'ADDRESS', 'SIDE');

    map { printf("%-36s %-15s %s\n",$_, $additions->{$_}{'address'}, $additions->{$_}{'side'}) } keys %$additions;
}

if ($nodes_removed > 0) {
    print "\nRemovals:\n";
    printf("%-36s %-15s %s\n", 'NODE ID', 'ADDRESS', 'SIDE');

    map { printf("%-36s %-15s %s\n",$_, $existing_cluster->{$_}{'address'}, $existing_cluster->{$_}{'side'}) } keys %$removals;
}

ask_to_continue("\nPlease ensure the above changes are what you intend before proceeding.") or bail("Stopping per user request.");

# Make the changes

my $dateformat = '%Y-%m-%d %H:%M:%S %z';

printf( "[%s] Creating new topology\n", strftime($dateformat, localtime) );

# Nodes participating in the rebalance
# Will include any new and removed nodes
my $participants = { %$existing_cluster };

map { $participants->{$_} = $additions->{$_} } keys %$additions;

my $new_topo_xml = '<nodes write_copies="' . $new_write_copies . "\">\n";

# Must sort in order to get the same topo hash each time
foreach my $nodeid ( sort( keys %$participants ) ) {
    # Skip nodes that are leaving
    next if $removals->{$nodeid};

    my $side = $participants->{$nodeid}{'side'};

    my $node_entry;

    $node_entry .= '  <node id="' . $nodeid . "\"\n";
    $node_entry .= '        address="' . $participants->{$nodeid}{'address'} . "\"\n";
    $node_entry .= '        apiport="' . $participants->{$nodeid}{'apiport'} . "\"\n";
    $node_entry .= '        port="'    . $participants->{$nodeid}{'port'} . "\"\n";
    $node_entry .= '        side="'    . $side . "\"\n" unless $side eq 'both';
    $node_entry .= '        weight="'  . $participants->{$nodeid}{'weight'} . "\"/>\n";

    $new_topo_xml .= $node_entry;
}

$new_topo_xml .= "</nodes>\n";

my $tempfh = File::Temp->new( DIR      => '/tmp',
                              TEMPLATE => 'newtopo_XXXX',
                              SUFFIX   => '.xml' );
my $xml_file = $tempfh->filename;
print $tempfh $new_topo_xml;

my ($si_in, $si_out);
my $si_err = gensym;

my $si_cmd = "/opt/circonus/bin/snowthimport -t /tmp -f $xml_file";
my $si_pid = open3($si_in, $si_out, $si_err, $si_cmd);

waitpid( $si_pid, 0 );
my $si_exit = $? >> 8;

my $error_msg;
if ($si_exit > 0) {
    $error_msg = <$si_err>;

    printf( "[%s] Error getting new topology hash:\n", strftime($dateformat, localtime) );
    bail($error_msg);
}

my $new_topo_hash;
while (<$si_out>) {
    chomp $_;
    my $line = $_;

    if ( $line =~ /compiling to ([[:xdigit:]]+)$/ ) {
        $new_topo_hash = $1;
    }
}

printf( "[%s] New topology: %s\n", strftime($dateformat, localtime), $new_topo_hash );

printf( "[%s] Loading new topology to all nodes\n", strftime($dateformat, localtime) );

my $load_curlm = WWW::Curl::Multi->new();
my $load_curl_id = 1;
my $load_active_handles = 0;
my $load_easy = {};

foreach my $new_node ( keys %$participants ) {
    my $node_addr = $participants->{$new_node}{'address'};
    my $node_port = $participants->{$new_node}{'apiport'};
    my $load_url  = "http://$node_addr:$node_port/topology/$new_topo_hash";

    my $load_curl = WWW::Curl::Easy->new();
    $load_easy->{$load_curl_id} = { curl => $load_curl, node => "$node_addr:$node_port", response => '' };

    $load_curl->setopt(CURLOPT_PRIVATE, $load_curl_id);
    $load_curl->setopt(CURLOPT_CONNECTTIMEOUT_MS, 5000);
    $load_curl->setopt(CURLOPT_TIMEOUT_MS, 5000);
    $load_curl->setopt(CURLOPT_POST, 1);
    $load_curl->setopt(CURLOPT_URL, $load_url);
    $load_curl->setopt(CURLOPT_HTTPHEADER, [ 'Content-Type: text/xml' ]);
    $load_curl->setopt(CURLOPT_POSTFIELDS(), $new_topo_xml);
    $load_curl->setopt(CURLOPT_WRITEDATA, \$load_easy->{$load_curl_id}{response});

    $load_curlm->add_handle($load_curl);
    $load_active_handles++;
    $load_curl_id++;
}

my $failed_loads = 0;

while ($load_active_handles) {
    my $active_loads = $load_curlm->perform;

    if ($active_loads != $load_active_handles) {
        while (my ($id,$return_value) = $load_curlm->info_read) {
            if ($id) {
                $load_active_handles--;
                my $info   = $load_easy->{$id};
                my $curlh  = $load_easy->{$id}{curl};
                my $httprc = $curlh->getinfo(CURLINFO_HTTP_CODE);

                if($return_value == 0 && $httprc == 200) {
                    printf( "[%s] Loaded successfully to %s\n", strftime($dateformat, localtime), $info->{node} );
                } else {
                    printf( "[%s] Failed loading to %s:\n", strftime($dateformat, localtime), $info->{node} );
                    if ( $httprc > 0 ) {
                        printf("  HTTP %s: %s\n", $httprc, $info->{response});
                    } else {
                        printf("  %s: %s\n", $curlh->strerror($return_value), $curlh->errbuf);
                    }
                    $failed_loads++;
                }
                delete $load_easy->{$id}{curl};
            }
        }
    }
}

bail("Unable to load new topology to all nodes. Please ensure that all nodes that are part of the new cluster are installed, running, and reachable from where this script is being run.") if $failed_loads > 0;

# Activate the new topology, starting the rebalance
printf( "[%s] Activating new topology on all nodes to begin the rebalance\n", strftime($dateformat, localtime) );

my $act_curlm = WWW::Curl::Multi->new();
my $act_curl_id = 1;
my $act_active_handles = 0;
my $act_easy = {};

foreach my $new_node ( keys %$participants ) {
    my $node_addr = $participants->{$new_node}{'address'};
    my $node_port = $participants->{$new_node}{'apiport'};
    my $act_url  = "http://$node_addr:$node_port/rebalance/activate/$new_topo_hash";

    my $act_curl = WWW::Curl::Easy->new();
    $act_easy->{$act_curl_id} = { curl => $act_curl, node => "$node_addr:$node_port", response => '' };

    $act_curl->setopt(CURLOPT_PRIVATE, $act_curl_id);
    $act_curl->setopt(CURLOPT_CONNECTTIMEOUT_MS, 5000);
    $act_curl->setopt(CURLOPT_TIMEOUT_MS, 5000);
    $act_curl->setopt(CURLOPT_POST, 1);
    $act_curl->setopt(CURLOPT_POSTFIELDSIZE, 0);
    $act_curl->setopt(CURLOPT_URL, $act_url);
    $act_curl->setopt(CURLOPT_WRITEDATA, \$act_easy->{$act_curl_id}{response});

    $act_curlm->add_handle($act_curl);
    $act_active_handles++;
    $act_curl_id++;
}

my $failed_activates = 0;

while ($act_active_handles) {
    my $active_activations = $act_curlm->perform;

    if ($active_activations != $act_active_handles) {
        while (my ($id,$return_value) = $act_curlm->info_read) {
            if ($id) {
                $act_active_handles--;
                my $info   = $act_easy->{$id};
                my $curlh  = $act_easy->{$id}{curl};
                my $httprc = $curlh->getinfo(CURLINFO_HTTP_CODE);

                if($return_value == 0 && $httprc == 200) {
                    printf( "[%s] Activated successfully on %s\n", strftime($dateformat, localtime), $info->{node} );
                } else {
                    printf( "[%s] Failed activation on %s:\n", strftime($dateformat, localtime), $info->{node} );
                    if ( $httprc > 0 ) {
                        printf("  HTTP %s: %s\n", $httprc, $info->{response});
                    } else {
                        printf("  %s: %s\n", $curlh->strerror($return_value), $curlh->errbuf);
                    }
                    $failed_activates++;
                }
                delete $act_easy->{$id}{curl};
            }
        }
    }
}

bail("Unable to activate new topology on all nodes.") if $failed_activates > 0;

printf( "[%s] New topology $new_topo_hash has been loaded and activated on all nodes.\n", strftime($dateformat, localtime) );
print "Rebalance may take a significant amount of time depending on the amount\n";
print "of data to relocate.\n";

print "\nEach node will report its progress during the rebalance at\n";
print "http://<node>:<apiport>/rebalance/state\n";
print "\nDocumentation: https://www.irondb.io/docs/api/rebalance-state.html\n";

# End of program

sub ask_to_continue {
    my ($msg) = @_;
    local $| = 1;
    print $msg . "\nContinue? (y/n): ";

    if ($assume_yes) {
        print "y\n";
        return 1;
    }

    chomp(my $resp = <STDIN>);
    return lc($resp) eq 'y';
}

sub bail {
    my ($msg) = @_;

    print "$msg\n";
    exit 1;
}

__END__

=head1 NAME

resize_cluster - Change the IRONdb cluster topology

=head1 SYNOPSIS

resize_cluster -b <ip[:apiport]> [-a <ip,uuid[,side]> [-a <ip,uuid[,side]>] ...] [-r <uuid> [-r <uuid>] ...] [-w <number>] [-y] [-h]

At least one instance of -a|-r is required.

=head1 OPTIONS

=over 4

=item B<-b <ip[:apiport]>>

IP address of a node in the running cluster from which to bootstrap the current
topology. Ideally this would be a node that is not changing with this operation.
If no port is specified, the default API port (8112) is used.

=item B<-a <ip,uuid[,side]>>

Specifies a node to add to the cluster. May be specified multiple times to add
multiple nodes. The value is at least two, possibly three comma-separated
components:

=over 2

=item ip

The node's IP address.

=item uuid

The node's UUID identifier.

=item side

(Optional) The side of the cluster on which this node should be added, if the
cluster being modified is sided. Acceptable values for the side are "a" or "b".

If the cluster is not sided, you MUST NOT specify a sided node.  Conversely, if
the cluster is sided, you MUST specify the side on which this node is to be
added.

=back

=item B<-r <uuid>>

Specifies an existing node to remove from the cluster. The argument is the
node's UUID. This option may be specified multiple times to remove multiple
nodes in one operation.

=item B<-w <number>>

An integer indicating the number of write copies for the updated cluster. If
not specified, the value from the existing cluster will be used, but may
generate warnings depending on the number of nodes in the revised topology.

=item B<-y>

Assume 'yes' as the answer to all prompts.

=item B<-h>

Print a usage summary.

=back

=cut
