Tuesday 10 December 2013

Script to monitor tomcat service

 Hi all,

This is a small script which could be used to monitor tomcat service is webserver to prevent down time if the tomcat service goes down. It helped me once to maintain the tomcat service in running status for a customer who had problem with tomcat service going down intermittently.

Script
-------------------------------------------------------------------------------------------------------------------------------
#!/bin/bash
#

CHECK_URL="http://example.com/index.jsp"
CHECK_KEYWORD="synosure"
MAXTRIES=2
SLEEPTIME=1
LOGFILE=/var/log/tomcat_check.log
TOMCATSH=/etc/init.d/tomcat

### Functions -----------------------

# check for a few times
function checkTomcatUp {
_maxtries=$1
for (( i=0; i<${_maxtries}; i=i+1 ))
do
/usr/bin/curl -s -m 30 "${CHECK_URL}" | grep "${CHECK_KEYWORD}"
> /dev/null
if [ $? -eq 0 ]
then
exit 0
fi
sleep ${SLEEPTIME}
done
}

### ---------------------------------

checkTomcatUp ${MAXTRIES}

# perform tomcat restart
echo `date` "--- Restarting Tomcat ---" >> ${LOGFILE}

# stop tomcat
echo `date` "Stopping Tomcat..." >> ${LOGFILE}
#${TOMCATSH} stop

# wait a while, then check if really stopped
#sleep 2
pid=`ps auwwx |grep "org.apache.catalina.startup.Bootstrap" |grep -v
grep|awk '{print $2;}'`
while [ "X${pid}" != "X" ]
do
echo `date` "Killing Tomcat, PID=" ${pid} >> ${LOGFILE}
kill -9 ${pid}
sleep 2
pid=`ps auwwx |grep "org.apache.catalina.startup.Bootstrap" |grep -v
grep|awk '{print $2;}'`
done

# start tomcat
echo `date` "Starting Tomcat..." >> ${LOGFILE}
${TOMCATSH} start

# give tomcat some time to start background processes
sleep 5

# just do 1 more check
checkTomcatUp 1
echo `date` "Giving up... waiting for next cron" >> ${LOGFILE}

exit 1
-------------------------------------------------------------------------------------------------------------------------------

Brief of script:

 This script basically checks whether the website is up by using the curl command which will download the page like a normal browser in the command prompt (note that it will be in html format). Now i check for a key work of my choice in it. It could be any word included in your index page. The MAXTRIES variable in this example helps us to limit the no of checks done.



Learn & share
rzm


No comments:

Post a Comment