#!/bin/sh
# vim:set syn=perl:
#
# Push statd logs across the ZTM cluster

# 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 "sync-logs: 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 32

=head1 NAME

sync logs - copy statd logs across the cluster of ZXTMs

=head1 SYNOPSIS

B<sync-logs>

=head1 DESCRIPTION

B<sync-logs> pushes the statd logs generated by this machine and by any
machines that have since left the cluster to the other cluster members.

=head1 COPYRIGHT

Copyright (C) 2010-2014 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::StorageManager;
use Zeus::ZXTM::EventLog qw( logEvent ZLOG_WARN ZLOG_INFO ZLOG_SERIOUS );
use Zeus::KeyValueConfigFile;
use Fcntl qw( O_WRONLY O_CREAT O_TRUNC );
use FileHandle;
use strict;


my $verbose = 0;
my $lock_timeout = 10;
my $got_running_lock = 0;
my $got_waiting_lock = 0;
my $runningLock = "$ENV{ZEUSHOME}/zxtm/internal/logsRLock";
my $waitingLock = "$ENV{ZEUSHOME}/zxtm/internal/logsWLock";
my $runningPid = "$ENV{ZEUSHOME}/zxtm/internal/logsRPid";
my $storage = new Zeus::ZXTM::StorageManager;

# Cleanup locks upon exit
END {
   rmdir( $waitingLock ) if( $got_waiting_lock );
   rmdir( $runningLock ) if( $got_running_lock );
   unlink( $runningPid ) if( $got_running_lock );
}


sub getCommkey()
{
   local *COMM;
   my $commfile = "$ENV{ZEUSHOME}/zxtm/conf/commkey";
   open( COMM, "< $commfile" ) or return undef;
   my $commkey = <COMM>;
   chomp( $commkey );
   close( COMM );
   return $commkey;
}

sub getControlPort($)
{
   my( $zxtm ) = @_;
   my $cfg = $storage->getZXTMConfig($zxtm);
   return $cfg->get( "controlport" );
}

sub getCertificate($)
{
   my( $zxtm ) = @_;
   my $cfg = $storage->getZXTMConfig($zxtm);
   return $cfg->get( "control!certificate" );
}

sub contains($@)
{
   my( $needle, @haystack ) = @_;
   return scalar grep { $_ eq $needle } @haystack;
}

sub wipeReqFile($$)
{
   my( $req, $reqfile ) = @_;

   # A primitive wipe of the request temporary file, because it contains the commkey.
   seek( $req,0,0 );
   print $req "\0" x 100;
   close( $req );
   unlink( $reqfile );
}

