プロセスがファイルの接触を停止した場合の警告通知の生成

プロセスがファイルの接触を停止した場合の警告通知の生成

プロセスが実行中かどうかをテストできるように、非常に簡単なスクリプトを設定しました。実行中の場合、ファイルに触れるとすべてが正常になります。しかし、プロセスが実行されておらず、ファイルに触れていない場合は、警告を設定できたらと思います。

pgrep "sleep" >/dev/null && touch monitor.log

このスクリプトは毎分 crontab で実行されます。ファイルをタッチしていないときに警告を表示する方法は必要ですか?可能ですか?

ありがとう

ベストアンサー1

これは簡単なファイル修正時間の確認です。複雑さは、主に1日に最大86,400の警告が表示される可能性があるという事実(通常、長い休日の週末にこれが起こる)と修正時間チェッカー(またはcronまたはシステム... .)の追加の複雑さです。 .) が実際に実行されており、ホストクロックが正しいか(virtの時間差、今後4年後のBIOSクロック、破損したNTPなど)。

#!/bin/sh

# what we're checking for mtime changes straying from the current system time
MONITOR=foofile
THRESHOLD=60

# use mtime on this file to avoid frequent alert spam should the above stop
# being updated
LAST_ALERT=barfile
LAST_ALERT_THRESHOLD=60

NOW_MTIME=`date +%s`

absmtimedelta() {
    delta=`expr $NOW_MTIME - $1`
    # absolute delta, in the event the mtime is wrong on the other side of
    # the current time
    echo $delta | tr -d -
}

alertwithlesscronspam() {
    msg=$1
    if [ ! -f "$LAST_ALERT" ]; then
        # party like it's
        touch -t 199912312359 -- "$LAST_ALERT"
    fi
    # KLUGE this stat call is unportable, but that's shell for you
    last_mtime=`stat -c '%Y' -- "$LAST_ALERT"`
    last_abs_delta=`absmtimedelta $last_mtime`
    if [ $last_abs_delta -gt $LAST_ALERT_THRESHOLD ]; then
        # or here instead send smoke signals, carrier pigeon, whatever
        echo $msg
        touch -- "$LAST_ALERT"
        exit 1
    fi
}

if [ ! -r "$MONITOR" ]; then
    alertwithlesscronspam "no file alert for '$MONITOR'"
fi

MONITOR_MTIME=`stat -c '%Y' -- "$MONITOR"`
ABS_DELTA=`absmtimedelta $MONITOR_MTIME`

if [ $ABS_DELTA -gt $THRESHOLD ]; then
    alertwithlesscronspam "mtime alert for '$MONITOR': $ABS_DELTA > $THRESHOLD"
fi

おそらく考慮してください標準モニタリングフレームワーク、ファイル変更時間の確認、またはそのためのプラグイン、カスタマイズ可能な警告、メトリック、上記よりも優れたコードなどをサポートできます。

おすすめ記事