#!/bin/ash
#
# This script monitors free memory in the SP, and returns a value
# reporting that free memory is critical.
# The script also logs events when applicable.
# Several other system resource values are saved to files for
# later reporting, if needed.
SEL_LOGGER="/usr/local/bin/sel_logger"

# Thresholds for low memory warning and low memory critical. 
# Values are in Kbytes.
LOW_MEM_WARNING=35000
LOW_MEM_REBOOT=30000
return_code=0
log_warning=0

# Check file system disk space usage
check_filesystems() {
    df | awk '{var=substr($5,1,length($5)-1); if ($1 == "none") print $0>"/var/run/df-output";  }'
}

# Check file descriptors
check_filedescriptors() {
     cat /proc/sys/fs/file-nr > /var/run/file-nr-output
}

# Check free memory
check_memory() {

     # If free mem falls below the warning threshold, just log the event.
     # Note: to keep from spamming event log, the warnings are only logged
     # periodically, as commanded by the caller.
     #
     # If free mem falls below the critical threshold, log an event and
     # return an error code to the caller.
     freemem=$(grep MemFree /proc/meminfo | awk '{print $2}' )
     if [ "$freemem" -le "$LOW_MEM_REBOOT" ] ; then
         return_code=3
     elif [ "$freemem" -le "$LOW_MEM_WARNING" ] && [ $log_warning == 1 ] ;  then
             $SEL_LOGGER IPMI.critical "Low Memory Warning: $freemem"
     fi
}

#Script starts here:

# Parameter 1, if it exists, orders script to log the warning event.
if [ $# -eq 1 ] ; then
       if [ $1 = "log" ] ; then
           log_warning=1
       fi
fi

#Check free memory
check_memory

#Check the file systems' space
check_filesystems

#Check file descriptors
check_filedescriptors

exit $return_code
