nagios-scripts/check-mem.sh
Jeroen De Meerleer 17ce488ac3
Refactor shell scripts to remove unused code.
- Remove possibleaverages array from check-disk.sh and check-mem.sh
2023-05-31 11:40:47 +02:00

106 lines
2.9 KiB
Bash

#!/bin/bash
#
#/
#/ Usage:
#/ check-memory.sh --warning=<level> --critical=<level>
#/
#/ Checks the memory usage
#/
#/ Options:
#/ -w, --warning=<level> The level of when to trigger a warning (level=loadavg/nproc)
#/ -c, --critical=<level> The level of when to trigger a critical warning (level=loadavg/nproc)
#/
#/ Exit Codes:
#/ 0 Everything OK
#/ 1 Warning level exceeded
#/ 2 Critical level exceeded
#/ 3 Unknown status
#/
Usage() {
grep '^#/' "${script_dir}/${script_name}" | sed 's/^#\/\w*//'
}
GetOptions() {
# https://stackoverflow.com/a/29754866
OPTIONS=w:c:
LONGOPTS=warning:,critical:
# -use ! and PIPESTATUS to get exit code with errexit set
# -temporarily store output to be able to check for errors
# -activate quoting/enhanced mode (e.g. by writing out “--options”)
# -pass arguments only via -- "$@" to separate them correctly
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
# e.g. return value is 1
# then getopt has complained about wrong arguments to stdout
Usage
exit 2
fi
# read getopt's output this way to handle the quoting right:
eval set -- "$PARSED"
# now enjoy the options in order and nicely split until we see --
while true; do
case "$1" in
-w|--warning)
warn="$2"
shift 2
;;
-c|--critital)
crit="$2"
shift 2
;;
--)
shift
break
;;
*)
echo "MEMORY UNKNOWN - ${1} is not a valid parameter"
exit 3
;;
esac
done
}
LC_NUMERIC="C"
warn=0.7
crit=0.9
script_name=$(basename "${0}")
script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
GetOptions "$@"
totalfull=$(cat /proc/meminfo | grep MemTotal | awk '{ print $2; }')
availfull=$(cat /proc/meminfo | grep MemAvailable | awk '{ print $2; }')
usedfull=$(echo ${totalfull}-${availfull} | bc)
val=$(echo "${usedfull}/${totalfull}" | bc -l)
if (( $(echo "$val < ${warn}" | bc -l) )); then
rval=0
rmsg="OK"
elif (( $(echo "$val < ${crit}" | bc -l) )); then
rval=1
rmsg="WARNING"
else
rval=2
rmsg="CRITICAL"
fi
critfull=$(echo ${totalfull}\*${crit} | bc -l | awk '{ print int($1+0.5) }')
warnfull=$(echo ${totalfull}\*${warn} | bc -l | awk '{ print int($1+0.5) }')
minfull=0
maxfull=${totalfull}
unitfull="KiB"
used100=$(printf %.1f $(echo ${val}\*100 | bc -l))
crit100=$(printf %.1f $(echo ${crit}\*100 | bc -l))
warn100=$(printf %.1f $(echo ${warn}\*100 | bc -l))
min100=0
max100=100
unit100="%"
echo "MEMORY ${rmsg} - Used: ${usedfull} Available: ${availfull} Total: ${totalfull}|mem=${usedfull}${unitfull};$warnfull;$critfull;$minfull;$maxfull mem%=${used100}${unit100};$warn100;$crit100;$min100;$max100"
exit $rval