#!/usr/bin/perl

use strict;
use warnings;

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

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

# 0. Configuration
my $debug = 0;
my $import_dir;

# 1. Initialization
if (!defined $ARGV[0] || !-d $ARGV[0])
{
  &printUsage('Directory not provided or doesn\'t exist');
}
my $dir = $ARGV[0];
my $timing_csv_path = &filenameCat($dir, 'timing.csv');
if (!-e $timing_csv_path)
{
  &printUsage('Directory doesn\'t contain timing.csv: ' . $dir);
}
print 'Timing File: ' . $timing_csv_path . "\n";
my $chart_width = 1024;
if (defined $ARGV[1])
{
  if ($ARGV[1] !~ /^\d+$/)
  {
    &printUsage('Chart width not a number');
  }
  $chart_width = $ARGV[1];
}
print "Chart Width: " . $chart_width . "px\n";

my ($epoc) = $dir =~ /(\d+)$/;
my $gantt_path = $dir . '/' . $epoc . '-gantt.html';
print "Gantt Chart: " . $gantt_path . "\n";

print "===================================\n\n";

# Read in timing.csv and parse information into data structure
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+/)
    {
      $timing_data->{$parts[1]} = {'N'=>$parts[2], 'S'=>$parts[3], 'E'=>$parts[4], 'F'=>{}};
      $id_2_worker_id->{$parts[0]} = $parts[1];
    }
    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, '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}));;

# 3. Produce pretty HTML chart of timing information including jobs
print " * Generating timing information as 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}' . "\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}' . "\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>\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 @months = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

print HTMLOUT "<tr><th>Import Directory:</th><td>" . $import_dir . "</td></tr>\n";
my ($sec, $min, $hour, $day, $month, $year) = (localtime($timing_data->{'M'}->{'S'}))[0,1,2,3,4,5];
print HTMLOUT "<tr><th>Start Time:</th><td>" . sprintf('%04d%s%02d %02d:%02d:%02d', ($year+1900), $months[$month], $day, $hour, $min, $sec) . "</td></tr>\n";
print HTMLOUT "<tr><th>Processing Time:</th><td>" . &renderTime($total_duration) . "</td></tr>\n";
print HTMLOUT "<tr><th>Processing Threads:</th><td>" . $number_of_workers . "</td></tr>\n";
print HTMLOUT "<tr><th>Files Processed:</th><td>" . $file_count . "</td></tr>\n";
if ($data_locality > 0)
{
  print HTMLOUT "<tr><th>Data Locality:</th><td>" . sprintf('%d%% [%d out of %d]', (($data_locality / $file_count) * 100), $data_locality, $file_count) . "</td></tr>\n";
}
print HTMLOUT "<tr><th>Serial Processing Time:</th><td>" . &renderTime($total_process_time) . "</td></tr>\n";
print HTMLOUT "<tr><th>Serial IO Time:</th><td>" . &renderTime($total_io_time) . "</td></tr>\n";
print HTMLOUT "<tr><th>Average File Processing Time:</th><td>" . &renderTime($avg_processing_time) . "</td></tr>\n";
print HTMLOUT "<tr><th>Fastest File:</th><td>" . &renderTime($fastest_file) . "</td></tr>\n";
print HTMLOUT "<tr><th>Slowest File:</th><td>" . &renderTime($slowest_file) . "</td></tr>\n";
print HTMLOUT "<tr><th>Problem Files:</th><td>" . $problem_files . "</td></tr>\n";

print HTMLOUT "</table>\n";
print HTMLOUT "<hr />\n";
print HTMLOUT "<h2>Timing Chart (Gannt)</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";
print "Complete!\n\n";
exit;


## @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;
  # protocols
  $path =~ s/^(HDFS|HDFSShell|HDThriftFS):\//$1:\/\//;
  return $path;
}
## filenameCat() ##

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


## @function longestCommonPath
#
sub longestCommonPath
{
  my ($path_new, $path_current) = @_;
  my $result = '';
  if (defined $path_current)
  {
    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);
  }
  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">';
  }
  $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;
    # Scale Job co-ordinates
    my $jleft_percent = $rjstart / $duration;
    my $jleft = int(($jleft_percent * $table_width) + 0.5);
    my $jwidth_percent = $jduration / $duration;
    my $jwidth = int(($jwidth_percent * $table_width) + 0.5);
    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 . '%"><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);
  }
  elsif ($minutes > 0)
  {
    $time_str = sprintf('%dm%02ds', $minutes, $seconds);
  }
  else
  {
    $time_str = $seconds . 's';
  }
  return $time_str;
}
