#!/usr/bin/perl

# Pragma
use strict;
use warnings;

BEGIN
{
    if ( !defined $ENV{'GEXTPARALLELBUILDING_INSTALLED'}) {
	die "GEXTPARALLELBUILDING_INSTALLED not set\n";
    }
    # Installed CPAN packages for GEXT*INSTALL
    my $perl_version = `perl-version.pl`;
    my $perl_path = sprintf("%s/lib/perl/%s", $ENV{'GEXTPARALLELBUILDING_INSTALLED'}, $perl_version);
    unshift (@INC, $perl_path);
}

# Modules
use Sort::Naturally;
use POSIX qw(floor strftime);

print "\n===== Generate Timing (GANTT) =====\n";

# 0. Init
# - configurables
my $chart_width = 1600;
# - any video more than 95% complete is probably complete with rounding errors
my $complete_threshold = 95;

my $debug = 0;
my $color_master = 'blue';
my $color_worker = 'green';
my $color_nlocal = 'red';
my $disable_header = 0;
my $max_worker_count = 0;
# - globals
my $chart_count = 0;
my @months = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

# 1. Parse options
while (defined $ARGV[0] && $ARGV[0] =~ /^-/)
{
  my $option = shift(@ARGV);
  if ($option eq '-debug')
  {
    $debug = 1;
  }
  elsif ($option eq '-width')
  {
    if (!defined $ARGV[0])
    {
      &printUsage('Error! No width value specified');
    }
    my $value = shift(@ARGV);
    if ($value !~ /^\d+$/)
    {
      &printUsage('Error! Chart width not a number');
    }
    $chart_width = $value;
  }
  elsif ($option eq '-grayscale')
  {
    $color_master = '#1D1D1D';
    $color_worker = '#969696';
    $color_nlocal = '#4C4C4C';
  }
  elsif ($option eq '-noheader')
  {
    $disable_header = 1;
  }
  elsif ($option eq '-maxworkers')
  {
    if (!defined $ARGV[0])
    {
      &printUsage('Error! No maxworkers value specified');
    }
    my $value = shift(@ARGV);
    if ($value !~ /^\d+$/)
    {
      &printUsage('Error! Maxworkers not a number');
    }
    $max_worker_count = $value;
  }
  else
  {
    &printUsage('Error! Unknown option: ' . $option);
  }
}
print "Chart Width: " . $chart_width . "px\n";
print "Grayscale? " . ($debug ? 'Yes' : 'No') . "\n";
print "Debug? " . ($debug ? 'Yes' : 'No') . "\n";
print "===================================\n\n";

# 2. Search for valid directories (containing timing.csv)
while (defined $ARGV[0])
{
  my $dir = shift(@ARGV);
  if (!-d $dir)
  {
    &printUsage('Error! Not a directory: ' . $dir);
  }
  if ($dir =~ /(.*)[\\\/]$/)
  {
    $dir = $1;
  }
  &searchForTimingCSV($dir);
}

# 3. Done
print "Complete!\n\n";
print "===================================\n";
print 'Generated ' . $chart_count . " charts\n";
print "===================================\n\n";
exit;
## main() ##


## @function searchForTimingCSV()
#
sub searchForTimingCSV
{
  my $dir = shift(@_);
  # For every directory where we find a timing.csv we generate a gantt chart
  my $timing_path = &filenameCat($dir, 'timing.csv');
  if (-e $timing_path)
  {
    &generateChart($dir, $timing_path);
  }
  # We also recursively search for other directories containing timing.csv's
  opendir(my $dh, $dir) or &printError('Failed to open directory for reading: ' . $dir);
  my @files = readdir($dh);
  foreach my $file (@files)
  {
    if ($file !~ /^\./)
    {
      my $path = &filenameCat($dir, $file);
      if (-d $path)
      {
        &searchForTimingCSV($path);
      }
    }
  }
}
## searchForTimingCSV() ##


