#!/bin/sh
#
# Copy the local ZXTM's config onto all other ZXTMs

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "replicate-config FATAL: ZEUSHOME not set"
   exit 1
fi

# Try to get networking commands into our PATH
PATH=/sbin:/usr/etc/sbin:/usr/etc:/usr/sbin:$PATH

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}

#!perl -w
#line 31

=head1 NAME

replicate-config - copy ZXTM configuration across the cluster of ZXTMs

=head1 SYNOPSIS

B<replicate-config>

=head1 DESCRIPTION

B<replicate-config> will take a complete copy of the local ZXTM's'
configuration, and copy it across to all other ZXTMs that are in the
cluster.

=head1 COPYRIGHT

Copyright (C) 2000-2013 Zeus Technology Limited. All rights reserved.

=cut


# setup our libraries
BEGIN {
   unshift @INC, ( "$ENV{ZEUSHOME}/perl",
                   "$ENV{ZEUSHOME}/admin/lib/perl",
                   "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
                   "$ENV{ZEUSHOME}/zxtm/lib/perl",
                 );
}

use Zeus::ZXTM::AMP;
use Zeus::ZXTM::Version qw( ZXTMVersion ZXTMReleaseVersion );
use Zeus::ZXTM::Utils qw( GetServerName );
use Zeus::ZXTM::EventLog qw( logEvent ZLOG_WARN ZLOG_SERIOUS );
use Zeus::Execute;
use Zeus::WaitLock;
use Zeus::KeyValueConfigFile;
use Zeus::ZXTM::StorageManager;
use strict;

# Lock files
my $lockDirectory = "$ENV{ZEUSHOME}/zxtm/internal/persistent-data";
my $runningLock = "$lockDirectory/replicate-config-rLock";
my $waitingLock = "$lockDirectory/replicate-config-wLock";
my $logfile = "$ENV{ZEUSHOME}/zxtm/log/replicate-config";

# Command line arguments
my @args = @ARGV;
my $keeptar = 0;
my $upgrade_tar = 0;
my $partial = undef;

# Timeouts
my $timeout = 0;

# truncate_logfile($storage_manager)
# If the replicate-config logfile size goes above the configured
# 'replicate_config_log_max' kb then shrink it (discarding oldest lines) to
# 'replicate_config_truncate_size' kb.
# The truncate_size should be a lot smaller than log_max, so that shrinking
# only need to be done occasionally.
# 'replicate_config_log_max' and 'replicate_config_truncate_size' are
# expert config keys.
sub truncate_logfile($)
{
   my ($storage_mngr) = @_;
   my $globals = $storage_mngr->getGlobalConfig();
   if( defined( $globals ) ) {
      # Find out how large the logfile is allowed to be.
      my $log_max_size = $globals->get( "replicate_config_log_max" );
      $log_max_size *= 1024; # This value was in kb.

      # A 0 value implies we should not do any logfile shrinking.
      if( $log_max_size != 0 ) {
         # Open logfile for read.
         my $log_fh;
         if( open( $log_fh, '<', $logfile ) ) {
            seek( $log_fh, 0, 2 ); # Seek to EOF so tell gives the file size.
            if( $log_max_size < tell( $log_fh ) ) {
               # Logfile has grown too big. Find desired new size.
               my $log_truncate_size =
                  $globals->get( "replicate_config_truncate_size" );
               $log_truncate_size *= 1024; # This value was in kb.

               # Check the config is reasonable.
               if ( $log_truncate_size > $log_max_size ) {
                  # Bad configuration of keys. Delete keys, restoring defaults.
                  $globals->delete( "replicate_config_truncate_size" );
                  $globals->delete( "replicate_config_log_max" );

                  print( "The config for the config replication logfile size was bad.\n" );
                  logEvent(
                     type => ZLOG_WARN,
                     msg => "Bad replicate_config_log limits, reset."
                  );

                  # Update the Config on Disk.
                  $storage_mngr->putConfig( $globals );

                  # These config values were in kb.
                  $log_max_size *= 1024;
                  $log_truncate_size *= 1024;
               }

               # Seek to truncate_size bytes before EOF.
               seek( $log_fh, -$log_truncate_size, 2 );
               # Then skip to end of line.
               scalar <$log_fh>;

               #  Create a file for swapping.
               my $swap_logfile = $logfile . "-tmp";
               my $new_log_fh;
               open( $new_log_fh, '>', $swap_logfile );

               # and copy to EOF to swap.
               while( my $line = <$log_fh> ) {
                  print( { $new_log_fh } $line );
               }
               close( $new_log_fh );

               # Replace the logfile with the shrinked copy.
               rename( $swap_logfile, $logfile );
            }
            close( $log_fh );
         }
      }
   }
}

