CentOSにswatchをインストールして設定する

JavaのアプリケーションログとかにOutOfMemoryとか出たら、
デーモンが落ちる前にスケジューリングして再起動をかけないといけません。

アプリケーションログはswatchで監視します。

yum install swatch
yum install perl-File-Tail

mkdir -p /etc/swatch/conf
mkdir /var/log/swatch

vim /etc/rc.d/init.d/swatch
---
#!/bin/bash
#
# swatch
#
# chkconfig: 2345 90 35
# description: swatch start/stop script

# Source function library.
. /etc/rc.d/init.d/functions

PATH=/sbin:/usr/local/bin:/bin:/usr/bin

mkdir -p /var/log/swatch

start() {
    # Start daemons.
    ls /var/run/swatch_*.pid > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo -n "Starting swatch" 
        pno=0
        for conf in /etc/swatch/conf/*.conf
        do
            pno=`expr $pno + 1`
            WATCHLOG=`grep "^# logfile" $conf | awk '{ print $3 }'`
            swatch --config-file $conf --tail-file $WATCHLOG \
            --script-dir=/tmp --awk-field-syntax --use-cpan-file-tail --daemon \
            --pid-file /var/run/swatch_$pno.pid \
            --tail-args='--follow=name --retry -n 0' \
            >> /var/log/swatch/swatch.log 2>&1
            RETVAL=$?
            [ $RETVAL != 0 ] && return $RETVAL
        done
        echo
        [ $RETVAL = 0 ] && touch /var/lock/subsys/swatch
        return $RETVAL
    else
        echo "swatch is already started" 
    fi
}

stop() {
    # Stop daemons.
    ls /var/run/swatch_*.pid > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo -n "Shutting down swatch" 
        for pid in /var/run/swatch_*.pid
        do
           kill $(cat $pid)
           rm -f $pid
        done
        echo
        rm -f /var/lock/subsys/swatch /tmp/.swatch_script.*
    else
        echo "swatch is not running" 
    fi
}

status() {
    ls /var/run/swatch_*.pid > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo -n "swatch (pid" 
        for pid in /var/run/swatch_*.pid
        do
           echo -n " `cat $pid`" 
        done
        echo ") is running..." 
    else
        echo "swatch is stopped" 
    fi
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        stop
        start
        ;;
  status)
        status
        ;;
   *)
        echo "Usage: swatch {start|stop|restart|status}" 
        exit 1
esac

exit $RETVAL
---

chmod 744 /etc/rc.d/init.d/swatch

監視設定をおこないます
logfileでログファイルのパスを指定
throttleは連続してワードにひっかかったときに一気にアラートが飛ばないように間隔空けるものです。

vim /etc/swatch/conf/app.conf
---
# logfile /usr/local/play-app/dist/logs/application.log

watchfor /OutOfMemory/
  pipe "/path/to/script/alertmail.sh" 
  throttle=00:00:10
---
service swatch start
chkconfig swatch on