#!/usr/bin/env perl

## Copyright (c) 2007 Data Intensive Cyberinfrastructure Foundation. All rights reserved.
## For full copyright notice please refer to files in the COPYRIGHT directory
## Written by Jean-Yves Nief of CCIN2P3 and copyright assigned to Data Intensive Cyberinfrastructure Foundation

use strict;
use warnings;
use File::Basename;
use IO::Handle;

use Getopt::Long;

$Getopt::Long::order=$PERMUTE;
$Getopt::Long::autoabbrev=1;

## This script collects the informations on the server activity:
## cpu fraction used , runq load, swap mem fraction used, disk space occupancy,
## network input activity rate, network output activity rate, disk space available in MB.
## all the output numbers are between 0 (no activity) and 100 (full load) except the absolute space available
## which is not used by the monitoring system directly but is used for feeding the resource "free space" metadata.
## They are registered into the iCAT by the msiServerMonPerf micro-service into the iCAT  database.
## Once this information is in the database, it can be used by the msiLoadBalancing micro-service
## in order to pick up the resource which is the least loaded.
##

#########################
# variables declaration #
#########################
	# options variable definition
	my $optHelp;
	my $optFS;
	my $optTime;
	my $optVerb;
	
	# result variable :
	my $sysFilePath = '';
	my $systype = '';
	my $rhost = '';
	my $nbCPU = 0;
	my $runqLoad = 0;
	my $memLoad = 0;
	my $swapRatio = 0;
	my $iswap = 0;
	my $oswap = 0;
	my $pagIOAct = 0;
	my $free = 0;
	my $totalMem = 0;
	my $netCapability = 0;
	my $diskUsed = 0;
	my $diskAbsAvail = 0;
	my $cpuUsed = 0;
	my $file = 0; # empty configuration file
	my $ipackets = 0;
	my $opackets = 0;
	my $iNetAct = 0; # input network activity
	my $oNetAct = 0; # output network activity
	my $netInput = 0;
	my $netOutput = 0;
	# constant variables
	my $pagLimit = 100; # limit of pagging I/O activity (MB/s)
	my $maxrqload = 4;  # maximum accepted runq load / CPU, rather arbitrary (not so much :-) ), can be modified.
	# variables used to find result variables
	my $paramTime = 0; # if the user give a time constraint
			   # used for network activity
	my $distrib = ''; # used to stock the linux distrib
	my $cmd = ''; # used to execute commands
	my $path = ''; # used to store the current path
	my $cpt = 0;
	my $i = 0;
	my @result;
	my @result2;
	my @temp;
	my @temp2;
	my @line_iname; # lines for the network interfaces (netstat output: eth, ce...)
	my $col_iname = 0; # column of the interface name
	my $col_mtu = 0; # column of the mtu
	my $col_iswap = 0; # pagging input swap activity
	my $col_oswap = 0; # pagging outpout swap activity
	my $col_idle = 0; # column where the idle time is found with 'vmstat'
	my $col_free = 0; # column of the free memory 
	my $col_swap = 0; # column of the swap memory
	my $col_ipack = 0; # column of the number of input packets
	my $col_opack = 0; # column of the number of output packets
	my $col_diskUsed = 0; # column of the disk activity
	my $col_diskAbsAvail = 0; # column for the absolute disk space available
	my $fsExists; # flag to record the existence of a filesystem

&GetOptions ("-help" => \$optHelp,"-v" => \$optVerb, "-fs:s" => \$optFS,"-t:i" => \$optTime);
	
# Test of the arguments
if( $optHelp )
{
	print_help(); # display help and close if -help option is mentionned
	exit;
}

if( $optFS )
{
	$sysFilePath = $optFS;
}
else
{
	Log("File system path is missing! $!");
}

if( $optTime )
{
	$paramTime = $optTime;	
}
else
{
	$paramTime = 5;
}
	 
# test the existence of the file system...
$fsExists = 1;
my @sysPathList = split(',', $sysFilePath);
foreach my $pth(@sysPathList) {
	if ($pth ne 'none') {
		my $rc = system("LANG=C;export LANG;df -kP $pth > /dev/null 2>&1"); # JMC - backport 4830
		if( $rc != 0 ) {
			Log("The file $pth system doesn't exist. $!");
			$fsExists = 0;
		}
	}
}

###############################################
# get the name of the server and the platform #
###############################################
$systype = `/bin/uname`; chomp($systype);
$rhost = `/bin/uname -n`; chomp($rhost);
$path = dirname($0)."/../../config/scriptMonPerf.config";

##################################################
# Test the existence of the configuration file   #
# if it doesn't exit, it is created in the       #
# directory of the script and the file is opened #
##################################################
if( (-e "$path") && (! -z "$path"))
{
	$file = 1;
}
else
{
	
	#############################################
	# get the number of processor on the server #
	#############################################
	if( $systype eq 'Linux' ) # if the platform is linux 
	{
		$nbCPU = `grep -c cpu /proc/stat` - 1;
	}

	if( $systype eq 'SunOS' ) # if the platform is Sun
	{
		$cmd = `uname -X | grep NumCPU`;
		chomp($cmd);
		@result = split("= ", $cmd);
		$nbCPU = $result[1];
	}

	# the format of vmstat command is different on
	# the different platform...
	# so it is interessant to determine the column useful.
	# for example the idle time, free memory, swap memory...
	@result = `vmstat`;
	chomp($result[1]);
	@result = split('\s+', $result[1]);
	
	foreach my $column(@result) # swap memory column (swap for Sun or swpd for Linux)
	{
		last if( ( $column eq 'swap' ) || ( $column eq 'swpd' ) );
		$col_swap++;
	}
	foreach my $column(@result) # free memory column
	{
		last if( $column eq 'free' );
		$col_free++;
	}
	foreach my $column(@result) # paging input swap activity (si for Linux or pi for Sun)
	{
		last if( ( $column eq 'si' ) || ( $column eq 'pi') );
		$col_iswap++;
	}
	foreach my $column(@result) # paging output swap activity (so for Linux or po for Sun)
	{
		last if( ( $column eq 'so' ) || ( $column eq 'po') );
		$col_oswap++;
	}
	foreach my $column(@result) # idle column
	{
		last if( $column eq 'id' );
		$col_idle++;
	}

	# the format of netstat command is also different on
	# the different platform...
	# first, one need to determine for each platform the two usefull columns:
	# input packets and output packets
	@result = `netstat -i`;
	if( $systype eq 'SunOS' )
	{
		chomp($result[0]);
		@result = split('\s+', $result[0]);
	}
	if( $systype eq 'Linux' )
	{
	chomp($result[1]);
	@result = split('\s+', $result[1]);
	}

	foreach my $column(@result) # input packet column (ipkts for Sun and RX-OK for Linux)
	{
		last if( ( $column eq 'Ipkts' ) || ( $column eq 'RX-OK' ) );
		$col_ipack++;
	}
	foreach my $column(@result) # output packet column (opkts for Sun or TX-OK for Linux)
	{
		last if( ( $column eq 'Opkts' ) || ( $column eq 'TX-OK' ) );
		$col_opack++;
	}
	foreach my $column(@result) # mtu column (Mtu for Sun and MTU for Linux
	{
		last if( ( $column eq 'Mtu' ) || ( $column eq 'MTU' ) );
		$col_mtu++;
	}
	foreach my $column(@result)
	{
		last if( ( $column eq 'Name' ) || ( $column eq 'Iface' ) );
		$col_iname++;
	}

	# the format of df command is different on
	# the different platforms...
	# it is necessary to determine the column useful for each plateform:
	if ( $fsExists ) { 
		foreach my $pth(@sysPathList) {
			if ( $pth ne 'none' ) {
				@result = `LANG=C;export LANG;df -kP $pth`; # JMC - backport 4830
				chomp($result[0]);
				foreach my $entry(@result) {
					if ( $entry !~ /Filesystem/ && $entry =~ /%/) {
						chomp($entry);
						@temp2 = split('\s+', $entry);
						foreach my $column(@temp2) {
							last if (  $column =~ /%/ );
							$col_diskUsed++;
						}
					}
				}
				$col_diskAbsAvail = $col_diskUsed - 1;
				last;
			}
		}
	}

	# add all these info in the file...
	if( $file == 0)
	{
		open(FIC,">$path") or die("open: $!");
		print(FIC "systype:$systype\n");
		print(FIC "rhost:$rhost\n");
		print(FIC "proc:$nbCPU\n");
		print(FIC "swap:$col_swap\n");
		print(FIC "free:$col_free\n");
		print(FIC "iswap:$col_iswap\n");
		print(FIC "oswap:$col_oswap\n");
		print(FIC "idle:$col_idle\n");		
		print(FIC "mtu:$col_mtu\n");
		print(FIC "iname:$col_iname\n");
		print(FIC "ipack:$col_ipack\n");
		print(FIC "opack:$col_opack\n");
		print(FIC "diskused:$col_diskUsed\n");
		print(FIC "diskabsavail:$col_diskAbsAvail\n");
		# close the configuration file
		close(FIC);
	}
} # end of the else


