#!/bin/sh
#
# Do the recurring log work:
#    Set up environment.
#    Start a nice perl {
#       initialise
#       read state
#       log maintenance (create new tarballs, and delete really old ones).
#       update state files
#       run logging commands,
#    }

# 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`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

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

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

# Restart ourselves nicely in perl
exec nice -n 10 $ZEUSHOME/perl/miniperl -wx $0 ${1+"$@"}

#!perl -w
#line 38

my $zeushome;

my ($log_homedir, $log_current, $log_historic);
my $run_count;
my $last_archive;
my $test_run;
my $verbose;
my $system_os;
my $system_platform;
my $datestamp;

# Archiving parameters that are all read from config settings in readConfig
my $log_interval;  # here for completeness/debugging.
my $logging_enabled;
my $archive_every;
my $archive_on_size; # measured in Mbytes
my $max_tar_files;
my $max_tar_size; # measured in MBytes

BEGIN { 
   unshift @INC, "$ENV{ZEUSHOME}/zxtm/lib/perl", 
                 "$ENV{ZEUSHOME}/zxtmadmin/lib/perl", 
                 "$ENV{ZEUSHOME}/perl" ;

   # Set up log directories.
   $zeushome = $ENV{ZEUSHOME};
   $log_homedir = "$zeushome/log/periodic-logs";
   $log_current = "$log_homedir/current";
   $log_historic = "$log_homedir/historic";

   # set environment variable for logging programs to use.
   $ENV{LOGCURRENT} = $log_current;

   mkdir($log_homedir);
   mkdir($log_current);
   mkdir($log_historic);
}
use strict;


use POSIX qw(ULONG_MAX);
use Zeus::Execute qw( execute );
use Zeus::ZXTM::ApplianceUtils qw( isAppliance hasApplianceFeature CalculateSupportID );

# Setting $| to non zero will force a flush after every write:
#   http://perldoc.perl.org/perlvar.html
$| = 1;

sub findProgram($);
sub usage($);
sub readconfig();
sub updateState();
sub is_uint($);

sub initialise()
{
   my $argNum = 0;
   my $numArgs = scalar( @ARGV );

   chomp($system_os = `uname`);
   chomp($datestamp = "Periodic-Log: local date: " . `date`);
   $system_platform = "";

   while( $argNum < $numArgs ) {
      my $arg = $ARGV[$argNum];
      if( $arg eq "--platform" ) {
         $argNum++;
         $system_platform = $ARGV[$argNum]//"";
      } elsif( $arg eq "--verbose" ) {
         $verbose = 1;
      } elsif( $arg eq "--testrun" ) {
         $test_run = 1;
         $verbose = 1;
      } elsif( $arg eq "--help" ) {
         usage(0);
         exit(0);
      } else {
         usage(1);
         exit(1);
      }
      $argNum++;
   }
   readConfig();
   
   if( $verbose ) {
      print( "Run on $system_os : $system_platform\n");
      print( "  ZeusHome        $zeushome\n" );
      print( "  Testrun         ". ($test_run?"Yes\n":"No\n"));
      print( "  logging_enabled ". ($logging_enabled?"Yes\n":"No\n"));
      print( "  log interval    $log_interval seconds\n");
      print( "  archive_every   $archive_every\n");
      print( "  archive_on_size $archive_on_size MBs\n");
      print( "  max_tar_files   $max_tar_files\n");
      print( "  max_tar_size    $max_tar_size MBs\n\n");
   }
}

sub is_uint($)
{
   my ($int) = @_;
   if( defined($int) ) {
      return ($int =~ /^[+]?\d+$/);
   }
   return 0;
}

sub readConfigNumber($$$)
{
   my ($conf,$name,$default) = @_;
   my $param = $conf->get('periodic_log!'.$name);
   return is_uint($param)?$param:$default;
}

sub readConfig() 
{
   my $storage = new Zeus::ZXTM::StorageManager( );
   my $conf = $storage->getSettingsConfig();
   my $param;

   if( $param = $conf->get("periodic_log!enabled") ) {
      $logging_enabled = ($param =~ /Yes/i);
   }

   $log_interval = readConfigNumber( $conf, "interval", 600 );
   $archive_every = readConfigNumber( $conf, "run_count", 180 );
   $archive_on_size = readConfigNumber( $conf, "max_log_set_size", 1 );
   $max_tar_files = readConfigNumber( $conf, "max_num_archives", 14 );
   $max_tar_size = readConfigNumber( $conf, "max_archive_set_size", 10 );
}

