system-helpers/usr/local/bin/memory_usage_alert
Alexander Schäferdiek 71977c9dca
All checks were successful
continuous-integration/drone/push Build is passing
Fail properly in all scripts when required commands are not available
2023-01-25 09:42:22 +01:00

82 lines
2 KiB
Bash
Executable file

#!/usr/bin/env bash
# usage
usage() {
USAGE=$(cat <<EOF
Usage: memory_usage_alert [CONFIG_FILE (absolute path)]
Checks available memory and sends out notification via mail. Please see man memory_usage_alert.
EOF
)
echo "$USAGE";
}
set -e;
MEMORY_USAGE_ALERT_MAIL_ADDRESS="";
MEMORY_USAGE_ALERT_THRESHOLD=512;
# check for config file
apply_config() {
local config=$1;
if [[ ! -f "$config" ]]; then
echo "No config file specified";
echo "";
usage;
exit 1;
fi
set -a;
# shellcheck disable=SC1090
source "$config";
set +a;
}
source_config() {
local config=$1;
local configFallback=$2;
local configGlobalFallback=$3;
if [[ -f "$config" ]]; then
apply_config "$config";
return;
fi
if [[ -f "$configFallback" ]]; then
apply_config "$configFallback";
return;
fi
if [[ -f "$configGlobalFallback" ]]; then
apply_config "$configGlobalFallback";
return;
fi
}
check_required() {
type hostname &> /dev/null || { echo "Requiring 'hostname' but it's not installed"; exit 1; }
type mailx &> /dev/null || { echo "Requiring 'mailx' but it's not installed"; exit 1; }
type free &> /dev/null || { echo "Requiring 'free' but it's not installed"; exit 1; }
}
source_config "$1" "$HOME/.memory_usage_alert.conf" "/etc/memory_usage_alert.conf"
check_required
HOSTNAME=$(hostname)
SUBJECT="[memory $HOSTNAME] memory is low"
# DO NOT TOUCH BELOW
total=$(free -mt | grep Total | awk '{print $2}')
used=$(free -mt | grep Total | awk '{print $3}')
# shellcheck disable=SC2004
free=$(($total-$used))
if [[ "$free" -le $MEMORY_USAGE_ALERT_THRESHOLD ]]; then
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head >/tmp/top_proccesses_consuming_memory.txt
file=/tmp/top_proccesses_consuming_memory.txt
echo -e "Memory on $HOSTNAME is running low ($MEMORY_USAGE_ALERT_THRESHOLD MB is the remaining threshold)!\n\nFree memory: $free MB" | mailx -a "$file" -s "$SUBJECT" "$MEMORY_USAGE_ALERT_MAIL_ADDRESS"
fi
exit 0