Skip to content

Instantly share code, notes, and snippets.

@Slurpgoose
Created March 19, 2021 15:41
Show Gist options
  • Save Slurpgoose/d72745e59712256edd66426fc66df006 to your computer and use it in GitHub Desktop.
Save Slurpgoose/d72745e59712256edd66426fc66df006 to your computer and use it in GitHub Desktop.
check and restart process if server memory utilization is too high. this is designed to be a quick fix until the larger problem is diagnosed
#!/bin/sh
percent_allowed=85
memory_too_high(){
MAXMEM=$(free -m | grep -oP '\d+' | head -n 1) #total available memory
USEDMEM=$(free -m | awk 'NR==2{printf "%s", $3,$2,$3*100/$2 }') # memory used
PERCENTAGE=$(echo "scale=8; ($USEDMEM / $MAXMEM) * 100" | bc) # get percentage
P_INT=${PERCENTAGE%.*} # convert from float to int
echo memory allocation: $P_INT'%'
result=$(( P_INT < percent_allowed)) # 1 if memory is too high
return $result
}
if memory_too_high ;
then
echo "memory allocation is too high... killing all node processes"
killall node;
sleep 1s
/usr/local/bin/pm2 status
sleep 1s
/usr/local/bin/pm2 start path/to/script
else
echo "no issues"
fi
~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment