#!/usr/bin/perl

use strict;

my ($x, @arr, %ubc, %failed_beans, $proc_ubc, $bean_str, $veid, $bean_counter, $count);

my ($DEBUG) = 0; # set to 1 to see debug info

# get hostname
my $hostname = `hostname`;
chomp $hostname;

# read in UBC stored from last run
if (-e "fail_counters.txt") {
	open(IN,"fail_counters.txt");

	while (<IN>) {
		chomp;
		($veid, $bean_counter, $count) = split /,/,$_;

		$failed_beans{$veid}{$bean_counter} = $count;

		print "FAIL COUNT - VEID: $veid bc: $bean_counter val: $failed_beans{$veid}{$bean_counter}\n" if ($DEBUG);
	}
	close(IN);
}

# get bean counters
my $proc_ubc = `cat /proc/user_beancounters`;

# split out into an array
my @beans = split /\n/,$proc_ubc;

open (OUT,">fail_counters.txt"); # file for tracking what the UBC are at.

for $x (2..$#beans) { #skip the first 2 lines, version number and column headers
	$bean_str = $beans[$x];
	$bean_str =~ s/\s+/ /g;
	$bean_str =~ s/^\s*//;

	# figure out which VE we're looking at
	if ($bean_str =~ m/^\s*([^:]*):/ ) {
		$veid = $1;
		print "Analyzing VE: $veid \n\n" if ($DEBUG);
	}
	
	# remove VE info 
	$bean_str =~ s/^\s*[^:]*:\s*//;

	# split info into array
	@arr = split / /,$bean_str;
	($bean_counter, $count) = ($arr[0], $arr[5]);

	$ubc{$veid}{$bean_counter} = $count;

	if ($failed_beans{$veid}{$bean_counter} != $ubc{$veid}{$bean_counter}) {
		print "$hostname VEID: $veid Bean Counter: $bean_counter increased from $failed_beans{$veid}{$bean_counter} to $ubc{$veid}{$bean_counter} 
			Held: $arr[1] Max Held: $arr[2] Barrier: $arr[3] Limit: $arr[4]\n";
	}

	print OUT "$veid,$bean_counter,$count\n";

}

close(OUT);


#VZ Quota info

my $proc_vzq = `cat /proc/vz/vzquota`;
my @vzq = split /\n/,$proc_vzq;
my ($vzq_str, $utilization);

for $x (1..$#vzq) {
	$vzq_str = $vzq[$x];
	$vzq_str =~ s/\s+/ /g;
	$vzq_str =~ s/^\s*//;
	
	if ($vzq_str =~ m/^\s*([^:]*):/ ) {
		$veid = $1;
		print "Analyzing Quota VE: $veid \n\n" if ($DEBUG);
	}
	else {
		@arr = split / /,$vzq_str;
		$utilization = $arr[1] / $arr[2];
		if ($utilization > .80) {
			$utilization *= 100;
			$utilization = sprintf("%.2f",$utilization);
			print "VZ Quota needs attention for VE: $veid Item: $arr[0] is at $utilization\%\n\tUsage: $arr[1]\n\tSoftlimit: $arr[2]\n\tHardlimit: $arr[3]\n\tTime: $arr[4]\n\tExpire: $arr[5]\n";
		}
	}
}