## @function generateChart()
#
sub generateChart
{
  my $dir = shift(@_);
  my $timing_csv_path = shift(@_);
  my $import_dir;
  my ($epoc) = $dir =~ /(\d+)$/;
  my $gantt_path = $dir . '/' . $epoc . '-gantt.html';

  print ' * Generating chart for: ' . $dir . "\n";
  print ' - timing file: ' . $timing_csv_path . "\n";
  print ' - gantt chart: ' . $gantt_path . "\n";

  # Read in timing.csv and parse information into data structure
  print ' - parsing timing.csv... ';
  my $timing_data = {};
  my $id_2_worker_id = {};
  if (open(TIN, '<:utf8', $timing_csv_path))
  {
    my $line;
    while ($line = <TIN>)
    {
      my @parts = split(/,/, $line);
      if ($parts[1] eq 'M0')
      {
        $timing_data->{'M'} = {'N'=>$parts[2], 'S'=>$parts[3], 'E'=>$parts[4]};
      }
      elsif ($parts[1] =~ /W\d+/)
      {
        my $worker_id = $parts[1];
        my $hostname = $parts[2];
        # Alter the worker name for compute nodes so they can be naturally
        # sorted
        if ($hostname =~ /compute-0-(\d+)/)
        {
          $worker_id = 'W' . $1;
        }
        $timing_data->{$worker_id} = {'N'=>$hostname, 'S'=>$parts[3], 'E'=>$parts[4], 'F'=>{}};
        $id_2_worker_id->{$parts[0]} = $worker_id;
      }
      elsif ($parts[1] =~ /T\d+/)
      {
        my $worker_id = $id_2_worker_id->{$parts[7]};
        my $stop = $parts[4];
        my $filepath = $parts[8];
        $filepath =~ s/^\s+|\s+$//g;
        my $percent_complete = 'NA';
        if (defined($parts[9]))
        {
          $percent_complete = $parts[9];
          chomp($percent_complete);
          if ($percent_complete >= $complete_threshold)
          {
            $percent_complete = 'NA';
          }
        }
        $import_dir = &longestCommonPath($filepath, $import_dir);
        my $start_time = $parts[3];
        while (defined $timing_data->{$worker_id}->{'F'}->{$start_time})
        {
          $start_time += 0.000001;
        }
        $timing_data->{$worker_id}->{'F'}->{$start_time} = {'FN'=>$filepath, 'S'=>$parts[3], 'PS'=>($stop - $parts[5]), 'PE'=>$stop, 'E'=>$stop, 'DL'=>$parts[6], 'PC'=>$percent_complete};
      }
    }
    close(TIN);
  }
  else
  {
    die('Error! Failed to open file for reading: ' . $timing_csv_path);
  }
  my $number_of_workers = scalar(keys(%{$id_2_worker_id}));;
  print "Done\n";

  # 3. Produce pretty HTML chart of timing information including jobs
  print " - generating timing information as chart in HTML... ";
  open(HTMLOUT, '>:utf8', $gantt_path) or die('Error! Failed to open file for writing: gantt.html');
  print HTMLOUT "<html>\n";
  print HTMLOUT '<head>' . "\n";
  print HTMLOUT '<style type="text/css">' . "\n";
  print HTMLOUT "body {margin:0px;padding:4px}\n";
  print HTMLOUT 'div.thread {position:relative}' . "\n";
  print HTMLOUT 'div.master {border:1px solid gray;color:white;font-weight:bold}' . "\n";
  print HTMLOUT 'div.worker {border:1px solid black;background-color:' . $color_worker . ';color:white;font-weight:bold;margin-bottom:1px;}' . "\n";
  print HTMLOUT 'div.time {font-size:smaller;font-weight:normal}' . "\n";
  print HTMLOUT 'div.job {background-color:transparent;color:black;border:1px solid black;display:block;font-size:smaller;font-weight:normal;position:relative;text-align:left;margin-bottom:1px;}' . "\n";
  print HTMLOUT 'span.process {z-index:-1;background-color:#C7C7C7;position:absolute}' . "\n";
  print HTMLOUT 'div.label {z-index:1;background-color:transparent;white-space:nowrap;text-align:center}' . "\n";
  print HTMLOUT "th {text-align:left}\n";
  print HTMLOUT "tr.toprule th,tr.toprule td {border-top:2px solid black;width:17%}\n";
  print HTMLOUT "tr.bottomrule th,tr.bottomrule td {border-bottom:2px solid black}\n";
  print HTMLOUT '</style>' . "\n";
  print HTMLOUT '</head>' . "\n";
  print HTMLOUT "<body>\n";
  ##print HTMLOUT "<h2>Parallel Import Timing Chart</h2>\n";
  print HTMLOUT "<table style=\"border-collapse:collapse;width:" . $chart_width . "px;";
  if ($disable_header)
  {
    print HTMLOUT "display:none;";
  }
  print HTMLOUT "\">\n";

  my $total_duration = $timing_data->{'M'}->{'E'} - $timing_data->{'M'}->{'S'};
  my $file_count = 0;
  my $data_locality = 0;
  my $total_io_time = 0;
  my $total_process_time = 0;
  my $fastest_file = 0;
  my $slowest_file = 0;
  my $problem_files = 0;
  foreach my $worker_id (keys %{$timing_data})
  {
    if ($worker_id ne 'M')
    {
      foreach my $job_start ( keys %{$timing_data->{$worker_id}->{'F'}} )
      {
        my $process_start = $timing_data->{$worker_id}->{'F'}->{$job_start}->{'PS'};
        my $process_end = $timing_data->{$worker_id}->{'F'}->{$job_start}->{'PE'};
        my $job_end = $timing_data->{$worker_id}->{'F'}->{$job_start}->{'E'};
        my $percent_complete = $timing_data->{$worker_id}->{'F'}->{$job_start}->{'PC'};
        if ($process_start == 0 || $process_end == 0 || $job_end == 0 || ($percent_complete =~ /^\d+$/ && $percent_complete < $complete_threshold))
        {
          $problem_files++;
        }
        else
        {
          my $io_duration = ($process_start - $job_start) + ($job_end - $process_end);
          my $process_duration = $process_end - $process_start;
          my $total_duration = $io_duration + $process_duration;
          &debugPrint("filename: " . $timing_data->{$worker_id}->{'F'}->{$job_start}->{'FN'});
          &debugPrint("start: $job_start ps: $process_start pe: $process_end end: $job_end");
          &debugPrint("io: $io_duration process: $process_duration duration: $total_duration");
          # Running stats
          $total_io_time += $io_duration;
          $total_process_time += $process_duration;
          if ($fastest_file == 0 || $total_duration < $fastest_file)
          {
            $fastest_file = $total_duration;
          }
          if ($slowest_file == 0 || $total_duration > $slowest_file)
          {
            $slowest_file = $total_duration;
          }
        }
        # Shorten filename
        if (defined $timing_data->{$worker_id}->{'F'}->{$job_start}->{'FN'} && $timing_data->{$worker_id}->{'F'}->{$job_start}->{'FN'} ne '')
        {
          $timing_data->{$worker_id}->{'F'}->{$job_start}->{'FN'} = substr($timing_data->{$worker_id}->{'F'}->{$job_start}->{'FN'}, length($import_dir) + 1);
        }
        $file_count++;
        if ($timing_data->{$worker_id}->{'F'}->{$job_start}->{'DL'} == 1)
        {
          $data_locality++;
        }
      }
    }
  }
  if ($file_count <= 0)
  {
    $file_count = 1;
  }
  if ($total_process_time <= 0)
  {
    $total_process_time = 1;
  }
  my $avg_processing_time = floor(($total_io_time + $total_process_time) / $file_count);
  my $avg_io_time = int(($total_io_time / $file_count) + 0.5);
  my $avg_cpu_time = int(($total_process_time / $file_count) + 0.5);

  print HTMLOUT "<tr class=\"toprule\">\n";
  print HTMLOUT ' <th style="width:17%;">Import Directory:</th><td style="width:83%;" colspan="5">' . $import_dir . "</td>\n";
  print HTMLOUT "</tr>\n";

  print HTMLOUT "<tr>\n";
  my ($sec, $min, $hour, $day, $month, $year) = (localtime($timing_data->{'M'}->{'S'}))[0,1,2,3,4,5];
  print HTMLOUT ' <th>Start Time:</th><td>' . sprintf('%04d%s%02d %02d:%02d:%02d', ($year+1900), $months[$month], $day, $hour, $min, $sec) . "</td>\n";
  ($sec, $min, $hour, $day, $month, $year) = (localtime($timing_data->{'M'}->{'E'}))[0,1,2,3,4,5];
  print HTMLOUT ' <th>End Time:</th><td>' . sprintf('%04d%s%02d %02d:%02d:%02d', ($year+1900), $months[$month], $day, $hour, $min, $sec) . "</td>\n";
  print HTMLOUT "  <th>Processing Time:</th><td>" . &renderTime($total_duration) . "</td>\n";
  print HTMLOUT "</tr>\n";

  print HTMLOUT "<tr>\n";
  print HTMLOUT "  <th>Processing Threads:</th><td>" . $number_of_workers . "</td>\n";
  print HTMLOUT "  <th>Files Processed:</th><td>" . $file_count . "</td>\n";
  print HTMLOUT "  <th>Problem Files:</th><td>" . $problem_files . "</td>\n";
  print HTMLOUT "</tr>\n";

  print HTMLOUT "<tr>\n";
  print HTMLOUT '  <th>Serial Processing Time:</th><td>' . &renderTime($total_process_time) . "</td>\n";
  print HTMLOUT '  <th>Serial IO Time:</th><td>' . &renderTime($total_io_time) . "</td>\n";
  print HTMLOUT '  <th>IO Percentage:</th><td>' . sprintf('%d%%', (($total_io_time / $total_process_time) * 100)) . "</td>\n";
  print HTMLOUT "</tr>\n";

  print HTMLOUT "<tr>\n";
  print HTMLOUT "  <th>Avg Processing Time:</th><td>" . &renderTime($avg_processing_time) . "</td>\n";
  print HTMLOUT "  <th>Avg File IO Time:</th><td>" . &renderTime($avg_io_time) . "</td>\n";
  print HTMLOUT "  <th>Avg File CPU Time:</th><td>" . &renderTime($avg_cpu_time) . "</td>\n";
  print HTMLOUT "</tr>\n";

  print HTMLOUT "<tr class=\"bottomrule\">\n";
  print HTMLOUT "  <th>Fastest File:</th><td>" . &renderTime($fastest_file) . "</td>\n";
  print HTMLOUT "  <th>Slowest File:</th><td>" . &renderTime($slowest_file) . "</td>\n";
  #if ($data_locality > 0)
  #{
    print HTMLOUT "  <th>Data Locality:</th><td>" . sprintf('%d%% [%d out of %d]', (($data_locality / $file_count) * 100), $data_locality, $file_count) . "</td>\n";
  #}
  #else
  #{
  #  print HTMLOUT "  <th>Data Locality:</th><td><i>Not Applicable</i></td>\n";
  #}
  print HTMLOUT "</tr>\n";

  print HTMLOUT "</table>\n";
  print HTMLOUT renderLine($chart_width, $timing_data->{'M'}->{'S'}, $timing_data->{'M'}->{'E'}, 'master', $timing_data->{'M'}->{'N'}, $timing_data->{'M'}->{'S'}, $timing_data->{'M'}->{'E'}, {}, $data_locality);
  my $worker_count = 0;
  foreach my $worker_id (nsort keys %{$timing_data})
  {
    if ($max_worker_count < 1 || $worker_count <= $max_worker_count)
    {
      if ($worker_id ne 'M')
      {
        my $data = $timing_data->{$worker_id};
        print HTMLOUT renderLine($chart_width, $timing_data->{'M'}->{'S'}, $timing_data->{'M'}->{'E'}, 'worker', $worker_id . ' [' . $data->{'N'} . ']', $data->{'S'}, $data->{'E'}, $data->{'F'}, 2); #$data_locality);
        $worker_count++;
      }
    }
  }
  print HTMLOUT '</div>' . "\n";
  print HTMLOUT "</body>\n";
  print HTMLOUT "</html>";
  close(HTMLOUT);
  print "Done!\n\n";
  $chart_count++;
}
## generateChart() ##


