Skip to content

FailOver automatico con python utilizando contenedores en Docker.

License

Notifications You must be signed in to change notification settings

AFLeonardo/FailOver-BD

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

32 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“˜ Sistema de Failover + Resync AutomΓ‘tico para MySQL con Docker

Autor: Leonardo
Objetivo del proyecto: Implementar un sistema de Alta Disponibilidad (HA) para MySQL utilizando Docker Compose, con:

  • Failover automΓ‘tico
  • ReplicaciΓ³n asΓ­ncrona
  • ResincronizaciΓ³n cuando un nodo vuelve
  • Watcher en Python
  • Servicio de resync dedicado
  • API con FastAPI + dashboard web

πŸ›  Tech Stack

Docker MySQL Python FastAPI Bash TailwindCSS JavaScript HTML5

πŸ— Arquitectura General

El sistema estΓ‘ formado por contenedores Docker definidos en docker-compose.yml:

  • mysql-primary β†’ Nodo principal (PRIMARY)
  • mysql-replica β†’ Nodo secundario (REPLICA) sincronizado por binlogs
  • db-watcher β†’ Servicio Python que monitoriza y dispara el failover
  • db-resync β†’ Servicio Python que resincroniza nodos desactualizados
  • fastapi-dashboard β†’ API FastAPI + dashboard web (HTML estΓ‘tico)

πŸ“ Diagrama general

                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚     fastapi-dashboard       β”‚
                         β”‚   - FastAPI (API REST)      β”‚
                         β”‚   - Dashboard HTML          β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                       β”‚
                               Usuario / Navegador
                                       β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β”‚                                   β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚      mysql-primary     β”‚           β”‚     mysql-replica      β”‚
        β”‚      Role: PRIMARY     │◄────────►│     Role: REPLICA      β”‚
        β”‚  Binlogs habilitados   β”‚           β”‚ IO/SQL threads activos β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜           β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      β”‚                                    β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                     β”‚
                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚        db-watcher          β”‚
                      β”‚  - Heartbeat               β”‚
                      β”‚  - Failover automΓ‘tico     β”‚
                      β”‚  - Registro de eventos     β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚         db-resync          β”‚
                      β”‚  - Dump/restore            β”‚
                      β”‚  - Reconfig. replicaciΓ³n   β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

βš™οΈ Flujo de Failover y Recovery

πŸŸ₯ Cuando el primary cae

  1. db-watcher deja de recibir respuesta de mysql-primary.
  2. Marca el primary como DOWN.
  3. Promueve mysql-replica β†’ PRIMARY lΓ³gico.
  4. Detiene replicaciΓ³n (IO/SQL threads).
  5. Registra el evento en los logs (accesible desde la API/dashboard).

🟩 Cuando el nodo caído vuelve

  1. El nodo puede regresar desactualizado respecto al nuevo primary.
  2. db-watcher activa el proceso db-resync.
  3. Se toma un dump del nodo saludable.
  4. Se restaura en el nodo que regresΓ³.
  5. Se reconfigura la replicaciΓ³n (usuario, host, log_file, log_pos).
  6. Se reinician los IO/SQL threads.
  7. Los estados son actualizados y registrados.

πŸš€ Levantar el proyecto

AsegΓΊrate de tener Docker y Docker Compose instalados.

git clone https://github.com/AFLeonardo/FailOver-BD.git
cd FailOver-BD

# Levantar todos los servicios
docker-compose up -d --build

# Ver contenedores
docker ps

Debes ver:

mysql-primary
mysql-replica
db-watcher
db-resync
fastapi-dashboard

Comandos importantes

πŸ›‘ Apagar el primary

docker stop mysql-primary

Esto simula una caΓ­da real.

db-watcher debe promover la rΓ©plica automΓ‘ticamente.

Comandos para Logs:

docker logs -f db-watcher
docker logs -f db-resync
docker logs -f fastapi-dashboard

πŸ†— Encender nuevamente el primary

docker start mysql-primary

Ahora db-resync entra en acciΓ³n:

docker logs -f db-resync

Debe verse:

πŸ“¦ Iniciando backup...
βœ… Backup y restore completados.
πŸ” Restaurando topologΓ­a...

🌐 Acceso al Dashboard y la API

Dashboard web (HTML estΓ‘tico)

http://localhost:8000/static/dashboard.html

FastAPI docs (Swagger UI)

http://localhost:8000/docs

🧱 Estructura del repositorio

/
β”œβ”€β”€ db-resync/
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── resync.py
β”‚
β”œβ”€β”€ db-watcher/
β”‚   β”œβ”€β”€ Dockerfile
β”‚   └── watcher.py
β”‚
β”œβ”€β”€ fastapi-dashboard/
β”‚   β”œβ”€β”€ static/
β”‚   β”‚   └── dashboard.html
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ main.py
β”‚   └── requirements.txt
β”‚
β”œβ”€β”€ DB.sql
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ LICENSE
β”œβ”€β”€ README.md

πŸ““ Notas TΓ©cnicas

πŸ“Œ ReplicaciΓ³n MySQL

  • ReplicaciΓ³n asΓ­ncrona.
  • server-id distinto para cada nodo.
  • Binlogs habilitados en el primary.

πŸ“Œ Watcher (db-watcher)

  • Implementado en Python.
  • Registra todos los eventos para monitoreo.

πŸ“Œ Resync (db-resync)

  • Ejecuta dump + restore automΓ‘tico.
  • Reconfigura la replicaciΓ³n.
  • Vuelve a enganchar el nodo desactualizado.

πŸ“Œ FastAPI + Dashboard (fastapi-dashboard)

main.py expone:

  • Estado del cluster
  • Logs del watcher
  • Acciones manuales (failover, resync)

dashboard.html muestra:

  • Estado en tiempo real
  • Últimos eventos
  • Indicadores visuales

πŸŽ“ ConclusiΓ³n

Este proyecto implementa un sistema totalmente funcional y automatizado de alta disponibilidad MySQL:

  • Failover automΓ‘tico
  • ResincronizaciΓ³n automΓ‘tica
  • RecuperaciΓ³n completa de la topologΓ­a
  • Capacidad de repetir el ciclo indefinidamente
  • FastAPI para mostrar estado del cluster en el Dashboard
  • Todo con Docker + Python