# we get the index of the line for the network interface
# given by the netstat command...
# it is used to compute the network activity
@result = `netstat -i`;		
if( $systype eq 'SunOS' )
{
	$cpt = 1;	# first line of the array to use for Sun
	$i = 0;
}

if( $systype eq 'Linux' )
{
	$cpt = 2;	# first line of the array to use for Linux
	$i = 0;
}

while($cpt < $#result)
{
	chomp($result[$cpt]);
	@temp = split('\s+', $result[$cpt]);
	if($temp[$col_iname] !~ 'lo' && $temp[$col_iname] !~ 'ce1')
	{
		$line_iname[$i] = $cpt;
		$i++;
	}
	$cpt++;
}

# if the conf file already exists,
# we get the informations from there.
if( $file != 0 )
{
	open(FIC,"$path") or die("open: $!");
	my @filelines = <FIC>;
	close(FIC);
	my $linef;
	foreach $linef(@filelines)
	{
		chomp $linef;
		if( $linef =~ /proc:/ )
		{
			$nbCPU = substr($linef, 5);
		}
		if( $linef =~ /swap:/ )
		{
			$col_swap = substr($linef, 5);
		}
		if( $linef =~ /free:/ )
		{
			$col_free = substr($linef, 5);
		}
		if( $linef =~ /iswap:/ )
		{
			$col_iswap = substr($linef, 6);
		}
		if( $linef =~ /oswap:/ )
		{
			$col_oswap = substr($linef, 6);
		}
		if( $linef =~ /idle:/ )
		{ 
			$col_idle = substr($linef, 5);
		}
		if( $linef =~ /mtu:/ )
		{
			$col_mtu = substr($linef, 4);
		}
		if( $linef =~ /iname:/ )
		{
			$col_iname = substr($linef, 6);
		}
		if( $linef =~ /ipack:/ )
		{
			$col_ipack = substr($linef, 6);
		}
		if( $linef =~ /opack:/ )
		{
			$col_opack = substr($linef, 6);
		}
		if( $linef =~ /diskused:/ )
		{
			$col_diskUsed = substr($linef, 9);
		}
		if( $linef =~ /diskabsavail:/ )
		{
			$col_diskAbsAvail = substr($linef, 13);
		}
		
	}

}

#######################################
# fraction of the swap being used (%) #
#######################################
getSwapFractionUsed();

##################################
# what's the paging I/O activity ?
# it is being computed but not used right now for the monitoring.
@result = `vmstat`;
chomp($result[2]);
@result = split('\s+', $result[2]);
$iswap = $result[$col_iswap]; # in kB/s
$oswap = $result[$col_oswap];
$pagIOAct = $iswap + $oswap;

####################################################
# check the number of interfaces on the server and #
# their capability (ethernet or gigabit)           #
# given in Mbits/s                      				   #
####################################################
if( !$netCapability )
{
	@result = `netstat -i`;
	$cpt = 0;	
	while( $cpt < $#line_iname+1 ) # for each line
	{	
		$i = $line_iname[$cpt]; # get the first line to treat
		@temp = split('\s+',$result[$i]); # extraction of the line
		if($temp[$col_iname] eq 'eth')
		{
			# if eth => 100 mbits/s
			$netCapability = $netCapability + 100;
	
		}
		if($temp[$col_iname] ne 'eth' && $temp[$col_iname] ne 'ce1')	# else 1000 Mbits/s
		# assumption: if it is not a 100 Mbits/s interface, it is a Gbits/s one.
		# this is made like this as it is not straightforward to guess the value
		# depending on the interface name.
		# needs some improvement.
		{
			$netCapability = $netCapability + 1000;
		}
		$cpt++;
	}	
	
}

########################################################################
# get the average number of jobs in the run queue over the last minute #
########################################################################
$cmd = `uptime`;
chomp($cmd);
@result = split("\, ", $cmd);
$runqLoad = int($result[4]/$nbCPU/$maxrqload*100);
$runqLoad = 100.0 if $runqLoad > 100.0;

######################################
# get the total memory of the server #
######################################
if( $systype eq 'Linux') # if the platform is Linux
{
	$cmd = `grep MemTotal /proc/meminfo`;
	@result = split('\s+', $cmd);
	$totalMem = $result[1]*1024;
}

if( $systype eq 'SunOS') # if the platform is Sun
{
	$cmd = `/etc/prtconf | grep Memory`;
	($totalMem) = $cmd =~ /.+:\s*(\d+)/s;
	$totalMem *= 1024*1024;
}

#############################
# Check the disk occupation #
#############################
if ( $fsExists ) {
	my $first = 0;
	$diskUsed = "";
	$diskAbsAvail = "";
	foreach my $pth(@sysPathList) {
		if ( $first ) { 
			$diskUsed .= ",";
			$diskAbsAvail .= ",";
		}
		$first = 1;
		if ( $pth eq 'none' ) {
			$diskUsed .= -1;
			$diskAbsAvail .= -1;
			next;
		}
		@result = `LANG=C;export LANG;df -kP $pth`; # JMC - backport 4830
		while ( my $entry = shift(@result) ) {
			if ( $entry !~ /Filesystem/ && $entry =~ /%/) {
				chomp($entry);
				@temp2 = split('\s+', $entry);
                # suppression of the character '%' at the end of the chain for diskUsed
                my $diskUsedTemp = $temp2[$col_diskUsed];
                $diskUsedTemp = substr($diskUsedTemp, 0, length($diskUsedTemp)-1);
                if ($diskUsedTemp =~ /^[+-]?\d+$/ ) {
					$diskUsed .= $diskUsedTemp;
                } else {
                	$diskUsed .= -1;
                }
                if ($temp2[$col_diskAbsAvail] =~ /^[+-]?\d+$/ ) {
					$diskAbsAvail .= int($temp2[$col_diskAbsAvail]/1024);
                } else {
					$diskAbsAvail .= -1;
                }
			}
		}
	}
}
else {
	$diskUsed = -1;
	$diskAbsAvail = -1;
}


###################
# netstat command #
###################
@result = `netstat -i`; # first call of netstat command
# instead of using 'sleep' command, it is better to call
# the vmstat command with the same time of the sleep command.
# vmstat command is in a function at the end of the script.
getCpuUse();
@temp = `netstat -i`;
$i=0; # counter used for the 'while'
while($i <= $#line_iname)
{
	$cpt = $line_iname[$i];
	chomp($temp[$cpt]);
	@temp2 = split('\s+', $temp[$cpt]);
	$ipackets = $temp2[$col_ipack]; # last value given by the command
	$opackets = $temp2[$col_opack];
	chomp($result[$cpt]);
	@result2 = split('\s+', $result[$cpt]);
	$ipackets -= $result2[$col_ipack]; # first value given by the command
	$opackets -= $result2[$col_opack];
	
	$ipackets /= $paramTime;
	$opackets /= $paramTime;

	# nb packets * mtu / 1e6 => Mbit/s
	$iNetAct += (($ipackets * $result2[$col_mtu]) * 8) / 1e6;
	$oNetAct += (($opackets * $result2[$col_mtu]) * 8) / 1e6;

	$i++;
}

$netInput = int( ($iNetAct / $netCapability) * 100 );
$netInput = 100 if $netInput > 100;
$netOutput = int( ($oNetAct / $netCapability) * 100 );
$netOutput = 100 if $netOutput > 100;

# what's the memory load ? (%)
$memLoad = $totalMem - getFree()*1024;
$memLoad = int($memLoad/$totalMem*100);
$memLoad = 100 if $memLoad > 100;

print "#".$cpuUsed."#".$memLoad."#".$swapRatio."#".$runqLoad."#".$diskUsed."#"
       .$netInput."#".$netOutput."#".$diskAbsAvail."#";

# if verbose mode
if( $optVerb )
{
		print "\n=========== Server Name : " . $rhost . " ===========\n";
		print "=Msc= Operating system => " . $systype . "\n";
		print "=Msc= Number of processors => " . $nbCPU . "\n";
		print "=CPU= CPU utilization rate (%) => " . $cpuUsed . "\n";
		print "=CPU= Run queue load => " . $runqLoad . "\n";
		print "=Mem= Total memory (Bytes) => " . $totalMem . "\n";
		print "=Mem= Fraction of the memory being used (%) => " . $memLoad . "\n";
		print "=Mem= Fraction of the swap memory being used (%) => " . $swapRatio . "\n";
		print "=Mem= Pagging I/O activity => " . $pagIOAct . "\n";
		print "=Dsk= Disk occupation ratio (%) for \"" . $sysFilePath . "\" => " . $diskUsed . "\n";
		print "=Dsk= Disk volume available (MB) for \"" . $sysFilePath . "\" => " . $diskAbsAvail . "\n";
		print "=Net= Network interface max capacity (Mbits/s) => " . $netCapability . "\n";
		print "=Net= Network input activity (Mbits/s) => " . $iNetAct . "\n";
		print "=Net= Network output activity (Mbits/s) => " . $oNetAct . "\n";
		print "=Net= Network input activity rate (%) => " . $netInput . "\n";
		print "=Net= Network ouput activity rate (%) => " . $netOutput . "\n";
}

#######################################
# vmstat command to get the CPU usage #
#######################################
sub getCpuUse
{
	my $count = 0;
	@temp = `vmstat 1 $paramTime`; 
	
	while (my $entry = shift(@temp) ) {
		chomp($entry);
		if ( $entry !~ /cpu/ && $entry !~ /id/ ) {
			@temp2 = split('\s+', $entry);
			if ($temp2[$col_idle] > 100 ) {
				$cpuUsed += 0;
			}
			else {
				$cpuUsed += 100 - $temp2[$col_idle];
			}
			$count++;
		}
	}
	
	if ( $count != 0 ) {
		$cpuUsed = int($cpuUsed/$count);
	}
	else {
		$cpuUsed = 0;
	}

}

##################################################
# function : get the fraction of swap being used #
##################################################
sub getSwapFractionUsed
{
	my $swapUsed;
	my $swapFree;

	@result = `top -b -n 1`;
	if( $systype eq 'SunOS' )
	{
		foreach my $c(@result)
		{
			if( $c =~ m/^Memory:/ )
			{
				 # get the different parts separated by ', '
				 @temp = split("\\, ",$c);
				 
				 # get the different parts separated by ' '
				 my @swapUsed = split('\s+', $temp[2]);
				 my @swapFree = split('\s+', $temp[3]);
				 
				 # last character is the metric (M or G for example)
				 # we want the result in bytes...
				 my $swapUsedMetric = substr($swapUsed[0], length($swapUsed[0])-1, 1);
				 my $swapFreeMetric = substr($swapFree[0], length($swapFree[0])-1, 1);
			
				 if( $swapUsedMetric eq 'M' )
				 {
				 	$swapUsed = (substr($swapUsed[0], 0, length($swapUsed[0])-1)) * 1e3 * 1024;
				 }
				 if( $swapUsedMetric eq 'G' )
				 {
				 	$swapUsed = (substr($swapUsed[0], 0, length($swapUsed[0])-1)) * 1e6 * 1024;
				 }
				 if( $swapUsedMetric eq 'k' )
				 {
				 	$swapUsed = (substr($swapUsed[0], 0, length($swapUsed[0])-1)) * 1024;
				 }
				 if( $swapFreeMetric eq 'M' )
				 {
				 	$swapFree = (substr($swapFree[0], 0, length($swapFree[0])-1)) * 1e3 * 1024;
				 }
				 if( $swapFreeMetric eq 'G' )
				 {
				 	$swapFree = (substr($swapFree[0], 0, length($swapFree[0])-1)) * 1e6 * 1024;
				 }
				 if( $swapUsedMetric eq 'k' )
				 {
				 	$swapFree = (substr($swapFree[0], 0, length($swapFree[0])-1)) * 1024;
				 }
			
				 if ( ($swapUsed + $swapFree) != 0 ) {
				 	$swapRatio = int(($swapUsed * 100) / ($swapUsed + $swapFree));
				 }
			}
		}
	}
	if( $systype eq 'Linux' )
	{
		foreach my $c(@result)
		{
			if( $c =~ /Swap:/ )
			{
				# get the different parts separated by ', '
				@temp = split(',', $c);
				# there are spaces characters before the swap used value...
				$temp[1] = reverse($temp[1]);
								
				# get the different parts separated by ' '
				my @swapUsed = split('\s+', $temp[1]); 
				my @swapFree = split('\s+', $temp[2]);
				
				# don't forget that the swap used is inversed
				$swapUsed[1] = reverse($swapUsed[1]);
				
				# the result finish with character 'k',
				# and is in kB, we want in bytes
				my $swapUsed = (substr($swapUsed[1], 0, length($swapUsed[1])-1)) * 1024;
				my $swapFree = (substr($swapFree[1], 0, length($swapFree[0])-1)) * 1024;
				
				if ( ($swapUsed + $swapFree) != 0 ) {
					$swapRatio = int(($swapUsed * 100) / ($swapUsed + $swapFree));
				}
				
			}
		}
	}
}

##################################
# function : get the free memory #
##################################
sub getFree
{
	@result = `vmstat`;
	chomp($result[2]);
	@temp = split('\s+', $result[2]);
	
	my $free = $temp[$col_free];
	
	return ($free);
}

###############
# Help option #
###############
sub print_help
{
	print "\n";
	print "This script gives various metrics (CPU load, network activity...)  of a server.\n\n";
	print "Options:\n";
	print "1) -v: verbose mode\n";
	print "2) -help: to obtain this message\n";
	print "3) -fs: file system path\n";
	print "4) -t: time parameter used for vmstat and netstat (duration of the measurement in s)\n";
	print "\n";
	return (0);
}

##################################
# Error message display function #
##################################
sub Log
{
	my($message, $return) = @_;
	print STDERR "$0: $message\n";
	return 0 if $return;
}
