#!/usr/bin/perl

# Author: Andrew Theurer
#
# usage: numastat-postprocess <dir>  dir = directory where numastat.txt can be found
#
# The purpose of this script is to
# -output the chart data in JSON format (numastat.js)
# -output html file (numastat.html) with embedded javascript, using d3.js libraries
#
# The input file that this scripts processes must be in the format which is generated by numastat-datalog

use strict;
use warnings;

use lib $ENV{'pbench_lib_dir'};
no lib ".";
use GenData qw(gen_data);

my $dir=$ARGV[0];
my $pid;
my $node;
my $mem_MB;
my $timestamp;
my $timestamp_ms;
my $line;
my $nr_nodes;
my @nodelist;
my %numastat;

open(NUMASTAT_TXT, "$dir/numastat-stdout.txt") || die "could not find $dir/numastat-stdout.txt\n";
while (my $line = <NUMASTAT_TXT>) {
	chomp $line;
	#timestamp: 1398274848.924503133
	#
	#Per-node process memory usage (in MBs)
	#PID                        Node 0          Node 1           Total
	#----------------  --------------- --------------- ---------------
	#63429 (qemu-kvm)          4927.60            1.10         4928.70
	#63451 (qemu-kvm)             8.13         4938.83         4946.96
	#----------------  --------------- --------------- ---------------
	#Total                     4935.73         4939.93         9875.66
	if ( $line =~ /^timestamp:\s(\d+\.\d+)/ ) {
		$timestamp = $1;
		$timestamp_ms = 1000 * $timestamp;
		next;
	}
	if ($line =~ /^PID\s+Node.+/) {
		$line =~ s/^PID\s+Node\s*//;
		$line =~ s/\s+Total$//;
		@nodelist = split(/\s+Node\s/, $line);
		$nr_nodes = @nodelist;
		next;
	}

	if ($line =~ s/^(\d+)\s\S+// ) {
		$pid = "$1";
		for $node (@nodelist) {
			$line =~ s/\s+(\d+\.\d+)//;
			$mem_MB = $1;
			$numastat{$pid}{$node}{$timestamp_ms} = $mem_MB;
		}
	}
}
close(NUMASTAT_TXT);

my %graph_threshold;
my %graph_type;
gen_data(\%numastat, \%graph_type, \%graph_threshold, $dir);
