【问题标题】:Restart Apache if average server load past minute is higher than X如果过去一分钟的平均服务器负载高于 X,则重新启动 Apache
【发布时间】:2019-11-15 00:22:27
【问题描述】:

我编写了一个 shell 脚本并将其添加到我的 cron 中。它应该每分钟运行一次并检查过去 1 分钟的平均服务器负载,如果超过 40,它应该记录负载、日期,然后重新启动 Apache httpd。这是我的脚本:

#!/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

如果我查看日志文件,我会看到以下内容:

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

显然有问题,因为它应该仅在负载超过 40 时记录并重新启动 Apache,但正如您从日志中看到的那样,负载为 9、7、6、5 和 5。有人能指出我正确的方向吗?

【问题讨论】:

    标签: bash shell cron sh


    【解决方案1】:

    这是 GNU awk 中的一个(GNU awk 由于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
    

    【讨论】:

      【解决方案2】:

      来自man bashCONDITIONAL EXPRESSIONS 部分(强调我的):

      字符串 1 > 字符串 2
      如果 string1 按字典顺序排序在 string2 之后,则为真。

      您要么想要使用[[-gt 运算符,要么使用算术评估而不是[[

      if (( chekk > 40 )); then
      

      【讨论】:

      • 谢谢,我试试看。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多