# $Header: osCpuUsage.pl 09-oct-2007.22:47:25 ssalunke Exp $
#
# osCpuUsage.pl
# 
# Copyright (c) 2001, 2008, Oracle. All rights reserved.  
#
#    NAME
#      osCpuUsage.pl 
#
#    DESCRIPTION
#       This script is used in EMD to collect CPU related statistics.  
#       Only Linux is supported.
#	It prints
#                 
#       em_result=<cpu_num>|<user_time>|<system_time>|<wait_time>|<idle_time>
#			  
#
#    NOTES
#      
#
#    MODIFIED   (MM/DD/YY)
#    ssalunke    01/17/08 - XbranchMerge ssalunke_bug-6490436_10.2.0.5.0 from
#                           st_emagent_10.2.0.1.0
#    ssalunke    11/12/07 - XbranchMerge ssalunke_bug-6490436 from main
#    ssalunke    10/09/07 - Changed tail options in RHEL5
#    shnavane    12/11/06 - Fix bug#5701916
#    shnavane    04/03/07 - Backport shnavane_bug-5701916 from main
#    sreddy      10/18/04 - cleanup and fix compile errors 
#    sacgoyal    10/13/04 - bug 3845346 fixed 
#    vsekuboy    10/28/02 - Removed Tru64
#    vsekuboy    10/25/02 - Modified the comments to mention the OSs supported
#    vsekuboy    10/25/02 - Changes for Tru64
#    xxu         06/25/02 - remove /usr/local/bin/perl
#    rlal        09/21/01 - Base wants to use PATH not hardcoded execs.
#    rlal        09/14/01 - Adding Linux.
#    njagathe    07/27/01 - Fix spello on HP
#    aaitghez    04/20/01 - reversing wait and idle output.
#    aaitghez    04/20/01 - fixing hangup on HP.
#    aaitghez    04/19/01 - metric to get cpu utlization.
#    aaitghez    04/19/01 - Creation
# 

die "unsupported platform" if ($^O ne "linux"); 

$ENV{PATH} = "/bin:/usr/bin:/usr/local/bin:/local/bin";

my $cpuidle;
my $cpuuser;
my $cpusys ;
my $cpuwait = 0;

my $value;
my @data;
my $count;
my $i;

$value = `grep cpu /proc/stat | tail -n +2` or die "Failed to run grep";
@data = split("\n", $value);

$count = scalar(@data);

for ($i = 0; $i < $count; $i++)
{
  $_ = $data[$i];
  
  if(/cpu\d+\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/) 
  {
    $cpuuser = $1;
    $cpuuser += $2;
    $cpusys  = $3;
    $cpuidle = $4;
    $cpuwait = $5;
  }
  elsif (/cpu\d+\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/)
  {
    $cpuuser = $1;
    $cpuuser += $2;
    $cpusys  = $3;
    $cpuidle = $4;
  }
  print "em_result=$i|$cpuuser|$cpusys|$cpuwait|$cpuidle\n";
}

exit 0;
