Copyright (c) 2.007 Jos� Angel de Bustos P�rez <jadebustos@augcyl.org>
.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".
Tabla de contenidos
Lista de tablas
Tabla de contenidos
Clustering es la capacidad de varias m�quinas para realizar una tarea como s� de una �nica m�quina se tratase.
Cada una de las m�quinas que forman el cluster recibe el nombre de nodo.
Cluster como un todo.
Dependiendo del tipo de soluci�n que busquemos podemos clasificar los clusters en varios tipos:
High Performance Cluster
Activo / Pasivo
Activo / Activo
Grid Computing
Este tipo de clusters son clusters para c�lculo matem�tico intensivo.
Un ejemplo es el Marenostrum que IBM tiene en Espa�a.
En este tipo de cluster solamente hay un nodo que da servicio, el resto estan inactivos.
En el momento que el nodo activo no pueda dar servicio, otro nodo se har� cargo del servicio.
En este tipo de cluster todos los nodos estan dando servicio.
Grid Computing se puede pensar c�mo una especializaci�n de un cluster activo/activo.
Este tipo de computaci�n distribuida se basa en la utilizaci�n de los recursos de diferentes ordenadores, no necesariamente en la misma red. Pudiendo estar geogr�ficamente dispersos.
Este tipo de sistemas est�n pensados para utilizar los recursos de cientos de ordenadores que no est�n siendo utilizados.
Por ejemplo, es com�n que en una empresa o una instituci�n haya multitud de ordenadores encendidos que no est�n siendo utilizados. A la hora de comer, de los caf�s, durante reuniones, ..., los caf�s, ...
Se puede utilizar esa potencia para la incrementar la potencia de c�lculo de un conjunto de m�quinas dedicadas al completo a la realizaci�n de una determinada tarea.
Hay diferentes formas de uso:
Uso de recursos cuando el equipo no est� siendo utilizado.
Uso m�nimo de recursos y siempre en funci�n del uso del equipo por parte del usuario.
Tabla de contenidos
El prop�sito de un cluster es:
Redundancia frente a fallos (alta disponibilidad).
Aumento de potencia (escalabilidad).
Estos prop�sitos no son excluyentes.
A la hora de escoger que tipo de cluster se va a utilizar hay que tener en cuenta las caracter�sticas que nos ofrece cada tipo y cual es el que mas encaja en nuestro entorno.
Alta disponibilidad es la capacidad para ofrecer un servicio cuando el servidor que lo ofrece deja de funcionar.
La alta disponibilidad es ofrecida por todos los tipos de cluster.
Garantizar la alta disponibilidad requiere:
Una correcta configuraci�n del cluster.
Redundancia de hardware (red, almacenamiento, fuentes de alimentaci�n, ...).
Redundancia del sistema el�ctrico.
SAIs.
Nodos en diferentes CPDs.
La disponibilidad de los sistemas se clasifica con la regla de los 9s:
Bonding es una t�nica utilizada en GNU/Linux para utilizar dos tarjetas de red como si fueran una.
Es necesario que el n�cleo est� configurado para ello.
Los dispositivos de networking tienen que soportarlo.
Los datos son cr�ticos ya que sin ellos no se puede ofrecer el servicio. Existen dos t�cnicas para garantizar la alta disponibilidad en los sistemas de almacenamiento:
Sistemas de almacenamiento externo.
Ventajas:
Altamente escalable.
Rapidez, hasta 4 Gb/s.
Inconvenientes:
Precio.
Requiere personal especializado.
Replicaci�n de datos:
Ventajas:
Barato.
Inconvenientes:
Poco escalable.
"Lentitud".
La replicaci�n de datos se puede hacer utilizando slony.
MySQL utiliza NDB para la replicaci�n de datos.
Escalabilidad es la capacidad de crecimiento que tiene un servicio frente a la demanda.
La escalabilidad s�lo es ofrecida por:
High Performance Cluster.
Cluster Activo / Activo.
La escalabilidad se logra incrementando el n�mero de nodos disponibles en el cluster.
En un cluster activo / pasivo el incrementar el n�mero de nodos disponibles en el cluster no incrementa la potencia del cluster ya que unicamente un nodo estar� ofreciendo el servicio.
Escalabilidad de un cluster.
Un servicio de cluster consta de:
Balanceador de carga.
Sistema para la detecci�n de fallos en los nodos del cluster.
Servicio a clusterizar.
Recursos del cluster.
Fencing.
Arquitectura b�sica de un cluster.
S�lo son necesarios en aquellas configuraciones que sean Activo / Activo y/o balanceo de carga.
La funci�n de los balanceadores, tambi�n conocidos como network dispatcher es redireccionar las peticiones a los servidores que las est�n atendiendo.
Es necesario un sistema que detecte cuando existen nodos en el cluster que no est�n disponibles para ofrecer el servicio. En este caso no se enviar�n peticiones para ser atendidas si el cluster es Activo / Activo o no se balancear� el servicio sobre ellos si es Activo / Pasivo.
Para detectar esta situaci�n se utilizan dos t�cnicas:
Heartbeat.
Disco de quorum.
Son todos aquellos recursos necesarios para el servicio:
IP de servicio.
Filesystems.
Scripts para arrancar el servicio, ...
Tabla de contenidos
Se puede definir el balanceo de carga como la habilidad que tiene un servicio para repartir el trabajo a realizar entre varias m�quinas.
Arquitectura b�sica de un cluster con balanceo de carga.
Los balancearores pueden ser tanto hardware como software.
Los balancedares hardware son m�quinas con un prop�sito espec�fico y solo son �tiles para el balanceo de carga.
Los balanceadores software son servidores configurados para hacer balanceo.
Precio.
Una vez no sea necesario el balanceador o se requiera uno m�s potente se puede reciclar para otras tareas.
A partir de la version 9 de BIND nos bastaria simplemte con a�adir varias entradas "IN A", una para cada servidor, que apunten al mismo nombre, el del servidor que queremos balancear:
www IN A 192.168.0.100 www IN A 192.168.0.101 www IN A 192.168.0.102
Utilizando el comando "host" varias veces podemos ver como se balancean las peticiones dns:
[jadebustos@dedalo ~]$
host www.servidorbalanceado.es
www.servidorbalanceado.es has address 192.168.0.100 www.servidorbalanceado.es has address 192.168.0.101 www.servidorbalanceado.es has address 192.168.0.102
[jadebustos@dedalo ~]$
host www.servidorbalanceado.es
www.servidorbalanceado.es has address 192.168.0.101 www.servidorbalanceado.es has address 192.168.0.102 www.servidorbalanceado.es has address 192.168.0.100
[jadebustos@dedalo ~]$
host www.servidorbalanceado.es
www.servidorbalanceado.es has address 192.168.0.100 www.servidorbalanceado.es has address 192.168.0.101 www.servidorbalanceado.es has address 192.168.0.102
[jadebustos@dedalo ~]$
De esta forma cada vez que se haga una solicitud DNS para www.servidorbalanceado.es se resolver� con una IP diferente, ir� rotando.
Este sistema tiene varios inconvenientes:
El primero es que si un servidor cae el DNS no ser� consciente de ello y el cliente que obtenga la IP del servidor caido como respuesta a su solicitud encontrar� que el servicio no esta disponible.
El segundo inconveniente es que con las caches de DNS se cachear� permanente el nombre www.servidorbalanceado.es con una IP especifica, con lo cual todas las peticiones iran a esa IP y no habr� balanceo, pudiendo de esta forma estar uno o varios servidores sobrecargados y el resto muy ligeros.
Linux Virtual Server es una soluci�n para poder implementar un servidor virtual altamente escalable y en alta disponibilidad.
Esta soluci�n consiste en un balanceador de carga, tambi�n conocido como director, que ser� la m�quina que ser� accesible directamente para los clientes y luego tendremos los servidores que ser�n aquellos que recibiran las peticiones de los clientes, v�a el balanceador de carga, y responder�n a las peticiones.
Los servidores podr�n estar o bien en la misma red f�sica o en redes diferentes lo que permitir� el tener servidores en granjas distribuidas geogr�ficamente.
Esta soluci�n nos permitir� tener el servicio funcionando casi continuamente ya que no se ver� afectado por posibles ca�das de las m�quinas debido a fallos en el suministro el�ctrico o bien cortes en el ISP de una determinada granja. Cualquiera de estos fallos, u otros que pudieran ocurrir, afectar�n a una o varias granjas, pero nunca a todas con lo cual el servicio seguir�a funcionando aunque los clientes podr�an experimentar cierta demora en el servicio.
Para los clientes existir� un �nico servidor (el balanceador) que se encargar� de distribuir la carga entre los servidores reales.
La escalabilidad en el servicio la conseguiremos a�adiendo nodos, mientras que la disponibilidad se lograr� identificando el nodo o el balanceador que no funciona y reconfigurando el sistema de tal forma que el servicio no se vea interrumpido. Es decir no enviando peticiones a un nodo que no pudiera dar servicio en ese momento.
El balanceo lo podemos hacer de tres formas:
Mediante NAT
IP Tunneling
Direct Routing
NAT (Network Address Translation) es una t�cnica utilizada para que una m�quina reciba informaci�n dirigida a otra y esta pueda reenviarla a quien la solicit� inicialmente.
Para ello la m�quina que recibe la informaci�n, en forma de paquetes, deber� reescribir los paquetes sustituyendo su propia direcci�n con la de la m�quina que realiz� la petici�n (nos referimos a direcciones tanto f�sicas, MAC, como l�gicas, IP) una vez reescrito el paquete de la forma correcta el balanceador se encargar� de enviar los paquetes por la interface adecuada para que le lleguen al destino verdadero del paquete.
Cuando el balanceador reciba peticiones este sobreescribir� el paquete y pondr� la direcci�n de un servidor real, gracias a esto los servidores reales podr�n estar ejecutando cualquier sistema operativo que sea accesible v�a TCP/IP.
Cuando el servidor responda lo har� al balanceador y este reescribir� el paquete, otra vez, poniendo en los paquetes la direcci�n del cliente que solicit� la informaci�n.
LVS - NAT.
El balanceador guardar� los datos de todas las conexiones que balancee para luego devolver la respuesta al cliente adecuado.
Pero no todo son ventajas, esta sobreescritura de los paquetes trae consigo una carga de CPU que puede llegar a ser un cuello de botella. Adem�s tendremos que tener en cuenta cual es el ancho real de nuestra interface de red y tener presente que por el balanceador van a pasar tanto las peticiones hacia los servidores, como las respuestas de los servidores hacia los clientes.
Todos estos paquetes tendr�n que ser reescritos por el balanceador y aunque aumentemos la memoria o las capacidades de procesamiento del balanceador todav�a estaremos limitados por el ancho real de la interface ya que las respuestas de los servidores ocupar�n mas ancho de banda que las peticiones.
El problema del ancho de banda se podr� paliar utilizando las capacidades de Bonding del n�cleo de Linux.
No suele ser muy recomendable esta opci�n ya que los costes necesarios para desplegar la infraestructura suelen ser mayores que los de implementar LVS con IP Tunneling o Direct Routing.
El balanceador deber� tener dos IP una de cara a los posibles clientes (DIP) y otra en la red de los servidores (VIP), es decir que el balanceador deber� hacer funciones de enrutado con lo cual el n�cleo deber� estar configurado para ello y tendremos que tener el enrutado habilitado y el n�cleo tendr� que estar compilado para poder sobreescribir paquetes.
Para tener habilitado el enrutado es necesario que el n�cleo est� configurado para ello y necesitaremos que el fichero /proc/sys/net/ipv4/ip_forward
si utilizamos ipv4 o /proc/sys/net/ipv6/conf/all/forwarding
est�n a 1.
Los servidores en este caso estar�n en la misma red de VIP y tendr�n como gateway al balanceador de carga.
Utilizando NAT ten�amos un cuello de botella en el balanceador ya que tiene que reescribir y distribuir los paquetes del cliente al servidor y viceversa.
Utilizando IP Tunneling el balanceador �nicamente tendr� que hacerse cargo de las peticiones de los clientes y enviarlas a los servidores, siendo estos mismos los que responder�n a los clientes. De esta forma el balanceador de carga puede manejar mas nodos, es decir el servicio es mas escalable.
LVS - IP Tunneling.
Una vez el balanceador de carga tiene el paquete determina si pertenece a uno de los servicios que tiene balanceados. De ser as� encapsula el paquete en otro paquete y se lo env�a al servidor de destino. Es este el que se encarga de responder al cliente directametne sin pasar por el balanceador.
El balanceador guarda una tabla de conexiones y cuando le llega un paquete determina si ya existe una conexi�n abierta y de ser as� que servidor real es el que est� sirviendola para enviarle el paquete.
Encapsulamiento IP en IP-Tunneling.
Los servidores deber�n estar configurados para trabajar con IP Tunneling (encapsulation) ya que cuando el balanceador recibe un paquete para uno de los servidores este lo encapsula en un datagrama IP y lo manda a uno de los servidores. Cuando el servidor lo recibe tend� que desencapsularlo y responder� directamente al cliente sin pasar por el balanceador con lo cual los servidores tendr�n que estar conectados tanto al balanceador como a los clientes (en NAT s�lo con el balanceador).
No es necesario que los servidores est�n en la misma red, pueden estar geogr�ficamente distribuidos.
En esta configuraci�n surge el problema de ARP.
Al igual que en IP Tunneling el balanceador s�lo gestionar� las peticiones del cliente hac�a el servidor con lo cual es una soluci�n altamente escalable.
La direcci�n virtual (VIP) es compartida por el balanceador y los servidores. De esta manera el balanceador recibe las peticiones y las env�a a los servidores que procesan las peticiones y dan servicio directamente a los clientes.
LVS - Direct Routing.
En esta soluci�n es necesario que una de las interfaces del balanceador y los servidores est�n en el mismo segmento f�sico de red ya que el balanceador de carga cambiar� su direcci�n f�sica, MAC, en la trama por la direcci�n f�sica de uno de los servidores que tendr� un alias con la direcci�n VIP.
El balanceador guarda una tabla de conexiones y cuando le llega un paquete determina si ya existe una conexi�n abierta y de ser as� que servidor real es el que est� sirviendola para enviarle el paquete.
LVS - Direct Routing.
El alias se acostumbra a poner en el dispositivo de loopback.
En esta configuraci�n surge el problema de ARP.
Cuando utilizamos Tunneling o Direct Routing tanto el balanceador como los servidores comparten una direcci�n IP (VIP) y esto puede traer consigo problemas si los balanceadores y los servidores est�n en la misma red.
El modelo OSI de la ISO consta de 7 capas, las tres primeras son la capa f�sica, la capa de enlace de datos y la capa de red.
Cuando un ordenador transmite datos empieza a encapsular en la capa de aplicaci�n, s�ptima capa. Cuando llega a la capa de red a�ade la informaci�n de red, direcciones IP y direcciones l�gicas (origen y destino). Acto seguido a�ade su direcci�n f�sica o MAC que es una direcci�n �nica que tiene cada tarjeta de red o NIC y que consta de dos partes una que identifica al fabricante de la tarjeta y la otra parte identifica a la tarjeta.
Despu�s en la capa f�sica se traduce toda la informaci�n a se�ales el�ctricas y se transmite por el medio. Adem�s de sus direcciones propias IP y MAC se a�aden las direcciones del destinatario y si el paquete fuera destinado a una red diferente de la de partida se pondr�a en el campo de la MAC de destino la MAC de gateway o del router por defecto y este se ir�a encargando de enrutar el paquete hasta que llegar� al �ltimo router o gateway el cual cambiar�a su MAC por la MAC del equipo que tuviera la IP de destino del paquete. Este �ltimo router mandar�a el paquete por la interface correspondiente y todos los equipos en esa red desencapsular�n el paquete hasta la segunda capa y s�lo aquel cuya MAC este en esa trama, como destino, tomar� el paquete y lo desencapsulara entero para hacer uso de el.
Cuando utilizamos Tunneling o Direct Routing tenemos que tener en cuenta que los clientes hacen las peticiones al balanceador, pero sin embargo las respuestas las reciben de los servidores.
Tanto el balanceador de carga como los servidores comparten una IP (VIP), cuando un cliente solicita una conexi�n con VIP la petici�n se debe de hacer al balanceador, no a los clientes.
Cuando llega una petici�n de un cliente para el servicio bajo LVS esta llegar� desde fuera de la red, con lo cual el router de esa red har� una petici�n ARP para obtener la MAC de la m�quina con la IP VIP.
En esa red podr�a haber varias m�quinas con la IP VIP (el balanceador y los servidores comparten dicha IP) con lo cual cualquiera de ellas podr�a, y de hecho lo har�, responder a la petici�n. Pero el paquete deber� ir destinado al balanceador no a los servidores.
El balanceador registrar� en sus tablas a que servidor le manda las peticiones y consecuentemente todas las peticiones de ese cliente ir�n al mismo servidor, bajo la conexi�n ya establecida. Si uno de los servidores respondiera a la petici�n ARP el router tendr�a en su tabla ARP la direcci�n f�sica del servidor y todos los paquetes se los enviar� directamente al servidor sin utilizar el balanceador.
Si en alg�n momento se cambiar� la entrada en la tabla ARP y el router actualizar� con la MAC de otra m�quina (el balanceador y el resto de servidores tienen una interface o alias con la IP VIP) entonces las peticiones de ese cliente iran a otro servidor en lugar de al servidor que originariamente estaban yendo. Si esto pasa dentro de una misma conexi�n cuando un servidor empiece a recibir las solicitudes de una conexi�n que el no ha iniciado (la realiz� el servidor que primero respondi� a la petici�n ARP) la conexi�n se cerrar� y habr� que volver a negociarla.
Este problema se presenta con n�cleos a partir de la serie 2.2.x y se soluciona haciendo que la interface que tiene la IP VIP no responda a peticiones ARP en los servidores y si en el balanceador de carga. De esta forma nos aseguramos que cuando el router haga una petici�n ARP para la VIP la �nica m�quina que responda sea el balanceador y de esta forma todos los paquetes para el LVS ser�n enviados al balanceador y este har� su trabajo.
Hemos estado haciendo referencia a que el balanceador distribuir� las peticiones entre los servidores. Pero para que esta distribuci�n sea efectiva ha de ser planificada de alguna forma. A la hora de compilar el n�cleo en el balanceador tendremos que escoger que algoritmos vamos a utilizar para hacer el balanceo de carga.
Los algoritmos m�s interesantes son los siguientes:
Round-Robin. Este algoritmo es el m�s simple y lo que hace es distribuir las peticiones entre los servidores de tal manera que si hay 5 servidores y 100 peticiones cada servidor atender� a 20 peticiones.
El orden de distribuci�n de la carga ser� secuencial, primera petici�n hac�a el primer servidor, segunda al segundo, ..., quinta al quinto, sexta al primero, ...
Esta distribuci�n es muy sencilla pero presupone que todas las peticiones van a ser equivalentes, en t�rminos de carga, para el servidor, algo que en la realidad dista mucho de ser cierto. O que la capacidad de procesamiento de los servidores es la misma.
Podr�a darse el caso de que haya servidores atendiendo varias peticiones y otros esperando o que los servidores m�s lentos estuvieran muy sobrecargados mientras que los m�s potentes estuvieran m�s desahogados.
Weighted Round-Robin. Este algoritmo permite un aprovechamiento mejor del cluster cuando hay m�quinas con diferentes capacidades de procesamiento, de esta forma a las m�quinas con mayor capacidad de procesamiento se les dar� una mayor prioridad (weight) para responder a las peticiones de los clientes y el balanceador distribuir� la carga entre los servidores teniendo en cuenta su prioridad.
En realidad el Round-Robin Scheduling es un Weighted Round-Robin Scheduling y todas las prioridades son iguales para los servidores.
Least-Connection. Con este algoritmo las peticiones se enviaran al servidor que menos conexiones este sirviendo en ese momento.
Si la capacidad de procesamiento de los servidores es similar este algoritmo distribuir� la carga de forma �ptima entre todas las m�quinas del cluster. Sin embargo si las capacidades de procesamiento var�an mucho la carga no sera repartida de forma ecu�nime ya que la carga se repartir� seg�n el n�mero de conexiones abiertas en ese momento y no sobre la carga real de cada m�quina.
Weighted Least-Connection. Este algoritmo es al Least-Connection Scheduling lo que el Weighted Round-Robin Scheduling es al Round-Robin Scheduling.
A cada servidor se le asigna una prioridad seg�n su capacidad de procesamiento y aquellos que mas prioridad tengan asignada atender�n m�s peticiones, es decir tendr�n m�s conexiones abiertas.
ipvsadm es una herramienta en espacio de usuario para interactuar con LVS.
Podemos ver el listado de conexiones:
[jadebustos@dedalo ~]#
ipvsadm -Ln
IP Virtual Server version 1.2.0 (size=4096) Prot LocalAddress:Port Scheduler Flags -> RemoteAddress:Port Forward Weight ActiveConn InActConn TCP 172.16.0.207:443 wlc persistent 3600 -> 172.16.0.199:443 Route 1 5 0 -> 172.16.0.198:443 Route 1 2 0 TCP 172.16.0.205:9085 wlc -> 172.16.0.200:9085 Route 1 2 0 -> 172.16.0.201:9085 Route 1 2 0 TCP 172.16.0.206:80 wlc -> 172.16.0.197:80 Route 1 1 0 -> 172.16.0.195:80 Route 1 4 0 -> 172.16.0.196:80 Route 1 2 0 TCP 172.16.0.207:80 wlc persistent 3600 -> 172.16.0.199:80 Route 1 1 0 -> 172.16.0.198:80 Route 1 1 0 TCP 172.16.0.205:80 wlc -> 172.16.0.200:80 Route 1 1 0 -> 172.16.0.201:80 Route 1 1 0
[jadebustos@dedalo ~]#
Podemos sacar estad�sticas:
[jadebustos@dedalo ~]#
ipvsadm --list --stats --numeric
IP Virtual Server version 1.2.0 (size=4096) Prot LocalAddress:Port Conns InPkts OutPkts InBytes OutBytes -> RemoteAddress:Port TCP 172.16.0.207:443 7 169 292 x y -> 172.16.0.199:443 5 113 214 x y -> 172.16.0.198:443 2 56 78 x y TCP 172.16.0.205:9085 4 67 99 x y -> 172.16.0.200:9085 2 34 45 x y -> 172.16.0.201:9085 2 33 44 x y TCP 172.16.0.206:80 7 109 178 x y -> 172.16.0.197:80 1 12 23 x y -> 172.16.0.195:80 4 67 100 x y -> 172.16.0.196:80 2 30 45 x y TCP 172.16.0.207:80 2 30 58 x y -> 172.16.0.199:80 1 13 25 x y -> 172.16.0.198:80 1 17 33 x y TCP 172.16.0.205:80 2 27 50 x y -> 172.16.0.200:80 1 15 27 x y -> 172.16.0.201:80 1 12 23 x y
[jadebustos@dedalo ~]#
Otras opciones que nos permite:
A�adir, modificar y borrar servicios.
A�adir, modificar y borrar servidores.
Modificar los par�metros de configuraci�n de los servicios balanceados.
El balanceador es un punto de fallo cr�tico. Si el balanceador no est� disponible no habr� servicio aunque las m�quinas que den el servicio est�n en perfecto estado de funcionamiento.
Fallo en balanceador.
La alta disponibilidad se logr� garantizando que siempre haya un balanceador funcionando, resumiendo el servicio siempre tiene que estar disponible.
Balanceadores en Alta Disponibilidad.
Keepalived es un demonio que se encarga de que siempre haya un balanceador balanceanado el servicio (failover). En realidad es un interface a LVS.
Adem�s tambi�n se encarga de que no se env�en peticiones a servidores que en ese momento no puedan atenderlas (health-checking).
Keepalived se instala en los balanceadores. Uno de ellos ser� el MASTER y el resto ser�n denominados de BACKUP. Cuando el MASTER deje de estar operativo entrar� en funcionamiento el balanceador BACKUP de m�s alta prioridad y continuar� balanceando hasta que el MASTER vuelva a estar operativo o hasta que tenga alg�n problema, entonces lo sustituir� otro balanceador de BACKUP, el siguiente de m�s alta prioridad. De esta forma siempre estar� balanceando el balanceador de m�s alta prioridad. En el momento que un balanceador de m�s alta prioridad que el activo vuelva al servicio asumir� el balanceo.
Keepalived utiliza el protocolo VRRP (rfc 2338). Keepalived formar� un balanceador virtual formado por un balanceador MASTER y varios balanceadores BACKUP funcionando de la manera ant�s descrita.
Los balanceadores informar�n al resto de su disponibilidad utilizando el protocolo VRRP.
Para el health-checking de los servicios balanceados keepalived puede realizar la comprobaci�n de varias formas:
TCP_CHECK se har� una petici�n TCP y si no es respondida se eliminar� el servidor de la lista de servidores activos.
HTTP_GET Se solicitar� una p�gina del servidor y se comprobar� con una que es la correcta mediante un hashing MD5, previamente calculado, en caso de no coincidir el servidor ser� eliminado de la lista de servidores activos.
Para general el hashing MD5 utilizaremos la utilidad genhash que nos permitir� generar el hashing directamente desde el servidor.
SSL_GET igual que HTTP_GET pero la p�gina ser� solicitada bajo una conexi�n SSL por el puerto 443 (https).
MISC_CHECK esta opci�n nos permitir� comprobar la disponibilidad de los servidores mediante un script creado por nosotros. Si la situaci�n lo requiere podremos comprobar la disponibilidad de los servidores de forma personalizada.
El fichero de configuraci�n de keepalived normalmente en /etc/keepalived.conf
consta de tres partes:
Zona de configuraci�n global donde se especificar� la forma en la que keepalived avisar� a los administradores de un fallo en el servidor virtual (direcci�n de correo, servidor SMTP, ...)
Configuraci�n de VRRP donde indicaremos si el balanceador es MASTER o BACKUP, la prioridad, cual ser� la interface por la que tiene acceso al servidor virtual, la IP virtual (VIP) ...
Configuraci�n del servidor virtual indicando la IP (VIP) y el puerto, protocolo, ... y una entrada real server con los par�metros de cada servidor real, IP (real), puerto, m�todo de health-checking, ...
Este fichero ser� exactamente igual en el MASTER y en los BACKUPS salvo que en los BACKUPS el par�metro state en la configuraci�n de VRRP ser� BACKUP y en el MASTER ser� MASTER como cabr�a esperar.
Un ejemplo t�pico del fichero /etc/keepalived.conf
para una configuraci�n Direct Routing:
# Configuration File for keepalived # Configuracion Global global_defs { notification_email { alertas@midominio.com } notification_email_from balanceador1@midominio.com smtp_server 192.168.1.10 smtp_connect_timeout 30 lvs_id LVS_DEVEL } vrrp_instance wasIntranet { state MASTER interface eth1 virtual_router_id 50 priority 100 advert_int 1 wdog-vrrp 1 virtual_ipaddress { 172.16.0.205 172.16.0.206 172.16.0.207 } } virtual_server 172.16.0.205 80{ delay_loop 6 lb_algo wlc lb_kind DR persistence_timeout 3600 protocol TCP real_server 172.16.0.200 80 { weight 1 TCP_CHECK { connect_port 80 connect_timeout 30 } delay_before_retry 3 } real_server 172.16.0.201 80 { weight 1 TCP_CHECK { connect_port 80 connect_timeout 30 } delay_before_retry 3 } } virtual_server 172.16.0.205 9085 { delay_loop 6 lb_algo wlc lb_kind DR persistence_timeout 3600 protocol TCP real_server 172.16.0.200 9085 { weight 1 TCP_CHECK { connect_port 9085 connect_timeout 30 } delay_before_retry 3 } real_server 172.16.0.201 9085 { weight 1 TCP_CHECK { connect_port 9085 connect_timeout 30 } delay_before_retry 3 } } virtual_server 172.16.0.206 80 { delay_loop 6 lb_algo wlc lb_kind DR persistence_timeout 3600 protocol TCP real_server 172.16.0.195 80 { weight 1 TCP_CHECK { connect_port 80 connect_timeout 30 } delay_before_retry 3 } real_server 172.16.0.196 80 { weight 1 TCP_CHECK { connect_port 80 connect_timeout 30 } delay_before_retry 3 } real_server 172.16.0.197 80 { weight 1 TCP_CHECK { connect_port 80 connect_timeout 30 } delay_before_retry 3 } } virtual_server 172.16.0.207 80 { delay_loop 6 lb_algo wlc lb_kind DR persistence_timeout 3600 protocol TCP real_server 172.16.0.198 80 { weight 1 TCP_CHECK { connect_port 80 connect_timeout 30 } delay_before_retry 3 } real_server 172.16.0.199 80 { weight 1 TCP_CHECK { connect_port 80 connect_timeout 30 } delay_before_retry 3 } } virtual_server 172.16.0.207 443 { delay_loop 6 lb_algo wlc lb_kind DR persistence_timeout 3600 protocol TCP real_server 172.16.0.198 443 { weight 1 TCP_CHECK { connect_port 443 connect_timeout 30 } delay_before_retry 3 } real_server 172.16.0.199 443 { weight 1 TCP_CHECK { connect_port 443 connect_timeout 30 } delay_before_retry 3 } }
Tabla de contenidos
Un cluster debe conocer cuando alg�n nodo no est� disponible para no enviale peticiones.
Esto se hace de dos formas:
Heartbeat es la t�cnica m�s habitual. Consiste en comunicarse o bien a trav�s de una interface de red o puerto serie cada cierto tiempo. Si se pierde la comunicaci�n durante un determinado tiempo se supone que el nodo ha caido.
Disco de quorum es una t�nica complementaria que lo que se hace es que todos los nodos del cluster escriben su estado en un disco y de esa forma se determina quien est� disponible para dar el servicio.
Para implementar est� t�nica los nodos tiene l�neas dedicadas, bien sea por red o conexiones serie por las que se comunican de forma continua para verificar el correcto funcionamiento de los nodos.
Es recomendable utilizar varias l�neas de heartbeat.
Si un nodo tiene problemas de red y no llega a los otros nodos pensar� que los otros nodos no est�n disponibles e intentar� hacerse con el servicio.
Si disponemos de dispositivos serie para el heartbeat entonces dispondremos de una forma de comprobar que los otros nodos est�n funcionando correctamente y el problema es nuestro. De no disponerlo se asumir� de forma incorrecta que los otros nodos han fallado, intentando asumir el control del cluster y produciendo un Split Brain.
Para evitar esto se utiliza el disco de quorum. Cada nodo escribe de forma continua su estado en el disco y de esta forma se puede verificar que nodos est�n disponibles para hacerse con el servicio en el cluster.
El disco de quorum no es una t�cnica que sustituya al heartbeat es una t�nica que debe usarse como complemento al heartbeat.
Fencing es la capacidad de un cluster para hacer que uno de sus nodos libere los recursos que tiene ocupados.
Tambi�n es posible encontrarnos con el t�mino STONITH que es un acr�nimo para Shoot The Other Node Into The Head (Dispara al otro nodo en la cabeza).
Cuando un nodo no dectecta a otro, mediante heartbeat o disco de quorum, asume que el otro nodo no est� disponible. Si este nodo est� en estado pasivo intentar� levantar el servicio.
STONITH es una modalidad de fencing que consiste en apagar o reiniciar a un nodo para asegurarse que libera los recursos que tiene asignados.
Cuando se tiene alguna duda al respecto se hace fencing. Hay diferentes tipos de fencing:
Power fencing, consiste en utilizar un dispositivo que pueda apagar o reiniciar el servidor:
Tarjetas RSA de IBM.
Management Module en los Blade Centers de IBM.
Tarjetas ILO de HP.
Fabric fencing, consiste en suprimir el acceso a los discos. Por ejemplo utilizando SCSI reservations.
Tabla de contenidos
Heartbeat dise�ado para detectar cuando se ha ca�do un servicio en una m�quina y administraci�n de cluster.
Heartbeat puede utilizar dispositivos ethernet y de serie para comunicarse con los otros nodos del cluster. Tambi�n permite el uso de discos de quorum mediante el plugin ipfail.
Mon est� dise�ado para monitorizar la disponibilidad de servicios y lanzar alertas cuando detecte un servicio ca�do.
Fake ha sido dise�ado para cambiar un servicio de servidor.
Cuando se detecta que un servicio ha caido en una m�quina se utiliza Fake para levantar el servicio en otra m�quina.
ldirectord es un demonio que se utilizar para monitorizar servicios y detectar la ca�da de los mismos..
Kimberlite es una soluci�n de cluster para clusters de dos nodos y permite la conexi�n a un disco compartido de quorum v�a SCSI o por fibra (SAN).
Ultramonkey es una soluci�n para balanceo de carga y alta disponibilidad basada en LVS.
Ultramonkey utiliza:
Heartbeat en los balanceadores para detectar cuando ha ca�do un servicio, monitorizar los servidores a balancear mediante ldirectord y controlar la IP del servicio balanceado.
ldirectord en los balanceadores para realizar el health-checking de los servidores balanceados.
Red Hat Cluster Suite es la soluci�n de Red Hat para clustering y alta disponibilidad.
Esta soluci�n consta de:
GFS sistema de ficheros de acceso concurrente.
CLVM o Clustered LVM.
Piranha interface gr�fico para LVS.
system-config-cluster herramienta gr�fica para la configuraci�n del cluster.
ccsd demonio que hace accesible la configuraci�n del cluster por otros nodos.
cman demonio para la administraci�n del cluster.
qdiskd demonio para el manejo de discos de quorum..
fenced demonio para el fencing de dispositivos.
rgmanager.
Red Hat Cluster est� disponible en Debian Etch.
Version 1.2, November 2002
Copyright � 2000,2001,2002 Free Software Foundation, Inc.
Version 1.2, November 2002
Tabla de contenidos
The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque".
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.
A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
GNU FDL Modification Conditions
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.
You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Sample Invariant Sections list
Copyright (c) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this:
Sample Invariant Sections list
with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.