#!/usr/bin/perl
#
# Copyright (c) 2002, 2006, Oracle. All rights reserved.  
#
#    NAME
#      countZombie.pl  
#
#    DESCRIPTION
#      Metric script that checks the percentage of processes,
#      which are in zombie state. 
#
#    OUTPUT:
#      em_result=<value>
#
#    NOTES
#      Supported platforms: Solaris, HP-UX, Linux, AIX, MACOSX and Tru64
#    
#      Usage:
#        countZombie.pl
#
#    MODIFIED    (MM/DD/YY)
#      nsharma    10/12/06 - Fix for OSF1 zombie process calculation
#      ajayshar   10/02/06 - Backport ajayshar_bug-5350824 from main
#      rmenon     02/23/04 - rmenon_host_mgmt_checkin 
#      lnhan      06/18/03 - Creation


use strict;
require "emd_common.pl";

my $os;                         # operating system  
chomp ($os = `uname -s`) or die "Failed to run the uname command";

my @procStates = ();            # process state list

SWITCH: {
   $os eq "SunOS" && do {
          chomp (my $ver = `uname -r`);
          if ( $ver !~ /^4./ ) {
             # OS is Solaris
             @procStates = `/usr/bin/ps -eo s`;
             last SWITCH;
          }
       };
   $os eq "HP-UX" && do {
          # OS is HP-UX
          # Enable XPG4 environment for ps
          $ENV{UNIX95} = "";
          @procStates = `/usr/bin/ps -eo state`;
          last SWITCH;
       };
   $os eq "Linux" && do {
          # OS is Linux
          @procStates = `/bin/ps -eo stat`;
          last SWITCH;
       };
   $os eq "AIX" && do {
          # OS is AIX
          @procStates = `/bin/ps -eo stat`;
          last SWITCH;
       };
   $os eq "OSF1" && do {
          # OS is OSF1
          @procStates = `/usr/bin/ps -eo cmd`;
          last SWITCH;
       };
   $os eq "Darwin" && do {
          # OS is MACOSX
          @procStates = `/bin/ps -eo stat`;
          last SWITCH;
       };
   EMD_PERL_DEBUG ("Unsupported Operating System"); 
   die "Unsupported Operating System\n";
}

# number of entries in the process list 
my $totalProc = @procStates; 

my $count = 0;                  # counter for number of zombies
if ( $os eq "OSF1" ) {
  for my $line ( @procStates) {
    if ( $line =~ /<defunct>/ ) {
      # process in zombie state
      $count++ ;
    }
  }
}
else
{
  for my $line ( @procStates) {
    if ( $line =~ /^Z/ ) { 
       # process in zombie state 
       $count++ ; 
    } 
  }
}

EMD_PERL_DEBUG ("Total number of processes : $totalProc\n");
EMD_PERL_DEBUG ("Number of zombie processes: $count\n");

my $percent = sprintf "%0.2f", $count/$totalProc *100;

print "em_result=$percent|$count\n";
EMD_PERL_DEBUG ("em_result=$percent|$percent\% of the processes are in zombie state.\n");
