#!/bin/bash

. /etc/rc.d/init.d/functions

#
# checkProcessMemoryThreshold
# Parameter 1 : process
# Parameter 2 : memory threshold (kB)
#
checkProcessMemoryThreshold() {
    mem=$(ps -eo sz,args | grep $1 | sort | tail -1 | /opt/bin/awk '{print $1}')
    if [ "$mem" -gt "$2" ]; then
        /nn/bin/AddNnuDiagLog -mMemRecovery -sE -wN -v-1 "Process $1 uses $mem KB of memory, Stopping $1 to recover the memory"
        if [ -f /etc/rc.d/init.d/$1 ]; then
            /etc/rc.d/init.d/$1 stop 
        else
            killproc $1
        fi
    fi
}


echo $"----------------------------------------------------------" >> /var/log/CPULoad.log
echo $"`date` High Memory Usage detected - Information Begin" >> /var/log/CPULoad.log
echo $"----------------------------------------------------------" >> /var/log/CPULoad.log
echo $"Output of /proc/meminfo :" >> /var/log/CPULoad.log
cat /proc/meminfo >> /var/log/CPULoad.log
echo $"Output of /proc/slabinfo :" >> /var/log/CPULoad.log
cat /proc/slabinfo >> /var/log/CPULoad.log
echo $"Output of ps -eo pid,pcpu,sz,args | sort +2 :" >> /var/log/CPULoad.log
ps -eo pid,pcpu,sz,args | sort +2 >> /var/log/CPULoad.log

# Additional check put in place to determine if owcimomd process is using > 50 MB of memory.
# This can be expanded to include a check on all processes listed in a configuration file 
# where memory thresholds are recorded.
checkProcessMemoryThreshold owcimomd 50000

echo $"----------------------------------------------------------" >> /var/log/CPULoad.log
echo $"`date` High Memory Usage detected - Information End" >> /var/log/CPULoad.log
echo $"----------------------------------------------------------" >> /var/log/CPULoad.log


