Kos Cos
Kos Cos

Reputation: 129

Restart Apache if average server load past minute is higher than X

I wrote a shell script and added it to my cron. It's supposed to run every minute and check for the average server load, past 1 minute, and if it's over 40 it should log the load, date and then restart Apache httpd. Here is my script:

#!/bin/bash
LOGFILE=/home/user/public_html/domain.com/cron/restart.log
function float_to_int() {
echo $1 | cut -d. -f1
}
check=$(uptime | awk -F' *,? *' '{print $12}')
now=$(date)
checkk=$(float_to_int $check)
if [[ $checkk > 40 ]]; then
        echo $now $checkk >> $LOGFILE 2>&1
        /usr/bin/systemctl restart httpd.service
fi

If I look at the log file I see the following:

Wed Jul 3 20:02:01 EDT 2019 70
Wed Jul 3 23:03:01 EDT 2019 43
Wed Jul 3 23:12:01 EDT 2019 9
Wed Jul 3 23:13:01 EDT 2019 7
Wed Jul 3 23:14:01 EDT 2019 6
Wed Jul 3 23:15:02 EDT 2019 5
Wed Jul 3 23:16:01 EDT 2019 5

Something is clearly wrong as it should only log and restart Apache if the load is over 40 but as you can see from the logs the load was 9, 7, 6, 5 and 5. Could someone point me in the right direction?

Upvotes: 1

Views: 428

Answers (2)

James Brown
James Brown

Reputation: 37404

Here's one in GNU awk (GNU awk due to strftime()):

awk '
$1 > 0.4 {                                          # interval above 0.4
    logfile="./log.txt"                             # my logpath, change it
    print strftime("%c"), $1 >> logfile             # date and load to log
    cmd="/usr/bin/systemctl restart httpd.service"  # command to use for restarting
    if((ret=(cmd|getline res)) !=0 )                # store return value and result
        print "failed: " ret                        # if failed
    else
        print "success"
}' /proc/loadavg                                    # getting load avg from /proc

Upvotes: 0

Aaron
Aaron

Reputation: 24812

From man bash, section CONDITIONAL EXPRESSIONS (emphasis mine) :

string1 > string2
True if string1 sorts after string2 lexicographically.

You will either want to use [['s -gt operator, or use arithmetic evaluation instead of [[ :

if (( chekk > 40 )); then

Upvotes: 2

Related Questions