sub readState()
{
   my $state_file = $log_homedir . "/periodic-log-state";
   $run_count = $run_count = undef;
   if( open (MYFILE, $state_file) ) {
      foreach my $line (<MYFILE>) {
         if( $line =~ /runcount\s+(\d+)/ ) {
            $run_count = $1;
            last if( defined($last_archive) );
         }elsif( $line =~ /last_archive\s+(\d+)/ ) {
            $last_archive = $1;
            last if( defined($run_count) );
         }
      }
      close( MYFILE );
   }
   $run_count = $run_count // 0;
   $last_archive = $last_archive// 0;

   $run_count += 1;
   if($verbose) {
      print("$0: Read state file $state_file\n" .
            "  run_count $run_count\n" .
            "  os $system_os Platform $system_platform\n\n");
   }
}

sub updateState()
{
   my $state_file = $log_homedir . "/periodic-log-state";
   if( !$test_run ) {
      if( open (MYFILE, ">$state_file") ) {
         print( MYFILE "runcount $run_count\n");
         print( MYFILE "last_archive $last_archive\n\n");

         print( MYFILE "Last actual run was on $system_os : $system_platform\n");
         print( MYFILE "Settings used:\n");
         print( MYFILE "  ZeusHome        $zeushome\n" );
         print( MYFILE "  log interval    $log_interval seconds\n");
         print( MYFILE "  archive_every   $archive_every runs\n");
         print( MYFILE "  archive_on_size $archive_on_size MBs\n");
         print( MYFILE "  max_tar_files   $max_tar_files\n");
         print( MYFILE "  max_tar_size    $max_tar_size MBs\n\n");
         close (MYFILE); 
      }
   }
}


sub usage($) {
   my $errout = shift;
   my $help = <<EOM;
$0 [--help] [--platform p] [--testrun] [--verbose]
   Log performance stats and cull files which are too old.
   
   --help:     Displays this help and exits.
   --verbose:  Prints activity messages.
   --testrun:  Considers what logging to run and what to archive,
               or delete but does nothing. 
               The verbose is automatically set to be true for test runs.
   --platform: Sets which virtualisation platform (if any) the script
               should consider itself to be running on.

EOM
   if( $errout ){
      print STDERR $help;
   } else {
      print $help;
   }
}

sub writeDefaultConfigFile($)
{
   my ($configfilename) = @_;
   if( $verbose ) {
      print("Creating default config file: $configfilename\n");
   }
   if( $test_run ) {
      return;
   }

   if( open (MYFILE, ">$configfilename") ) {
      print MYFILE <<EOF;
# Periodic Logging Configuration File
#
# Frequency, OS, Platform, logname, command, arguments 
#   A frequency of 1 means run every time logging occurs. 
#   A frequence of 2 means run every other time logging occurs 
# The frequency, OS, Platform fields may be left blank,
# values defaulting to 1,All,All 
#
# The environment variable LOGCURRENT is defined for executed commands
# so may be used as in a command's parameters.
#
# A leading # indicates a comment line.
#
# Examples:
#
# 1,  All,   All,     sockstat, cat, "/proc/net/sockstat" 
# 1,  SunOS, All,     prstat,   prstat, -a 0 1 
# 1,  Linux, HyperV,  lsmod,    lsmod, 
#,,,df,df, -h 

1,  Linux, All, sockstat, cat, "/proc/net/sockstat" 
1,  All,   All, netstat,  netstat, -s 
1,  SunOS, All, ps,       ps, -Alfj 
1,  Linux, All, ps,       ps, auwxx 
1,  All,   All, top,      top, -bn 1 
1,  All,   All, df,       df, -h 
1,  SunOS, All, prstat,   prstat, -a 0 1 
1,  Linux, All, sadc-log, /usr/lib/sysstat/sadc, -L -S XALL -F "\$LOGCURRENT/sadc-data" 1 1

EOF
   close(MYFILE);
      if( $verbose ) {
         print("Wrote config file: $configfilename\n");
      }
   } else {
      if( $verbose ) {
         print("Failed to write $configfilename: $!\n");
      }
   }

}