sub replicateConfig
{
   my $storage_mngr = new Zeus::ZXTM::StorageManager();

   # Flush buffers, else text gets printed twice
   $| = 1;

   # Log activity
   truncate_logfile( $storage_mngr );
   my $log_fh;
   open( $log_fh, '>>', $logfile );
   print( { $log_fh }
      "Config replicate started [" .
         scalar( localtime() ) . " - " . time .
      "]\n" .
      "Command: [$0 @args]\n"
   );

   # Now find the systems to send it to
   my $dir = "$ENV{ZEUSHOME}/zxtm/conf";
   if( ! opendir( DIR, "$dir/zxtms" ) ) {
      print( { $log_fh } "FATAL: Could not open zxtms directory for read\n" );
      die( "Can't read the traffic manager configuration directory: $!\n" );
   }
   my @zxtms = grep !/(^\.)|~$|(^\#)/, readdir( DIR );
   closedir( DIR );

   # Don't send the config to ourselves, we already kind of have it:
   my $hostname = GetServerName();
   if( ! $ENV{Z_TEST_REPLICATE_SELF} ) {
      @zxtms = grep { $_ ne $hostname } @zxtms;
   }

   # check whether we have to do anything at all:
   if( 0 == scalar( @zxtms ) && !$keeptar ) {
      print( { $log_fh } "No other machines, exiting [" . scalar( localtime() ) . " - " . time . "]\n" );
      print( "There are no other traffic managers to replicate the configuration to\n" );
      # we are the only machine in this cluster, no need to do
      # any replication at all
      return 0;
   }

   # check whether config storage is shared, in which case we don't need
   # to send the config around, and can instead just tell the peers
   # to reread the config
   my $settings = $storage_mngr->getSettingsConfig();
   my $is_shared = 0;
   if( defined( $settings ) ) {
      my $conf_is_shared = $settings->get("config!storage_shared");
      if( defined( $conf_is_shared ) && $conf_is_shared =~ /^y/i ) {
         $is_shared = 1;
      }
   }
   my $amp = undef;
   my $tarfile = undef;
   my $errors = 0;
   my $remote = 0;
   my $body_regex = undef;
   if( $is_shared ) {
      print( { $log_fh } "Config is shared, tell peers to reload\n" );
      $amp = Zeus::ZXTM::AMP::Multiplex(
                                        \&Zeus::ZXTM::AMP::changedconfig,
                                        [ HEADERS => { 'X-Poke-Configd' => '1' },
					  IGNORE_DEATH => 1, ],
                                        $timeout, @zxtms
                                       );

   } else {
      # Generate a tarfile
      $tarfile = "$ENV{ZEUSHOME}/zxtm/internal/conf.tar";
      $body_regex = 'Update successful';

      unlink( $tarfile ) if( -e $tarfile );
      chdir( $dir ) or die "Failed to change to directory '$dir': $!\n";

      my $targets = '*';
      if( $partial ) {
         $targets = $partial;
         $targets =~ s/,/ /g;
      }

      print( { $log_fh } "Taring up config: [tar cf $tarfile $targets]\n" );
      my( $exitcode, $stdout, $stderr ) = Zeus::Execute::execute(
         "tar cf $tarfile $targets",
         undef, undef, undef, $timeout
      );
      if( $exitcode ) {
         chomp( $stderr );
         print( { $log_fh } "FATAL: Failed to generate tar file:$stderr\n" );
         die( "Tar file generation failed:$stderr\n" )
      } else {
         # This next piece of output is used to signal the REST Daemon that tarring is complete.
         print( "Tar file generation successful\n" )
      }

      if( 0 == scalar( @zxtms ) ) {
         print( { $log_fh } "No other machines, exiting [" . scalar( localtime() ) . " - " . time . "]\n" );
         print "There are no other traffic managers to replicate the configuration to\n";
         # we are the only machine in this cluster, no need to do
         # any replication at all
         return 0;
      }

      if( $partial ) {
         touch( "$ENV{ZEUSHOME}/zxtm/.lastreplicate_partial" );
      } else {
         touch( "$ENV{ZEUSHOME}/zxtm/.lastreplicate" );
      }

      my %headers = ( 'Zxtm-Version' => ZXTMVersion() );
      $headers{'Upgrade-Tar'} = ZXTMReleaseVersion() if( $upgrade_tar );
      $headers{'Partial'} = $partial if( $partial );

      print( { $log_fh } "Sending tar to other traffic managers [@zxtms]\n" );
      $amp = Zeus::ZXTM::AMP::Multiplex(
                                        \&Zeus::ZXTM::AMP::configtar,
                                        [ $tarfile, HEADERS => \%headers, IGNORE_DEATH => 1,  ],
                                        $timeout, @zxtms
                                       );
   }
   print( { $log_fh } "AMP calls finished\n" );

   foreach my $zxtm ( @zxtms ) {
      # Kind of a lie... we've already done the sending, but leaving
      # this in so that the program behaves the same way as it always did.
      print "Sending configuration to machine '$zxtm'...\n";
      $remote++;

      my( $status, $error, $body, $header ) = @{$amp->{$zxtm}};

      if( $ENV{Z_TEST_REPLICATE_PAUSE} ) {
         sleep( $ENV{Z_TEST_REPLICATE_PAUSE} );
      }

      if( $error ne "" ) {
         # Connection-level error. Will mention the machine we're connecting to
         chomp( $error );
         print( { $log_fh } "Connection Error [$zxtm]: $error\n" );
         print STDERR "$error\n";
         $errors++;
         next;
      }

      if( !$status ) {
         # AMP error (e.g. commkey wrong)
         chomp( $body );
         print( { $log_fh } "AMP Error [$zxtm]: $body\n" );
         print STDERR "$zxtm: $body\n";
         $errors++;
         next;
      }

      # AMP request 'worked', but remote machine may still have had problems
      if( defined( $body_regex ) && $body !~ /$body_regex/ ) {
         chomp( $body );
         print( { $log_fh } "Possible remote command error [$zxtm]: $body\n" );
         print STDERR "$zxtm: $body\n";
         $errors++;
      }

      # If we reach here, it all worked
   }
   if( defined( $tarfile ) ) {
      print( { $log_fh } "Erasing temp tarfile [$tarfile]\n" );
      unlink( $tarfile ) unless( $keeptar );
   }

   if( !$remote ) {
      print "There are no other traffic managers to replicate the configuration to\n";
   } else {
      if( $errors ) {
         print "\nThere were errors replicating the configuration\n";
      } else {
         print "\nConfiguration replication completed successfully\n";
      }
   }

   print( { $log_fh }
      "Replicate finished ($errors errors) [" .
         scalar( localtime() ) . " - " . time .
      "]\n"
   );
   close( $log_fh );

   return $errors;
}

sub touch( $ )
{
   my $file = shift;
   if( open TOUCH, ">$file" ) {
      close TOUCH;
   }
}

###############################################################################

# Any args?
while( @ARGV ) {
   $_ = shift;
   if( /^--help$/i ) {
      print "Usage: replicate-config\n";
      exit 0;
   } elsif( /^--keeptar$/i ) {
      # For debug
      $keeptar = 1;
   } elsif( /^--upgradetar$/i ) {
      $upgrade_tar = 1;
   } elsif( /^--partial=(.*)$/i ) {
      $partial = $1;
   } elsif( /^--timeout$/i ) {
      $timeout = shift;
   }
}

my $partialLock = '__all__';
if( $partial ) {
   $partialLock = $partial;
   $partialLock =~ s/,/_-_/g;
}

Zeus::ZInstall::Common::Mkdir( "$lockDirectory", 0777 );
my $lock = new Zeus::WaitLock( $runningLock, $waitingLock . $partialLock );

my $exitcode = -1;
my( $err, $err_desc ) = $lock->RunLocked(
   { timeout => ($timeout == 0 ? 10 : $timeout), run_timeout => $timeout },
   sub {
      $exitcode = replicateConfig();
   }
);

if( $err ) {
   if( $err eq 'WAIT-TIMEOUT' ) {
      # Another process is currently waiting to start replicating the same
      # subset of the config.  Our changes will be replicated by this.
      exit( 0 );
   } else {
      die( "Replicate failed: $err_desc\n" );
   }
}

exit( $exitcode );
