Last active
July 9, 2022 06:25
-
-
Save matheusfillipe/e7aeb860ec8e55e7f85b56770e1d0c55 to your computer and use it in GitHub Desktop.
Auto restart process on high cpu or if check command is failing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# YPTSOCKET | |
TOP=20 | |
YPTSOCKET=/var/www/html/AVideo/plugin/YPTSocket/server.php | |
MAXCPU=80.0 | |
CPUSERVICE=ytsocket.service | |
# APACHE | |
TIMEOUT=2 | |
CHECK_CMD="curl --silent https://alive528.com/" | |
SERVICE=apache2 | |
# Check for high cpu usage and auto restart yptsocket | |
ps ax --sort -"%cpu" -eo pid=,pcpu=,command= | head -$TOP | awk '{$1=$1};1' | while read -r line; do | |
pid="$(echo $line | awk '{print $1}')" | |
cpu="$(echo $line | awk '{print $2}')" | |
command="$(echo $line | cut -d' ' -f 3-)" | |
if (( $(echo "$cpu > $MAXCPU" | bc -l) )) && [[ "$command" == *"$YPTSOCKET"* ]]; then | |
date | |
echo "Restarting -----> pid = '$pid' cpu = '$cpu' cmd = '$command'" | |
sudo systemctl restart $CPUSERVICE & | |
fi | |
done | |
if [[ "$TIMEOUT" -eq 0 ]] | |
then | |
echo "Exiting because timeout is set to 0" | |
exit 0 | |
fi | |
if ! systemctl is-active --quiet $SERVICE | |
then | |
echo "Exiting because $SERVICE is not running" | |
exit 1 | |
fi | |
# Check if command times out then restart apache | |
timeout $TIMEOUT $CHECK_CMD >> /dev/null | |
if (( $? == 124 )) | |
then | |
date | |
echo "Restarting $SERVICE" | |
sudo systemctl restart $SERVICE | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment