Páginas: Anterior 1 2 3 Siguiente
Páginas: Anterior 1 2 3 Siguiente

Páginas: Anterior 1 2 3 Siguiente

Apache checker: un script comprobador de Apache en bash

13 02 2010
apache-checker-logo

La gestión de servidores es un tema apasionante, pero exige mucho control sobre los sistemas a administrar. Personalmente en la empresa de hospedaje que administro llamada Quijost necesitamos un riguroso control de los servicios para detectar cualquier mal funcionamiento o sobrecarga y obtener una solución de forma casi inmediata.

Uno de los principales problemas es la gestión de recursos de memoria en servidores con Apache y que por lo general suelen usar Cpanel.

Cpanel es un buen sistema de panel de administración, pero es muy exigente en recursos y a veces consume demasiada memoria llegando a colapsar sus propios procesos e invocando a daemons encargados de reiniciarlo.

El problema viene cuando Cpanel además provoca un mal funcionamiento de Apache o bien tenemos un exceso de consumo en servidor por algún efecto Barrapunto, Menéame, Digg, etc.

En esos casos Apache atenderá todas las peticiones posibles dada la memoria de la que dispongamos. Normalmente y como referencia unas 200 peticiones por segundo con 1 GB de RAM (aunque tened presente que esta cifra puede variar bastante según configuraciones y hardware).

Cuando el servidor se quede sin memoria, las peticiones no se atenderán incluso otros servicios como emails (exim) pueden colapsar. Para evitar estas situaciones, he desarrollado un script que se encarga de comprobar periodicamente mediante una tarea cron, los recursos del sistema, la disponibilidad de Apache y la memoria disponible en el servidor, para actuar en consecuencia y reiniciar si es necesario, además de notificar a los administradores y mantener un log.

El script llamado Apache Checker está escrito en bash y tiene el siguiente aspecto:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Apache Checker: a script for check resources on apache servers
# Author: Shakaran (http://www.shakaran.net)
# License: GPLv3
 
# For CentOs servers require bc and mutt:
# yum install bc
# yum install mutt
 
# Uses:
# Add this script to a cron's task with crontab -e
# For example: For run the checking every minute
# */1 * * * * /apache_check.sh &> /dev/null 
 
# Exit immediately if a simple command exits with a non-zero status
set -e
 
# Number of current apache2 processes.
N_CURRENT="$(ps aux | grep apache2 | wc -l)"
N_MIN="1"
DESTINY_EMAIL="your-server-admin-address@domain.com"
USER=`id -un` # For example: root
HOST=`hostname`
USERHOST=$USER@$HOST
 
THRESHOLD=90 # Max threshold for restart apache
TOTAL_MEMORY=$(free | grep "Mem:" | awk '{print $2}')
REMAINING_MEMORY=$(free | grep "Mem:" | awk '{print $4}')
CURRENT_MEMORY=$(echo "($REMAINING_MEMORY/$TOTAL_MEMORY)*100.0" | bc -l)
 
MAX_NPROCESS_APACHE=5
NPROCESS_APACHE=`ps fu $USERNAME  | awk '/processname/ { x++ } END{print x}'`
 
if [ "$N_CURRENT" -lt "$N_MIN" ]; then
    apachectl restart
    echo "$HOST: The Apache process is not working and it has been restarted."
    echo "$HOST: The Apache process is not working and it has been restarted." \
    >> /var/log/apache_restarter.log
    SUBJECT="Script Apache checker: start"
    echo "$HOST: The Apache process is not working and it has been restarted." | mutt -s "$SUBJECT" $DESTINY_EMAIL
fi 
 
ps -fea | grep "/usr/sbin/apache2"
if test ! $? -eq 0 then
    apachectl start
    echo "$HOST: Apache has stopped and it has been reactivated."
    echo "$HOST: Apache has stopped and it has been reactivated." \
    >> /var/log/apache_restarter.log
    SUBJECT="Script Apache checker: restart"
    echo "$HOST: Apache has stopped and it has been reactivated." | mutt $DESTINY_EMAIL
-s "$SUBJECT"
fi
 
if [ $CURRENT_MEMORY -gt $THRESHOLD ]; then
    apachectl restart
    echo "$HOST: Restarted apache on `date +'%Y-%m-%d %H:%M:%S'`. RAM utilization at
${CURRENT_MEMORY}%"
    echo "$HOST: Restarted apache on `date +'%Y-%m-%d %H:%M:%S'`. RAM utilization at
${CURRENT_MEMORY}%" \
    >> /var/log/apache_restarter.log
    echo "Restarted apache on `date +'%Y-%m-%d %H:%M:%S'`. RAM utilization at
${CURRENT_MEMORY}%" \
    >> /var/log/apache_restarter.log
    SUBJECT="Script Apache checker: restart"
    echo "$HOST: Restarted apache on `date +'%Y-%m-%d %H:%M:%S'`. RAM utilization at
${CURRENT_MEMORY}%" | mutt $DESTINY_EMAIL -s "$SUBJECT"
fi
 
if [ `ps fu $USERNAME  | awk '/processname/ { x++ } END{print x}'`>
$MAX_NPROCESS_APACHE] then
    echo "$HOST: max number of apache process = ${MAX_NPROCESS_APACHE} `date
+'%Y-%m-%d %H:%M:%S'`. RAM utilization at ${CURRENT_MEMORY}% "
    echo "$HOST: max number of apache process = ${MAX_NPROCESS_APACHE} `date
+'%Y-%m-%d %H:%M:%S'`. RAM utilization at ${CURRENT_MEMORY}% " \
    >> /var/log/apache_restarter.log
    SUBJECT="Script Apache checker: max number of apache process"
    echo "$HOST: max number of apache process = ${MAX_NPROCESS_APACHE} `date
