KeepAlive Script

I was looking for a script to monitor and insure that Tomcat was active. I came across this script by Mahesh at https://serverfault.com/questions/608776/how-to-monitor-tomcat-application-and-restart-if-not-running. It can probably be modified to monitor any process you’d like.

        
#!/bin/bash

TOMCAT_HOME=/opt/tomcat
PUBLIC_IP=`wget http://ipecho.net/plain -O - -q ; echo`
EMAIL_BODY="Hi Admin,\n\n$PUBLIC_IP Tomcat is down at $(date -d "+330 minutes" +"%Y-%m-%d %T") IST, Please take necessary action.\n\n\nDo not reply to this email as it is auto generated by Ubuntu system\n"

tomcat_pid() {
  echo `ps aux | grep org.apache.catalina.startup.Bootstrap | grep -v grep | awk '{ print $2 }'`
}

start() {
  pid=$(tomcat_pid)
  if [ -n "$pid" ] 
  then
    echo "Tomcat is already running (pid: $pid)"
  else
    # Start tomcat
    echo "Starting tomcat"
    /bin/sh $TOMCAT_HOME/bin/startup.sh
  fi


  return 0
}

pid=$(tomcat_pid)

 if [ -n "$pid" ]
  then
    echo "Tomcat is running with pid: $pid"
    #stop
  else
    echo "Tomcat is not running"
    # send an email alert then start
    echo -e $EMAIL_BODY | mail -s "$PUBLIC_IP Tomcat is down" user@email.com
    echo "Mail sent"
    #remove cache and release memory occupied by heavy processes
    start
  fi
exit 0