#! /bin/sh
 #
 # This file is part of the Anotatornia suite.
 # 
 # Copyright © 2007, 2008, 2009, 2010 by Instytut Podstaw Informatyki
 # Polskiej Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 # Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 # 
 # This file may be distributed and/or modified under the terms of the
 # GNU General Public License version 3 as published by the Free Software
 # Foundation and appearing in the file COPYING included in the packaging
 # of this file.  (See http://www.gnu.org/licenses/translations.html for
 # unofficial translations.)
 # 
 # A commercial license is available from IPI PAN (contact
 # Michal.Ciesiolka.waw.pl or ipi.waw.pl for more
 # information).  Licensees holding a valid commercial license from IPI
 # PAN may use this file in accordance with that license.
 # 
 # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 # THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 # PURPOSE.
 #


Anotatornia_dir=/home/natror/anotatornia
mongrel_script=mongrels-anotatornia
port_AP=8000
port_AP2=8002
port_EH=8001

while true; do
    for p in $port_AP $port_AP2 $port_EH; do
	if [ -f $Anotatornia_dir/log/$mongrel_script.$p.pid ] ; then
	    mongrel_pid=`cat $Anotatornia_dir/log/$mongrel_script.8000.pid`
	    if [ -d /proc/$mongrel_pid ] ; then
		mongrel_mem=`ps --no-headers -o vsz $mongrel_pid`
		mongrel_cpu=`ps --no-headers -o cp $mongrel_pid`
# `cat /proc/$mongrel_pid/status | grep VmSize| perl -ne '/ (\d+) /; print $1'`
		if [ $mongrel_mem -gt 199000 ] ; then 
		    date
		    echo mongrel_mem: $mongrel_mem kB
		    $Anotatornia_dir/$mongrel_script  restart
		fi
		if [ $mongrel_cpu -gt 777 ] ; then 
		    date
		    echo mongrel_cpu: $mongrel_cpu kB "I'm killing it"
		    $Anotatornia_dir/$mongrel_script  stop
		    sleep 3
		# czekamy czy Mongrele się zakończą
		    if [ -d /proc/$mongrel_pid ] ; then
			kill -9 $mongrel_pid
		    fi
		fi
	    else
		date
		echo mogrel padł
		$Anotatornia_dir/$mongrel_script  restart
	    # restart a nie start, żeby ubić tę drugą Anotatornię.
	    fi
	else
	    date
	    echo "mongrel zabity z usunięciem pliku pid (chyba O.K.)"
	    $Anotatornia_dir/$mongrel_script  restart
	fi
    done
    sleep 10
# sleep 5 zabijało Mongrele, kiedy się uruchamiały, zajmując 99,9% procesora przez dłużej niż 5 sekund.
done