## @function debugPrint()
#
sub debugPrint
{
  my $msg = shift(@_);
  if ($debug)
  {
    print STDERR '[DEBUG] ' . $msg . "\n";
  }
}
## debugPrint() ##


## @function filenameCat
#
sub filenameCat
{
  my $path = join('/', @_);
  $path =~ s/[\/\\]+/\//g;
  return $path;
}
## filenameCat() ##


## @function printError()
#
sub printError
{
  my $msg = shift(@_);
  die('Error! ' . $msg . "\n\n");
}
## printError() ##


## @function printUsage()
#
sub printUsage
{
  my $msg = shift(@_);
  if (defined $msg)
  {
    print 'Error! ' . $msg . "\n";
  }
  die("Usage: generate_gantt.pl [-width <width in pixels>] <dir> [<dir> ...]\n\n");
}
## printUsage() ##


## @function longestCommonPath
#
sub longestCommonPath
{
  my ($path_new, $path_current) = @_;
  my $result = '';
  if (defined $path_current)
  {
    # Hide protocol before we split by slash
    $path_new =~ s/:\/\//:/;
    $path_current =~ s/:\/\//:/;
    my @path_new_parts = split(/\//, $path_new);
    my @path_current_parts = split(/\//, $path_current);
    my @path_parts;
    for (my $i = 0; $i < scalar(@path_current_parts); $i++)
    {
      if ($path_current_parts[$i] eq $path_new_parts[$i])
      {
        push(@path_parts, $path_new_parts[$i]);
      }
      else
      {
        last;
      }
    }
    $result = &filenameCat(@path_parts);
    # Restore protocol
    $result =~ s/:/:\/\//;
  }
  else
  {
    $result = $path_new;
  }
  return $result;
}
## longestCommonPath() ##


## @function renderLine()
#
sub renderLine
{
  my ($table_width, $start, $end, $class, $tname, $tstart, $tend, $jobs, $data_locality) = @_;
  &debugPrint("renderLine($table_width, $start, $end, $class, $tname, $tstart, $tend, <jobs>, $data_locality)");
  # All timings need to be relative to 0 (relative start)
  my $duration = $end - $start;
  my $rtstart = $tstart - $start;
  my $rtend = $tend - $start;
  # We need to scale these depending on the timing of this thread relative to
  # the master thread
  my $width = $chart_width;
  my $left = 0;
  if ($start != $tstart)
  {
    my $left_offset_percent = $rtstart / $duration;
    $left = $left_offset_percent * $table_width;
  }
  # - subtract any left offset from width
  $width = $width - $left;
  # - right offset directly subtracted from width
  if ($end != $tend)
  {
    my $right_offset_percent = ($duration - $rtend) / $duration;
    my $right = $right_offset_percent * $table_width;
    $width = $width - $right;
  }
  # Round things off (simple dutch rounding)
  $left = int($left + 0.5);
  $width = int($width + 0.5);
  # Output the bar for this master/worker
  my $html = '<div class="thread ' . $class . '" style="left:' . $left . 'px;width:' . $width . 'px;">';
  if ($class eq 'master')
  {
    $html .= '<div style="background-color:' . $color_master . ';margin-bottom:1px">';
  }
  $html .= '<div class="time" style="display:table-cell">' . &renderTime($rtstart) . '</div><div style="display:table-cell;padding-left:20px;width:100%;">' . ucfirst($class) . ': ' . $tname . '</div><div class="time" style="display:table-cell">' . renderTime($rtend) . '</div></div>';
  my $previous_jright = 0;
  foreach my $jstart (sort keys %{$jobs})
  {
    my $rjstart = $jstart - $start;
    my $rpstart = $jobs->{$jstart}->{'PS'} - $start;
    my $rpend = $jobs->{$jstart}->{'PE'} - $start;
    my $rjend = $jobs->{$jstart}->{'E'} - $start;
    my $jduration = $jobs->{$jstart}->{'E'} - $jstart;
    my $io_duration = $rpstart - $rjstart;
    my $cpu_duration = $rpend - $rpstart;
    # Scale Job co-ordinates
    my $jleft_percent = $rjstart / $duration;
    my $jleft = int(($jleft_percent * $table_width) + 0.5);
    my $jwidth_percent = $jduration / $duration;
    # -2 for left and right 1 pixel border
    my $jwidth = int(($jwidth_percent * $table_width) + 0.5) - 2;
    if ($jleft + $jwidth > $left + $width)
    {
      $jwidth = ($left + $width) - $jleft;
    }
    # Then scale process timings within that!
    my $rpleft_percent = ($rpstart - $rjstart) / $duration;
    my $rpleft = int(($rpleft_percent * $table_width) + 0.5);
    my $rpwidth = $jwidth - $rpleft;
    my $cpu_percent = int((($rpwidth / $jwidth) * 100) + 0.5);
    $html .= '<div class="job" style="left:' . $jleft . 'px;width:' . $jwidth . 'px;';
    ###rint "Data Locality? " . $data_locality . " DL? " . $jobs->{$jstart}->{'DL'} . "\n";
    if ($data_locality > 1 && $jobs->{$jstart}->{'DL'} != 1)
    {
      $html .= 'border:1px solid #C7C7C7;';
    }
    $html .= '" title="FN:' . $jobs->{$jstart}->{'FN'} . ', S:' . &renderTime($rjstart) . ', E:' . &renderTime($rjend) . ', CPU: ' . $cpu_percent . '% [' . &renderTime($io_duration) . ', ' . &renderTime($cpu_duration) . ', PC: ' . $jobs->{$jstart}->{'PC'} . '%]"><span class="process" style="left:' . $rpleft . 'px;width:' . $rpwidth . 'px">&nbsp;</span><div class="label" style="width:' . $jwidth;
    if ($data_locality > 1 && $jobs->{$jstart}->{'DL'} != 1)
    {
      $html .= ';color:' . $color_nlocal;
    }
    $html .=  '">' . $jobs->{$jstart}->{'FN'};
    if ($jobs->{$jstart}->{'PC'} ne 'NA')
    {
      $html .= ' <b>[Incomplete! ' . $jobs->{$jstart}->{'PC'} . '%]</b>';
    }
    if ($data_locality > 1 && $jobs->{$jstart}->{'DL'} != 1)
    {
      $html .= ' [NL]';
    }
    $html .= '</div></div>';
  }
  return $html;
}
## renderLine() ##


## @function renderTime()
#
sub renderTime
{
  my ($seconds) = @_;
  my $time_str = '';
  # determine how many hours
  my $an_hour = 60 * 60;
  my $hours = floor($seconds / $an_hour);
  $seconds = $seconds - ($hours * $an_hour);
  my $a_minute = 60;
  my $minutes = floor($seconds / $a_minute);
  $seconds = $seconds - ($minutes * $a_minute);
  if ($hours > 0)
  {
    $time_str = sprintf('%dh%02dm%02ds', $hours, $minutes, $seconds);
  }
  else
  {
    $time_str = sprintf('%dm%02ds', $minutes, $seconds);
  }
  return $time_str;
}
