#!/usr/bin/perl

# Pragma
use strict;
use warnings;
use 5.012; # so readdir assigns to $_ in a lone while test

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

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

# 0. Init
# - configurables
my $chart_width = 1600;
my $debug = 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;
  }
  else
  {
    &printUsage('Error! Unknown option: ' . $option);
  }
}
print "Chart Width: " . $chart_width . "px\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);
  }
  &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);
  while (readdir($dh))
  {
    my $file = $_;
    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;
        $import_dir = &longestCommonPath($filepath, $import_dir);
        $timing_data->{$worker_id}->{'F'}->{$parts[3]} = {'FN'=>$filepath, 'S'=>$parts[3], 'PS'=>($stop - $parts[5]), 'PE'=>$stop, 'E'=>$stop, 'DL'=>$parts[6]};
      }
    }
    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 '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:green;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;position:relative;text-align:center;overflow:hidden;margin-bottom:1px;}' . "\n";
  print HTMLOUT 'span.process {z-index:-1;background-color:#C7C7C7;position:absolute}' . "\n";
  print HTMLOUT 'span.label {z-index:1;background-color:transparent;overflow:hidden;white-space:nowrap;}' . "\n";
  print HTMLOUT "th {text-align:left}\n";
  print HTMLOUT '</style>' . "\n";
  print HTMLOUT '</head>' . "\n";
  print HTMLOUT "<body>\n";
  print HTMLOUT "<h2>Statistics</h2>\n";
  print HTMLOUT "<table style=\"width:100%;\">\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'};
        if ($process_start == 0 || $process_end == 0 || $job_end == 0)
        {
          $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'} = 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++;
        }
      }
    }
  }
  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>\n";
  print HTMLOUT ' <th style="width:12%;">Import Directory:</th><td style="width:22%;" 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 style="width:11%;">Start Time:</th><td style="width:22%;">' . 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 style="width:11%;">End Time:</th><td style="width:22%;">' . 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>Average Processing Time:</th><td>" . &renderTime($avg_processing_time) . "</td>\n";
  print HTMLOUT "  <th>Average File IO Time:</th><td>" . &renderTime($avg_io_time) . "</td>\n";
  print HTMLOUT "  <th>Average File CPU Time:</th><td>" . &renderTime($avg_cpu_time) . "</td>\n";
  print HTMLOUT "</tr>\n";

  print HTMLOUT "<tr>\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></th>\n";
    print HTMLOUT "  <td></td>\n";
  }
  print HTMLOUT "</tr>\n";

  print HTMLOUT "</table>\n";
  print HTMLOUT "<hr />\n";
  print HTMLOUT "<h2>Timing Chart (Gantt)</h2>\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'}, {});
  foreach my $worker_id (nsort keys %{$timing_data})
  {
    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'});
    }
  }
  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) = @_;
  &debugPrint("renderLine($table_width, $start, $end, $class, $tname, $tstart, $tend, <jobs>)");
  # 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:blue;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;';
    if ($jobs->{$jstart}->{'DL'} != 1)
    {
      $html .= 'border:1px dashed black;';
    }
    $html .= '" title="FN:' . $jobs->{$jstart}->{'FN'} . ', S:' . &renderTime($rjstart) . ', E:' . &renderTime($rjend) . ', CPU: ' . $cpu_percent . '% [' . &renderTime($io_duration) . ', ' . &renderTime($cpu_duration) . ']"><span class="process" style="left:' . $rpleft . 'px;width:' . $rpwidth . 'px">&nbsp;</span><span class="label"';
    if ($jobs->{$jstart}->{'DL'} != 1)
    {
      $html .= ' style="color:#FF0000"';
    }
    $html .=  '>' . $jobs->{$jstart}->{'FN'};
    if ($jobs->{$jstart}->{'DL'} != 1)
    {
      $html .= ' [NL]';
    }
    $html .= '</span></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;
}