sub syncLogs()
{
   # Flush buffers, else text gets printed twice
   $| = 1;

   touch( "$ENV{ZEUSHOME}/zxtm/conf/.lastsynclogs" );

   # Now find the systems to send it to
   my $zxtmsdir = "$ENV{ZEUSHOME}/zxtm/conf/zxtms";
   unless( opendir( DIR, $zxtmsdir ) ) {
      logEvent(
         type => ZLOG_SERIOUS,
         msg => "sync-logs aborted: cannot open $zxtmsdir: $!",
      );
      return 1;
   }
   my @zxtms = grep { !/(^\.)|~$|(^\#)/ && -f "$zxtmsdir/$_" } readdir( DIR );
   closedir( DIR );

   # Find out which machine is ours
   my $hostname = GetServerName();
   @zxtms = grep { $_ ne $hostname } @zxtms;

   my $errors = 0;
   my $remote = 0;
   my %headers = ( 'Zxtm-Version' => ZXTMVersion() );

   my $statddir = "$ENV{ZEUSHOME}/zxtm/log/statd";
   unless( opendir( DIR, $statddir ) ) {
      logEvent(
         type => ZLOG_SERIOUS,
         msg => "sync-logs aborted: cannot open $statddir: $!",
      );
      return 1;
   }
   my @logswehave = grep { !/^\./ && -d "$statddir/$_" } readdir( DIR );
   closedir( DIR );

   my $commkey = getCommkey();
   unless( defined( $commkey ) ) {
      logEvent(
         type => ZLOG_SERIOUS,
         msg => "sync-logs aborted: cannot read commkey",
      );
      return 1;
   }

   foreach my $zxtm ( @zxtms ) {
      # Check if state sharing is complaining it can't connect. If it can't 
      # skip this traffic manager without an error, we're already complaining
      if( Zeus::ZXTM::AMP::StateConnectionStatus( $zxtm ) eq 'FAILED' ) {
         next;
      }

      my $connect_host = Zeus::ZXTM::AMP::getStateIP( $zxtm ) || $zxtm; 
      print "got external IP $connect_host\n" if $verbose;
      my $msg_host = ($connect_host eq $zxtm) ? $zxtm : "$connect_host ($zxtm)";
      # TODO just sync local logs, and do the ghosts once on cluster join (bug 15825)
      my @logstosend = map { "\"$statddir/$_\"" } grep { $_ ne $zxtm && ! contains( $_, @zxtms ) } @logswehave;
      if( ! scalar @logstosend ) {
         if( $verbose ) {
            logEvent(
               type => ZLOG_INFO,
               msg => "sync-logs: Nothing suitable to send to '$msg_host'",
            );
         }
         next;
      }

      $remote++;
      if( $verbose ) {
         logEvent(
            type => ZLOG_INFO,
            msg => "sync-logs: Sending statd logs to '$msg_host'",
         );
      }

      my $cport = getControlPort($zxtm);
      if ( !$cport ) {
         logEvent(
            type => ZLOG_SERIOUS,
            msg => "sync-logs: sync to $zxtm failed: missing control port"
         );
         next;
      }

      my $ztmcert = getCertificate($zxtm);
      if ( !$ztmcert ) {
         logEvent(
            type => ZLOG_SERIOUS,
            msg => "sync-logs: sync to $zxtm failed: missing control certificate"
         );
         next;
      }
      my $clientcert = "$ENV{ZEUSHOME}/zxtm/etc/control/control.public";
      my $clientkey = "$ENV{ZEUSHOME}/zxtm/etc/control/control.private";
      if ( ! -r  $clientcert ) {
         logEvent(
            type => ZLOG_SERIOUS,
            msg => "sync-logs aborted: "
               . "cannot read control client certificate: $clientcert"
         );
         return 1; # not likely to be any better next time around
      }
      if ( ! -r  $clientkey ) {
         logEvent(
            type => ZLOG_SERIOUS,
            msg => "sync-logs aborted: "
               . "cannot read control client key: $clientkey"
         );
         return 1; # not likely to be any better next time around
      }

      my $reqfile = "$ENV{ZEUSHOME}/zxtm/internal/rsync-request-$$";
      if( -f $reqfile ) {
         logEvent(
            type => ZLOG_WARN,
            msg => "sync-logs deleting stale temporary file $reqfile",
         );
      }
      if( ! sysopen( REQ, $reqfile, O_WRONLY | O_CREAT | O_TRUNC, 0600 ) ) {
         logEvent(
            type => ZLOG_SERIOUS,
            msg => "sync-logs aborted: "
               . "cannot write to temporary file $reqfile: $!",
         );
         return 1;
      }
      REQ->autoflush(1);
      print REQ "POST /zxtm/rsyncstatd HTTP/1.0\r\nCommkey: $commkey\r\n\r\n";
      my $zconnectcmd = "$ENV{ZEUSHOME}/admin/bin/zconnect --ssl "
         . "--sslid=$ENV{ZEUSHOME}/admin/internal/ssl-$connect_host:$cport "
         . "--cert=$clientcert --key=$clientkey --peercert=$ztmcert "
         . "--send-file=\\\"$reqfile\\\" $connect_host $cport";
      print $zconnectcmd, "\n" if $verbose;
      # We use a relative path here; the destination's rsync should have been
      # launched in ZEUSHOME, which saves us working out what their ZEUSHOME is.
      # -e specifies an rsh-like command to connect to the remote host.
      # FIXME We're relying on zconnect ignoring extra args (host+command). We
      # should really make a wrapper script to discard them.
      my $errorReason;
      my @errors;
      open( RSYNC_ERRORS, "$ENV{ZEUSHOME}/zxtm/bin/rsync -az -e \"$zconnectcmd\" @logstosend $zxtm: 2>&1 |" ) or do {
         logEvent(
            type => ZLOG_WARN,
            msg => "sync-logs aborted: cannot execute rsync: $!",
         );
         wipeReqFile( \*REQ, $reqfile );
         return 1;
      };
      while( <RSYNC_ERRORS> ) {
         chomp;
         if( /\bConnection refused\b/
            || /\bwrite failed on\b/
            || /\bSocket connect failed\b/
            || /\bCannot resolve DNS .*/
            || /\bconnection unexpectedly closed\b/ ) {
            $errorReason = $_;
            last;
         }
         $_ = "rsync: $_" unless /^rsync/;
         push @errors, $_;
      }
      if( ! $errorReason ) {
         for (@errors) {
            logEvent(
               type => ZLOG_WARN,
               msg => $_,
            );
         }
      }
      close( RSYNC_ERRORS );
      my $closeError = $?;

      wipeReqFile( \*REQ, $reqfile );

      if( $closeError ) {
         $errorReason ||= scalar(@errors) ? "see previous lines" : ("rsync exited with status ".($closeError >> 8));
         logEvent(
            type => ZLOG_WARN,
            msg => "sync-logs: sync to $msg_host failed: $errorReason",
         );
         $errors++;
         next;
      }

      # If we reach here, it all worked
   }

   if( !$remote ) {
      if( $verbose ) {
         logEvent(
            type => ZLOG_INFO,
            msg => "sync-logs: No other machines to send statd logs to",
         );
      }
   } else {
      if( ! $errors && $verbose ) {
         logEvent(
            type => ZLOG_INFO,
            msg => "sync-logs: Statd logs replication completed successfully",
         );
      }
   }

   return $errors;
}

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


# Returns the age of a file in seconds, or undef if the file doesn't exist
sub age($)
{
   my $file = shift;
   my @st = stat( $file );
   return undef if( !-e _ );
   return time() - $st[8];
}

# Set our own pid in the logsRPid file.
sub set_pid()
{
   open( FILE, ">$runningPid" ) or die "sync-logs: Cannot open file $runningPid : $!\n";
   print FILE $$;
   close( FILE );
}

# Get the pid of the process currently running the sync logs.
sub get_pid()
{
   open( FILE, "<$runningPid" ) or return undef;
   my $pid = <FILE>;
   close( FILE );
   return $pid;
}


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


# Any args?
while( @ARGV ) {
   $_ = shift;
   if( /^--help$/i ) {
      print "Usage: sync-logs\n";
      exit 0;
   } elsif( /^--verbose$/ ) {
      $verbose = 1;
   } elsif( /^--timeout$/i ) {
      $lock_timeout = shift;
   }
}

if( -e $waitingLock ) {
   # Can't even wait, forget running....
   exit(0);
}

# Aquire Running Lock
if( mkdir( $runningLock, 0700 )) {
   # Payload
   $got_running_lock = 1;
   set_pid();

   my $exitcode = syncLogs();

   # Unlock Running Lock
   rmdir( $runningLock );
   unlink( $runningPid );
   $got_running_lock = 0;
   exit( $exitcode );
}

# Aquire waiting lock
if( !mkdir( $waitingLock, 0700 )) {
   # If we couldn't create the waiting lock, someone else did, so they
   # will do the replicate
   exit 0;
}

$got_waiting_lock = 1;

# Wait until the running lock is dropped by someone
while( 1 ) {
   if( mkdir( $runningLock, 0700 )) {
      $got_running_lock = 1;
      set_pid();
      last;
   }

   # Check age of running lock
   my $age = age( $runningLock );
   if( defined( $age ) && ( $age > $lock_timeout )) {
      # kill the running process. 
      my $pid = get_pid();
      kill 9, $pid if( $pid );
      rmdir( $runningLock );
      # Don't sleep, we want to grab this lock NOW
   } else {
      select( undef, undef, undef, 0.2 );
   }
}

rmdir( $waitingLock );
$got_waiting_lock = 0;

# Payload
my $exitcode = syncLogs();

# Unlock Running Lock
rmdir( $runningLock );
unlink( $runningPid );
$got_running_lock = 0;

exit( $exitcode );
