En una entrada anterior ya explicamos brevemente el funcionamiento de Nagios para monitorizar el estado de nuestros servidores y servicios, y recibir alertas ante cualquier problema detectado.
También hablamos del software NRPE (Nagios Remote Plugin Executor) que complementaba el uso de Nagios para poder realizar los chequeos internamente. Es decir, Nagios no sólo comprueba el servicio desde fuera (conectándose al servicio), sino que puede conectarse al software NRPE del servidor chequeado, y una vez dentro realiza comprobaciones internas utilizando cualquier lenguaje de programación o scripting.
Utilizando estas dos herramientas tenemos un completo sistema de monitorización que nos avisa casi inmediatamente de cualquier error que se produzca. De esta manera reducimos los tiempos de caída de nuestros servicios, al detectar los problemas con mayor rapidez.
Además, con Nagios, podemos ir un poco más allá y configurarlo de tal manera que sea el propio Nagios (con ayuda de NRPE) el que responda automáticamente ante un problema de un servicio, y esté programado para resolverlo inmediatamente de manera desatendida.
Para ello Nagios necesita configurar los ‘eventhandlers‘ (manejadores de eventos), que ante errores detectados se comunicará con NRPE y realizará las operaciones oportunas para solucionar el problema (por ejemplo reiniciando el servicio afectado).
Por ejemplo, podemos chequear el servicio Web de Apache con Nagios, si se detecta un problema (por ejemplo, que no responda el servicio), Nagios llamaría al eventhandler correspondiente (lo tendremos configurado en el propio chequeo del servicio), y éste realizaría la conexión al servidor Web vía NRPE, y ejecutaría el script indicado (previamente configurado tanto en el NRPE como su llamada en el eventhandler) para realizar la tarea de recuperación, que en este caso reiniciaría el servicio Apache.
¿Cómo configurar este ejemplo?
(a) Primero definimos el chequeo de Nagios para el servicio Apache ‘check_http’, en el que se ha añadido una llamada al eventhadler ‘restart-http’:
define service { host_name Servidor service_description Apache check_command check_http!servidor.eps.ua.es event_handler restart-http use generic-service }
(b) Nagios tendrá una definición del eventhandler ‘restart-http’ en su fichero ‘command.cfg’ para saber dónde localizarlo y cómo llamarlo (‘restart-http’ es un script ‘eventhandler’ localizado en el directorio ‘/usr/share/nagios3/plugins/eventhandlers’):
define command { command_name restart-http command_line /usr/share/nagios3/plugins/eventhandlers/restart-http $SERVICESTATE$ $SERVICESTATETYPE$ $SERVICEATTEMPT$ $HOSTADDRESS$ }
(c) Este es el código de ‘restart-http’ (en caso de error grave se conecta mediante NRPE, con el plugin ‘/usr/lib/nagios/plugins/check_nrpe’ al servidor con problemas, llamando al script ‘restart-http’, que tendrá que estar configurado en el NRPE del servidor problemático):
#!/bin/sh # # Event handler script for starting the HTTP servers # # Note: This script will only restart the server if the service is # retried 3 times (in a "soft" state) or if the service somehow # manages to fall into a "hard" error state. # # # What state is the service in? case "$1" in OK) # The service just came back up, so don't do anything... ;; WARNING) # We don't really care about warning states, since the service # is probably still running... ;; UNKNOWN) # We don't know what might be causing an unknown error, # so don't do anything... ;; CRITICAL) # Aha! The service appears to have a problem - perhaps we should # start the server... # Is this a "soft" or a "hard" state? case "$2" in # We're in a "soft" state, meaning that Nagios is in the middle of retrying the # check before it turns into a "hard" state and contacts get notified... SOFT) # What check attempt are we on? We don't want to restart the # server on the first check, because it may just be a fluke! case "$3" in # Wait until the check has been tried 3 times before restarting the server. # If the check fails on the 4th time (after we restart the server), the state # type will turn to "hard" and contacts will be notified of the problem. # Hopefully this will restart the server successfully, so the 4th check # will result in a "soft" recovery. # If that happens no one gets notified because we fixed the problem! 3) echo -n "Starting HTTP service in $4 (3rd soft critical state)..." # Call the init script to start the server /usr/lib/nagios/plugins/check_nrpe -H "$4" -c restart-http ;; esac ;; # The service somehow managed to turn into a hard error without getting fixed. # It should have been restarted by the code above, but for some reason it didn't. # Let's give it one last try, shall we? # Note: Contacts have already been notified of a problem with the service at this # point (unless you disabled notifications for this service) HARD) echo -n "Starting HTTP service in $4..." # Call the script to start the server /usr/lib/nagios/plugins/check_nrpe -H "$4" -c restart-http ;; esac ;; esac exit 0
(d) En el servidor chequeado, NRPE tendrá configurada la etiqueta ‘restart-http’ con las acciones a realizar (en este caso, la llamada al NRPE con la etiqueta ‘restart-http’ parará el servidor Apache y lo volverá a arrancar):
command[restart-http]=sudo /etc/init.d/apache2 stop > /dev/null 2> /dev/null;sudo /etc/init.d/apache2 start
De esta manera podremos automatizar todas las resoluciones de problemas: unas serán tan sencillas como el reinicio del servicio, y otras posiblemente requieran de la llamada a un script que realice varias comprobaciones antes de determinar la causa del problema y actuar en consecuencia.
La automatización en las resoluciones de problemas aumentará la disponibilidad de nuestros servicios al reducir el tiempo de caída. Hay que tener en cuenta que a pesar de Nagios y los eventhandlers, si el servicio sufre un daño de difícil reparación (software o hardware) permanecerá caído hasta la resolución del problema. Para evitar este tipo de caídas en el servicio habrá que poner en práctica otras soluciones de alta disponibilidad como DRBD y Hearbeat
2 Replies to “Alta disponibilidad con Nagios”