#!/usr/bin/perl

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

use strict;
use warnings;

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

my $dir=$ARGV[0];
my $dev;
my %proc_vmstat;
my $timestamp;
my $timestamp_ms;
my $last_timestamp_ms;
my $line;
my $this_element;
my $this_rate;
my $val_diff;
my $duration;
my $value;
my $last_value;
my $value_diff;
my $stat;
my $substat;
my %rate;
my $i;
my %graph_type;
my %graph_threshold;

open(VMSTAT_TXT, "$dir/proc-vmstat-stdout.txt") || die "could not find $dir/proc-vmstat-stdout.txt\n";
while (my $line = <VMSTAT_TXT>) {
	chomp $line;
	# timestamp: 1394048617.043209234
	# nr_free_pages 65401224
	# nr_alloc_batch 2387
	# nr_inactive_anon 2062
	# nr_active_anon 9829
	# nr_inactive_file 44843

	if ( $line =~ /^timestamp:\s(\d+\.\d+)/ ) {
		$timestamp = $1;
		$timestamp_ms = 1000 * $timestamp;
		next;
	}

	if ($line =~ /^(\w+)\s(\d+)/ ) {
		$stat = $1;
		$value = $2;
		if ($stat =~ /^([a-zA-Z]+)_(.*)/) {
			$stat = $1;
			$substat = $2;
			$proc_vmstat{$stat}{$substat}{$timestamp_ms} = $value;
		}
	}
}
close(VMSTAT_TXT);

# generate the rates and an average for each stat
for $stat (sort keys %proc_vmstat) {
	for $substat (sort keys %{ $proc_vmstat{$stat} }) {
		$i = 0;
		$last_timestamp_ms = 0;
		for $timestamp_ms (sort {$a<=>$b} keys %{ $proc_vmstat{$stat}{$substat} } ) {
			$value = $proc_vmstat{$stat}{$substat}{$timestamp_ms};
			if ($last_timestamp_ms != 0) {
				$duration = ($timestamp_ms - $last_timestamp_ms)/1000;
				$value_diff = $value - $last_value;
				$this_rate = $value_diff / $duration;
				$rate{"proc-vmstat"}{$stat . "_delta_sec"}{$substat}{$timestamp_ms} = $this_rate;
				$i++;
			}
			$last_value = $value;
			$last_timestamp_ms = $timestamp_ms;
		}
	}
}
gen_data(\%rate, \%graph_type, \%graph_threshold, $dir);