+'%Y-%m-%d %H:%M:%S'`. RAM utilization at ${CURRENT_MEMORY}% " | mutt $DESTINY_EMAIL
-s "$SUBJECT"
fi

El script esta basado en bash y ha sido probado en servidores GNU/Linux CentOs 5.4, pero debería funcionar en cualquier distribución que soporte bash. Como únicos requisitos necesita tener instalados los programas mutt (para enviar correo) y bc (para calcular datos). En CentOs puedes instalarlos con:

?Descargar instalar.txt
1
# yum install bc mutt

Además para su instalación necesitas añadir una tarea cron que ejecute el script periodicamente, por ejemplo para cada minuto, abre tu editor de cron con:

?Descargar editar.txt
1
# crontab -e

Y suponiendo que pones el script en / escribe:

1
*/1 * * * * /apache_check.sh &> /dev/null

Nota: se asume que el usuario que ejecuta el script tiene permisos de ejecución para Apache y programas bc y mutt que se utilizan (normalmente root), de lo contrario no funcionará correctamente.

¿como funciona?

El script necesita que configures una dirección de envío para los mails de notificación, que puedes cambiar en el valor de la variable DESTINY_EMAIL.

La primera comprobación que hace el script es para evitar ataques DDOS en los que se intentan que Apache haga muchos procesos hijos y sature el servidor (esto puede ser limitado en Apache) pero por si hubiese alguna manera de que el atacante lo incrementara o superase, el script reiniciará apache en caso de que haya muchos procesos y de esta manera se pueda liberar memoria. Para establecer el numero minimo y máximo, se pueden configurar las variables N_MIN y MAX_NPROCESS_APACHE respectivamente.

La segunda comprobación consiste en comprobar si apache esta funcionando, por si hubiese colapsado podamos volverlo a su ejecución normal.

La tercera comprobación establece un límite de consumo de memoria en el servidor, para que en tal caso (suponiendo que es Apache en que la consume) se reinicie apache y se liberen recursos. Por defecto este limite es el 90% de memoria del servidor y puede ser cambiado con la variable THRESHOLD.

De esta manera se puede conseguir tener un servidor un poco más optimizado al uso de memoria y tener constancia de cuando se producen picos debidos a Apache.

El script lo libero con licencia GPLv3 para todos aquellos que lo necesiten y quieran hacer uso de él.

Puedes descargarlo comprimido aquí: Apache Checker (78)

Todas la mejoras, sugerencias, fallos y críticas son bien recibidas.

VN:F [1.9.13_1145]
Rating: 10.0/10 (2 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)


Solucionar error con subversion: Missing Dependency: perl(URI) >= 1.17 is needed by package subversion-1.4.2-4.el5_3.1.x86_64

25 11 2009
cpanel-whm

Si usas CPanel con Centos 5.4 y necesitas instalar subversion probablemente te aparezca un error de dependencias al ejecutar:

1
# yum install subversion

Con salida:

?Descargar salida.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * addons: centosu.centos.org
 * base: centosy3-msync-dvd.centos.org
 * extras: centosu.centos.org
 * updates: centosv.centos.org
addons                                                   |  951 B     00:00     
base                                                     | 2.1 kB     00:00     
extras                                                   | 1.1 kB     00:00     
updates                                                  | 1.9 kB     00:00     
Excluding Packages in global exclude list
Finished
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package subversion.i386 0:1.4.2-4.el5_3.1 set to be updated
--> Processing Dependency: perl(URI) >= 1.17 for package: subversion
--> Processing Dependency: neon >= 0.25.5-6.el5 for package: subversion
--> Processing Dependency: libneon.so.25 for package: subversion
--> Processing Dependency: libapr-1.so.0 for package: subversion
--> Processing Dependency: libaprutil-1.so.0 for package: subversion
---> Package subversion.x86_64 0:1.4.2-4.el5_3.1 set to be updated
--> Processing Dependency: perl(URI) >= 1.17 for package: subversion
--> Running transaction check
---> Package apr.i386 0:1.2.7-11.el5_3.1 set to be updated
---> Package apr-util.i386 0:1.2.7-7.el5_3.2 set to be updated
--> Processing Dependency: libpq.so.4 for package: apr-util
---> Package neon.i386 0:0.25.5-10.el5_4.1 set to be updated
---> Package neon.x86_64 0:0.25.5-10.el5_4.1 set to be updated
---> Package subversion.i386 0:1.4.2-4.el5_3.1 set to be updated
--> Processing Dependency: perl(URI) >= 1.17 for package: subversion
---> Package subversion.x86_64 0:1.4.2-4.el5_3.1 set to be updated
--> Processing Dependency: perl(URI) >= 1.17 for package: subversion
--> Running transaction check
---> Package postgresql-libs.i386 0:8.1.18-2.el5_4.1 set to be updated
---> Package subversion.i386 0:1.4.2-4.el5_3.1 set to be updated
--> Processing Dependency: perl(URI) >= 1.17 for package: subversion
---> Package subversion.x86_64 0:1.4.2-4.el5_3.1 set to be updated
--> Processing Dependency: perl(URI) >= 1.17 for package: subversion
--> Finished Dependency Resolution
subversion-1.4.2-4.el5_3.1.x86_64 from base has depsolving problems
  --> Missing Dependency: perl(URI) >= 1.17 is needed by package subversion-1.4.2-4.el5_3.1.x86_64 (base)
subversion-1.4.2-4.el5_3.1.i386 from base has depsolving problems
  --> Missing Dependency: perl(URI) >= 1.17 is needed by package subversion-1.4.2-4.el5_3.1.i386 (base)
Error: Missing Dependency: perl(URI) >= 1.17 is needed by package subversion-1.4.2-4.el5_3.1.i386 (base)
Error: Missing Dependency: perl(URI) >= 1.17 is needed by package subversion-1.4.2-4.el5_3.1.x86_64 (base)
 You could try using --skip-broken to work around the problem
 You could try running: package-cleanup --problems
                        package-cleanup --dupes
                        rpm -Va --nofiles --nodigest
The program package-cleanup is found in the yum-utils package.

Y si pruebas a instalar el paquete de perl desde los repositorios, te dirá que esta actualizado:

?Descargar yum-perl.txt
1
2
3
4
5
6
7
8
9
10
11
# yum install perl
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * addons: centosu.centos.org
 * base: centosy3-msync-dvd.centos.org
 * extras: centosu.centos.org
 * updates: centosb2.centos.org
Excluding Packages in global exclude list
Finished
Setting up Install Process
Nothing to do

No te preocupes, tiene fácil solución. Bajaremos los paquetes de la versión 1.35 y lo instalaremos solventando el error:

?Descargar wget-perl.txt
1
# wget http://yum.trixbox.org/centos/5/RPMS/perl-URI-1.35-3.noarch.rpm

Instalamos el paquete de Perl usando el comando:

1
# rpm -i perl-URI-1.35-3.noarch.rpm

Ahora, prueba a instalar subversion y ya no tendrás el problema anterior:

1
# yum install subversion
VN:F [1.9.13_1145]
Rating: 7.5/10 (4 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)


Como reiniciar CPanel – Solucionar error: cpsrvd failed. A restart was attempted automagicly.

14 11 2009
cpanel-whm

Si es la primera vez que ves un mensaje similar a este:

?Descargar fallo.txt
1
2
3
4
cpsrvd failed @ Sat Nov  14 10:54:13 2009. A restart was attempted  automagically.
 Service Check Method:  [tcp connect]
 
 Failure Reason: Unable to connect to port 2086

Puede que estes algo confuso. ¿que diablos es cpsrvd? ¿porqué falla? ¡eso no puede ser bueno! ¿Reinicio? ¿funciono? ¿perdí algún dato? ¿está algo roto? ¿es “automagically” una palabra?

La buena noticia es que no te preocupes, no es una gran tragedia. cpsrvd es parte de los servicios de Cpanel, más específicamente mantiene el demonio de servicios de cPanel y realmente es muy común que falle. De hecho la mayoría de fallos que se producen en cPanel mantienen un pequeño script de reinicio para los casos en que sufren algun cuelgue.

En consecuencia, si este reinicio no se produce adecuadamente, no podrás tener acceso a tu cPanel y por tanto solo tendrás acceso mediante la consola o shell, por lo que puedes solucionarlo introduciendo el siguiente comando que reiniciara el demonio de cPanel:

1
/etc/init.d/cpanel restart

Una vez ejecutado, aparecerán una serie de mensajes indicando el proceso, una posible salida:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# /etc/init.d/cpanel restart 
Stopping tailwatchd:  2009-14-08 10:54:13 UTC [main] Current process '3508' stopped 
 [  OK  ] 
Stopping cPanel services:  Waiting for cpsrvd to shutdown ... ...Done 
Waiting for cpsrvd-ssl to shutdown ... ...Done 
 [  OK  ] 
Stopping cPanel dav services:  [Sat Nov  14 10:54:13 2009] Could not stop current process '5970' 
Waiting for cpdavd to shutdown ... ...Done 
Waiting for cpdavd-ssl to shutdown ... ...Done 
 [  OK  ] 
Stopping cPanel brute force detector services:  Waiting for cphulkd.pl to shutdown ... ...Done 
Waiting for cPhulkd to shutdown ... ...Done 
Waiting for cphulkd to shutdown ... ...Done 
 [  OK  ] 
Stopping pop3 services:  Waiting for cppop to shutdown ... ...Done 
Waiting for cppop-ssl to shutdown ... ...Done 
 [  OK  ] 
Stopping cPanel log services:                              [  OK  ] 
Stopping cPanel Chat services:                             [FAILED] 
Stopping Melange Chat services:                            [FAILED] 
Stopping InterChange services:                             [FAILED] 
Stopping cPanel ssl services:                              [  OK  ] 
Stopping mailman services:  Shutting down Mailman's master qrunner 
PID unreadable in: /usr/local/cpanel/3rdparty/mailman/data/master-qrunner.pid 
[Errno 2] No such file or directory: '/usr/local/cpanel/3rdparty/mailman/data/master-qrunner.pid' 
Is qrunner even running? 
mailmanctl: no process killed 
 [FAILED] 
Starting cPanel services:                                  [  OK  ] 
Starting cPanel brute force detector services:             [  OK  ] 
Starting cPanel dav services:                              [  OK  ] 
Starting cPanel Log services: ==> cPanel Log Daemon version 24.0 
 [  OK  ] 
Starting pop3 services: Waiting for cppop to shutdown ... ...Done 
Waiting for cppop-ssl to shutdown ... ...Done 
 [  OK  ] 
Starting cPanel Chat services:  
Starting Melange Chat services:  
Starting cPanel ssl services: Using Native SSL support (stunnel not needed) 
 [  OK  ] 
Starting mailman services:                                 [  OK  ] 
Starting tailwatchd: [Sat Nov  14 10:54:13 2009] Starting /usr/local/cpanel/libexec/tailwatchd daemon 
Log is at /usr/local/cpanel/logs/tailwatchd_log 
 [  OK  ]

Si eso no funciona, puedes intentar actualizando tu Cpanel (aviso: estos comandos aún no los he probado)

?Descargar update.txt
1
2
3
4
rm -f /usr/local/cpanel/cpanel 
/scripts/installgd 
/scripts/cleanmd5 
/scripts/upcp
VN:F [1.9.13_1145]
Rating: 8.5/10 (2 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)


Páginas: Anterior 1 2 3 Siguiente