sub processConfig()
{
   my $configfile = "$ENV{ZEUSHOME}/zxtm/conf/periodic-log-config";
   if( ! -f $configfile ) {
      writeDefaultConfigFile($configfile);
   }
   if( $verbose ) {
      print("Processing file $configfile\n");
   }

   if( open (MYFILE, $configfile) ) {
      my $linenum=0;
      foreach my $line (<MYFILE>) {
         $linenum++;
         chomp($line);
         if( ($line) && ($line !~ /^\s*#/ )) {
            my @params = split('\s*,\s*', $line, 6);
            
            if( scalar(@params) >=5 ) {
               my $freq = $params[0];
               my $os = $params[1];
               my $pf = $params[2];
               my $logname = $params[3];
               my $command = $params[4];
               # remember in perl '//' is the Null coalescing operator.
               my $arguments = $params[5]//"";
               
               $freq = 1 if (!is_uint($freq));
               if(   
                   ( ( $freq<2) ||(0 == ($run_count % $freq)) )&&
                   ( (!$pf) || ($pf eq "All") || ($system_platform =~ $pf) ) &&
                   ( (!$os) || ($os eq "All") || ($os eq $system_os) )
                 ) {
                  if( $verbose ) {
                     printf("*Running line $linenum: %-2d:%-6s:%-10s:%-10s:%-10s:%s\n", 
                           $freq, $os, $pf, $logname, $command, $arguments);
                  }
                  logCommand($logname,$command,$arguments);
               } else {
                  if($verbose) {
                     printf("Ignoring line $linenum: %-2d:%-6s:%-10s:%-10s:%-10s:%s\n", 
                           $freq, $os, $pf, $logname, $command, $arguments);
                  }
               }
            } elsif($verbose){
               print("Unable to parse line $linenum: $line\n");
            }
         }
      }
      close( MYFILE );
   }
}

# Returns the full path to an executable file.
# We check either the absolute path or our exec path.
# If an executable file is not found, it returns undef
sub findProgram($)
{
   my( $prog ) = @_;

   if( $prog =~ /^\// ) {
      return ( -x $prog )?$prog:undef;
   }

   my @exec_path = split( /:+/, $ENV{PATH} );
   push( @exec_path , "$zeushome/zxtm/bin" );
   foreach my $item( @exec_path ) {
      my $path = "$item/$prog";
      if( -x $path ) {
         return $path
      }
   }
   if( $verbose ) {
      print( "Unable to find $prog in @exec_path\n" );
   }
   return undef;
}

sub logCommand($$$)
{
   my( $file, $command,$argstring) = @_;
   $command = findProgram($command);

   if( $file && $command && (!$test_run)) {
      my $filename = "$log_current/$file";
      if( open( LOG, ">>$filename" )) {
         print( LOG "$datestamp\n" );
         close( LOG );
         $command = "$command $argstring >>\"$filename\" 2>&1";
         my ( $exit, $stdout, $stderr ) = execute( $command );

         # If the command returns non zero, then record that
         if( $exit && open( LOG, ">>$filename" )) {
            print( LOG "Return code of $exit from command: $command\n");
            close( LOG );
         }
      }
   }
}

# Append a comment to a file.
sub appendComment($$)
{
   my( $file, $line ) = @_;
   my $filename = "$log_current/$file";
   if( open( LOG, ">>$filename" )) {
      print LOG "$line";
      close( LOG );
   }
}

sub getDiskUsageKB($)
{
   my ($directory) = @_;
   my $du = findProgram("du");
   if( $du && $directory ) {
      # get usage in KB not MB because du rounds up.
      my $du_command = "$du -ks \"$directory\"";
      my ( $exit, $stdout, $stderr ) = execute( $du_command );
      # get first integer number or if undefined, zero.
      my ($kbytesused) = ($stdout =~ /(\d+)/)?$1:0;
      return ($kbytesused);
   }
   return 0;
}

sub moveCurrentToHistoric()
{
   my $do_tar = ( $run_count-$last_archive > $archive_every);
   if( (!$do_tar) && $archive_on_size ) {
      #check we haven't used up too much disk space.
      my $logsetsize = getDiskUsageKB($log_current);
      if( $verbose ) {
         print("Log set size = $logsetsize KBytes\n");
      }
      $do_tar = ($logsetsize/1024)>$archive_on_size;
      if( $do_tar) {
         appendComment("log-record",
            "Archiving current log set (size = $logsetsize KBytes)\n");

         if( $verbose ) {
            print("Archiving current log set\n");
         }
      }
   }

   if( $do_tar ) {
      my $tar = findProgram("tar");
      my $gzip = findProgram("gzip");
      if($tar) {
         my ($sec,$min,$hour,$mday,$mon,$year) = localtime(time);
         $year+= 1900;
         $mon += 1;

         my $logname = sprintf("log_%4d_%02d_%02d_%02d_%02d_%02d",
                              $year,$mon,$mday,$hour,$min,$sec);

         my $tarball = "$log_historic/$logname\.tar";
         my $tarcommand;
         if( $gzip ) {
            $tarball .= '.gz';
            $tarcommand = "$tar -cf - -C \"$log_current/\" \. " . 
                          "| $gzip -c > \"$tarball\"";
         } else {
            $tarcommand = "$tar -cf \"$tarball\" -C \"$log_current/\" \.";
         }
         if($verbose) {
            print("Archiving current logs to $log_historic:  $tarcommand\n");
         }

         if( ! $test_run ) {
            my ( $exit, $stdout, $stderr ) = execute( $tarcommand );
            if( !$exit ) {
               my $cleancommand = "rm \"$log_current/\"\*";
               $last_archive = $run_count;
               my ( $exit, $stdout, $stderr ) = execute( $cleancommand );
               my $cleanMessage;
               if( $exit ) {
                  $cleanMessage = "Clean up failed: $exit\n  $cleancommand\n" .
                           "  $stdout\n  $stderr\n";
                  appendComment("log-record",$cleanMessage);
               } else {
                  $cleanMessage = "Clean up succeeded with $cleancommand\n";
               }
               if($verbose) {
                  print( $cleanMessage );
               }
            } else {
               my $error = "Tar failed! $exit:\n  stdout: $stdout\n  stderr $stderr\n";
               appendComment("log-record",$error);
               if( $verbose ) {
                  print( $error );
               }
            }
         }
      }
   }
}

sub deleteOldestHistoricFiles()
{
   my $dir;

   if(opendir($dir,$log_historic)) {
      my @files = readdir($dir);
      my $time_now = time();
      my %filehash = ();
      my $totalSize = 0;
      my $fileCount = 0;
      foreach my $file (@files) {
         if( ($file ne ".") && ($file ne "..") ) {
            my $fullpathname = "$log_historic/$file";
            my @filestats = stat("$fullpathname");

            #  8th element is file size:
            # 10th element is last modification time:
            # see : http://perldoc.perl.org/functions/stat.html
            my $file_age = $time_now - $filestats[9];
            $totalSize += $filestats[7];
            $filehash{ $file_age } = [$fullpathname,$filestats[7]];
            $fileCount++;
         }
      }
      closedir $dir;
      if($verbose) {
         print( "Files in $log_historic\n");
         foreach my $key (sort { $b <=> $a} keys %filehash) {
            my $file = $filehash{$key}[0];
            my $size = $filehash{$key}[1];

            printf("Age %10d : Size %10d : path %s\n",$key, $size, $file);
         }
         printf("Total %10d\n",$totalSize);
      }

      # Delete oldest files if we've got at least two files AND
      # we've exceeded the allowable count or disk usage.
      my $maxbytes = $max_tar_size?$max_tar_size*1024*1024:ULONG_MAX;

      if( ( $fileCount > 1) &&
            (
            ($fileCount > $max_tar_files) || 
            ($totalSize > $maxbytes) 
            )
        ) {
         foreach my $key (sort { $b <=> $a} keys %filehash) {
            my $file = $filehash{$key}[0];
            my $size = $filehash{$key}[1];

            if( !$test_run ) {
               unlink($file);
            }
            $fileCount--;
            $totalSize -= $size;
            if($verbose) {
               print("Deleting $file\n");
            }
            last if( $fileCount == 1 );
            last if( ($fileCount <= $max_tar_files)&&($totalSize<$maxbytes) );
         }
      }
      if($verbose) {
         print( "\n");
      }
   }
}

sub updateHistoricRecords()
{
   moveCurrentToHistoric();
   deleteOldestHistoricFiles();
}

# Main code.
initialise();
if($logging_enabled) {
   appendComment("log-record","Starting log:$datestamp\n");
   readState();
   updateHistoricRecords();
   updateState();
   processConfig();
   appendComment("log-record","Completing log:$datestamp\n");
}
