Amephist

init.d httpd script para usar con monit

by admin on Jun.17, 2010, under Scripts

Monit es una excelente herramienta para controlar y mantener a raya los servicios de un servidor. Este lindo daemon se encarga de supervisar el sistema y puede accionar eventos ante determinados patrones; nosotros en particular lo usamos para que nuestros servicios httpd no terminen por colapsar el servidor. Esto funcionaba en el 70% de las veces puesto que cuando el servidor realmente tenia mucha carga monit reiniciaba el servicio usando el script standard en init.d y este no es lo suficientemente completo como esperar a que el sistema estuviera limpio antes de volver a levantar httpd; lo cual bloqueaba los semáforos de sistema o no generaba un PID correcto. Como resultado de esto, en un extraño pero factible 30% de las veces monit colapsaba y no comprendía porque su orden no se ejecutaba correctamente. No encontré solución alguna por ningún lado, monit no esta pensado para ser niñera del proceso que se encarga de reiniciar el servicio, no es su culpa sino del script que esta en init.d. Es por ese motivo que les presento una versión un tanto agresiva que reemplaza nuestros /etc/init.d/httpd , esta versión no levanta el proceso hasta asegurarse que el anterior ha finalizado y limpia semáforos para que realmente quede limpio el sistema.

#!/bin/bash
#
# httpd        Startup script for the Apache HTTP Server
#
# chkconfig: - 85 15
# description: The Apache HTTP Server is an efficient and extensible  \
#	       server implementing the current HTTP standards.
# processname: httpd
# config: /etc/httpd/conf/httpd.conf
# config: /etc/sysconfig/httpd
# pidfile: /var/run/httpd.pid
#
### BEGIN INIT INFO
# Provides: httpd
# Required-Start: $local_fs $remote_fs $network $named
# Required-Stop: $local_fs $remote_fs $network
# Should-Start: distcache
# Short-Description: start and stop Apache HTTP Server
# Description: The Apache HTTP Server is an extensible server
#  implementing the current HTTP standards.
### END INIT INFO

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

if [ -f /etc/sysconfig/httpd ]; then
        . /etc/sysconfig/httpd
fi

# Start httpd in the C locale by default.
HTTPD_LANG=${HTTPD_LANG-"C"}

# This will prevent initlog from swallowing up a pass-phrase prompt if
# mod_ssl needs a pass-phrase from the user.
INITLOG_ARGS=""

# Set HTTPD=/usr/sbin/httpd.worker in /etc/sysconfig/httpd to use a server
# with the thread-based "worker" MPM; BE WARNED that some modules may not
# work correctly with a thread-based MPM; notably PHP will refuse to start.

# Path to the apachectl script, server binary, and short-form for messages.
apachectl=/usr/sbin/apachectl
httpd=${HTTPD-/usr/sbin/httpd}
prog=httpd
pidfile=${PIDFILE-/var/run/httpd.pid}
service_pid=/var/run/httpd_service_stopping.pid
lockfile=${LOCKFILE-/var/lock/subsys/httpd}
RETVAL=0

# The semantics of these two functions differ from the way apachectl does
# things -- attempting to start while running is a failure, and shutdown
# when not running is also a failure.  So we just do it the way init scripts
# are expected to behave here.
start() {
	while : ; do
		if [ -e $service_pid ]; then
			sleep 1
		else
			break
		fi
	done

        echo -n $"Starting $prog: "
        LANG=$HTTPD_LANG daemon --pidfile=${pidfile} $httpd $OPTIONS
        RETVAL=$?
	echo
        [ $RETVAL = 0 ] && touch ${lockfile}
        return $RETVAL
}

# When stopping httpd a delay of >10 second is required before SIGKILLing the
# httpd parent; this gives enough time for the httpd parent to SIGKILL any
# errant children.
stop() {
        touch $service_pid
        echo -n $"Stopping $prog: "
        killproc -p ${pidfile} -d 10 $httpd
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
        #ADDED :d
	while : ; do
		if ps ax | fgrep -v fgrep | fgrep $httpd > /dev/null
		then
    			echo "$prog running, kill kill kill"
    			killall -9 $httpd
    			sleep 1
		else
    			rm $service_pid
    			break
		fi
	done
	for i in `ipcs -s | awk '/httpd|nobody|apache/ {print $2}'`; do (ipcrm -s $i); done
}
reload() {
    echo -n $"Reloading $prog: "
    if ! LANG=$HTTPD_LANG $httpd $OPTIONS -t >&/dev/null; then
        RETVAL=$?
        echo $"not reloading due to configuration syntax error"
        failure $"not reloading $httpd due to configuration syntax error"
    else
        killproc -p ${pidfile} $httpd -HUP
        RETVAL=$?
    fi
    echo
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
        status $httpd
	RETVAL=$?
	;;
  restart)
	stop
	start
	;;
  condrestart)
	if [ -f ${pidfile} ] ; then
		stop
		start
	fi
	;;
  force-reload|reload)
        reload
	;;
  graceful|help|configtest|fullstatus)
	$apachectl $@
	RETVAL=$?
	;;
  *)
	echo $"Usage: $prog {start|stop|restart|condrestart|reload|status|fullstatus|graceful|help|configtest}"
	RETVAL=3
esac

exit $RETVAL

No es la mejor solución pero funciona. El script es para CentOS 5.x, con pocos cambios debería funcionar en otras distribuciones. Pueden descargarlo desde aquí.

:, ,

1 Comment for this entry

  • miguel antonio

    hola soy de mexico y manejo la venta de tiempo aire de celulares, vi tu comentario que trabajas para una compañia de servicios de prepago electronico.

    podrais ayudarme ($$$) a hacer un multinivel tengo los protocolos

    saludos

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Archives

All entries, chronologically...