Sync from R2 skynet v8: manuales, operación, glosario v3
Añadido: - MANUAL_USUARIO_ARCHITECT.md - MANUAL_USUARIO_CORP.md - MANUAL_USUARIO_DECK.md - MANUAL_USUARIO_HST.md - 07_OPERACION/ (monitoring, runbooks, incident_response) - glosario_she_enterprise_v3.md Eliminado: - glosario_she_enterprise_v2.md (reemplazado por v3) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
97
07_OPERACION/INDEX.md
Normal file
97
07_OPERACION/INDEX.md
Normal file
@@ -0,0 +1,97 @@
|
||||
# Skynet v8 - Sección 07: OPERACIÓN
|
||||
|
||||
## Documentos de Operación
|
||||
|
||||
### 1. Runbooks (runbooks.md)
|
||||
Procedimientos estandarizados para operaciones comunes:
|
||||
- **Reinicio de servicios**: Procedimiento seguro para reiniciar servicios sin downtime
|
||||
- **Failover de base de datos**: Cambio automático a réplica en caso de fallo
|
||||
- **Restauración de backups**: Opciones de restauración (completa, PITR, tabla)
|
||||
- **Escalado de recursos**: CPU, RAM, almacenamiento
|
||||
|
||||
**Ubicación**: `/system/skynet v8/07_OPERACION/runbooks.md`
|
||||
|
||||
### 2. Respuesta ante Incidentes (incident_response.md)
|
||||
Procedimientos de respuesta para situaciones de crisis:
|
||||
- **Caída de servidor**: Detección, escalación, mitigación, recovery
|
||||
- **Ataque DDoS**: Identificación, rate limiting, activación de servicios de protección
|
||||
- **Breach de seguridad**: Aislamiento, investigación forense, recovery, notificación
|
||||
|
||||
Incluye:
|
||||
- Fases de respuesta (detección, confirmación, escalación, investigación, mitigación, resolución)
|
||||
- Escaleras de escalación por severidad (P1-P4)
|
||||
- Contactos de emergencia
|
||||
- Tiempos de respuesta objetivo (SLA)
|
||||
|
||||
**Ubicación**: `/system/skynet v8/07_OPERACION/incident_response.md`
|
||||
|
||||
### 3. Monitoreo y Observabilidad (monitoring.md)
|
||||
Arquitectura y configuración de monitoreo:
|
||||
- **Métricas a monitorear**: Aplicación, BD, sistema, seguridad
|
||||
- **Alertas configuradas**: P1 (críticas), P2 (altas), P3 (medias)
|
||||
- **Dashboards**: Sistema, aplicación, BD, infraestructura, seguridad
|
||||
- **Logs**: Ubicaciones, análisis, comandos útiles
|
||||
- **Exporters**: Prometheus, custom, PostgreSQL
|
||||
|
||||
**Ubicación**: `/system/skynet v8/07_OPERACION/monitoring.md`
|
||||
|
||||
---
|
||||
|
||||
## Estructura de Carpetas R2
|
||||
|
||||
```
|
||||
s3://architect/system/skynet v8/07_OPERACION/
|
||||
├── runbooks.md (6.6 KB)
|
||||
├── incident_response.md (10.9 KB)
|
||||
├── monitoring.md (17.0 KB)
|
||||
└── INDEX_07_OPERACION.md (este archivo)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceso Rápido
|
||||
|
||||
### Para operadores
|
||||
1. Problema con servicio → Consultar `runbooks.md`
|
||||
2. Incidente crítico → Consultar `incident_response.md`
|
||||
3. Verificar estado del sistema → Consultar `monitoring.md`
|
||||
|
||||
### Para automatización
|
||||
- Scripts de backup: Referir a `runbooks.md` - Restauración de backups
|
||||
- Alertas automáticas: Referir a `monitoring.md` - Alertas Configuradas
|
||||
- Escalación automática: Referir a `incident_response.md` - Escaleras de escalación
|
||||
|
||||
---
|
||||
|
||||
## Integración con otras secciones
|
||||
|
||||
| Sección | Relación |
|
||||
|---------|----------|
|
||||
| 01_ARCHITECTURE | Define componentes monitorear |
|
||||
| 02_SECURITY | Colabora en incident response |
|
||||
| 03_INFRASTRUCTURE | Detalles técnicos para runbooks |
|
||||
| 04_DEPLOYMENT | Coordina con reinicio de servicios |
|
||||
| 05_TESTING | Valida runbooks en staging |
|
||||
| 06_TROUBLESHOOTING | Diagnostico previo a incidentes |
|
||||
|
||||
---
|
||||
|
||||
## Mejoras Futuras
|
||||
|
||||
1. Automatización adicional:
|
||||
- Scripts Python para ejecutar runbooks
|
||||
- Integración con orchestration tools (Kubernetes, etc.)
|
||||
|
||||
2. Aprendizaje automático:
|
||||
- Análisis predictivo de fallos
|
||||
- Detección anomalías avanzada
|
||||
|
||||
3. Documentación mejorada:
|
||||
- Videos de procedimientos críticos
|
||||
- Simulacros periódicos
|
||||
|
||||
---
|
||||
|
||||
**Última actualización**: 2025-12-30
|
||||
**Versión**: Skynet v8.0
|
||||
**Estado**: Operacional
|
||||
424
07_OPERACION/incident_response.md
Normal file
424
07_OPERACION/incident_response.md
Normal file
@@ -0,0 +1,424 @@
|
||||
# Procedimientos de Respuesta ante Incidentes - Skynet v8
|
||||
|
||||
## Procedimiento General ante Incidentes
|
||||
|
||||
### Fases de respuesta
|
||||
1. **Detección**: Sistema de alertas detecta anomalía
|
||||
2. **Confirmación**: Validar que es incidente real
|
||||
3. **Escalación**: Notificar al equipo
|
||||
4. **Investigación**: Determinar causa
|
||||
5. **Mitigación**: Aplicar solución temporal
|
||||
6. **Resolución**: Fix permanente
|
||||
7. **Post-mortem**: Análisis y mejora
|
||||
|
||||
---
|
||||
|
||||
## Incidente: Caída de Servidor
|
||||
|
||||
### Severidad
|
||||
**CRÍTICA** - Impacto: 100% del servicio indisponible
|
||||
|
||||
### Detección
|
||||
- Sistema de monitoreo no recibe heartbeat
|
||||
- Usuarios reportan servicio inaccesible
|
||||
- Alertas en Grafana: `node_up == 0`
|
||||
|
||||
### Confirmación (2 minutos máximo)
|
||||
```bash
|
||||
# Verificar conectividad básica
|
||||
ping 69.62.126.110
|
||||
|
||||
# Intentar conexión SSH
|
||||
ssh -i ~/.ssh/tzzr architect@69.62.126.110
|
||||
|
||||
# Si SSH no responde, es caída real
|
||||
```
|
||||
|
||||
### Escalación INMEDIATA
|
||||
1. **Notificar a**:
|
||||
- On-call engineer (5 min de respuesta)
|
||||
- Engineering lead
|
||||
- Operations manager
|
||||
|
||||
2. **Crear incident**
|
||||
- Abrir INC ticket
|
||||
- Timestamp inicio
|
||||
- Severidad: P1-CRITICAL
|
||||
|
||||
3. **Canales de comunicación**
|
||||
- Slack #incidents-critical
|
||||
- Email a escalation-list@skynet.tzzr
|
||||
- SMS a on-call (si disponible)
|
||||
|
||||
### Investigación inicial (5 minutos)
|
||||
```bash
|
||||
# Desde backup server
|
||||
ssh -i ~/.ssh/tzzr root@72.62.1.113 # deck
|
||||
|
||||
# Verificar recursos
|
||||
ping -c 3 69.62.126.110
|
||||
ssh -o ConnectTimeout=5 root@69.62.126.110 "uptime"
|
||||
|
||||
# Verificar logs en firewall/router
|
||||
ssh monitoring "tail -f /var/log/firewall.log | grep 69.62.126.110"
|
||||
|
||||
# Contactar proveedor datacenter
|
||||
# Verificar alertas de potencia/red
|
||||
```
|
||||
|
||||
### Mitigación Temporal (Si fallo de hardware)
|
||||
|
||||
#### Opción 1: Reinicio remoto
|
||||
```bash
|
||||
# Si acceso IPMI disponible
|
||||
ipmitool -I lanplus -H ipmi.datacenter.com -U admin -P pass power reset
|
||||
|
||||
# Esperar 3 minutos
|
||||
sleep 180
|
||||
|
||||
# Verificar si responde
|
||||
ping -c 3 69.62.126.110
|
||||
```
|
||||
|
||||
#### Opción 2: Failover a servidor backup
|
||||
```bash
|
||||
# Redirigir tráfico a deck (72.62.1.113)
|
||||
# Actualizar DNS
|
||||
# change A record: skynet.ttzr 300 IN A 72.62.1.113
|
||||
|
||||
# Sincronizar estado si posible
|
||||
rsync -avz --delete /var/lib/postgresql/ deck:/var/lib/postgresql/
|
||||
|
||||
# Iniciar servicios en backup
|
||||
ssh deck "systemctl start skynet-database skynet-api skynet-core"
|
||||
```
|
||||
|
||||
### Resolución
|
||||
- **Si hardware**: Contactar con datacenter para reemplazo
|
||||
- **Si red**: Contactar ISP para restaurar conectividad
|
||||
- **Si aplicación**: Debugging post-restauración
|
||||
|
||||
### Post-mortem (24 horas)
|
||||
- Documentar timeline
|
||||
- Identificar root cause
|
||||
- Implementar prevención
|
||||
- Actualizar runbooks
|
||||
|
||||
---
|
||||
|
||||
## Incidente: Ataque DDoS
|
||||
|
||||
### Severidad
|
||||
**ALTA** - Impacto: Servicio degradado o inaccesible
|
||||
|
||||
### Detección
|
||||
- Spike repentino de tráfico (>10x normal)
|
||||
- Alertas: `request_rate > 50k/sec`
|
||||
- Origen: Múltiples IPs no reconocidas
|
||||
- Network utilization > 80% inbound
|
||||
|
||||
### Confirmación (1 minuto)
|
||||
```bash
|
||||
# Verificar tráfico
|
||||
iftop -n -s 10
|
||||
|
||||
# Análisis de IPs origen
|
||||
tcpdump -i eth0 -nnn 'tcp.port == 80 or tcp.port == 443' | \
|
||||
awk '{print $3}' | cut -d. -f1-4 | sort | uniq -c | sort -rn | head -20
|
||||
|
||||
# Patrones de ataque
|
||||
# - SYN flood: conexiones incompletas
|
||||
ss -antp | grep SYN_RECV | wc -l
|
||||
# - HTTP flood: requests normales pero masivos
|
||||
# - DNS amplification: puerto 53
|
||||
|
||||
# Verificar logs de aplicación
|
||||
tail -f /var/log/skynet/access.log | head -100
|
||||
```
|
||||
|
||||
### Escalación INMEDIATA
|
||||
1. **Notificar**:
|
||||
- Security team
|
||||
- Network operations
|
||||
- Incident commander
|
||||
|
||||
2. **Crear incident**
|
||||
- INC ticket con "DDoS" en título
|
||||
- Severidad: P2-HIGH (puede ser P1 si impacto crítico)
|
||||
|
||||
3. **Activar plan DDoS**
|
||||
```bash
|
||||
# Alertas automáticas envían:
|
||||
# - Notificación a CDN provider
|
||||
# - Activación de rate limiting
|
||||
# - Análisis automático de patrones
|
||||
```
|
||||
|
||||
### Mitigación Temporal (Primeros 5-10 minutos)
|
||||
|
||||
#### Paso 1: Rate limiting automático
|
||||
```bash
|
||||
# Activar rate limiting por IP
|
||||
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
|
||||
iptables -A INPUT -p tcp --dport 80 -j DROP
|
||||
|
||||
# Alternativa: WAF rules
|
||||
# modsecurity rule: SecAction phase:1,nolog,pass,setvar:ip.suspicious=1
|
||||
```
|
||||
|
||||
#### Paso 2: Blacklist de IPs ofensoras
|
||||
```bash
|
||||
# Script para extraer top atacantes
|
||||
tcpdump -i eth0 -nnn -c 10000 'tcp.port == 80 or tcp.port == 443' | \
|
||||
awk '{print $3}' | cut -d. -f1-4 | \
|
||||
sort | uniq -c | sort -rn | head -100 | \
|
||||
awk '{print "iptables -A INPUT -s " $3 " -j DROP"}'
|
||||
|
||||
# O usar geo-blocking
|
||||
geoiplookup <IP> | grep -E "CN|RU|KP" && echo "DROP"
|
||||
```
|
||||
|
||||
#### Paso 3: Activar protección DNS
|
||||
```bash
|
||||
# Cambiar nameservers a proveedor con DDoS mitigation
|
||||
# (e.g., CloudFlare, Akamai)
|
||||
|
||||
# Actualizar DNS:
|
||||
# skynet.ttzr NS dns1.cloudflare.com
|
||||
# skynet.ttzr NS dns2.cloudflare.com
|
||||
|
||||
# O activar Cloudflare proxy:
|
||||
# change A record a IP de Cloudflare
|
||||
# Cloudflare mitiga el ataque antes de llegar a nuestro servidor
|
||||
```
|
||||
|
||||
### Escalación a DDoS Mitigation Service
|
||||
```bash
|
||||
# Si ataque persiste > 30 minutos
|
||||
# Activar contrato con DDoS mitigation provider
|
||||
|
||||
# Ejemplo: Cloudflare
|
||||
# 1. Cambiar nameservers
|
||||
# 2. Enable "I'm under attack mode"
|
||||
# 3. Cloudflare absorbe el tráfico malicioso
|
||||
|
||||
# Ejemplo: AWS Shield Advanced
|
||||
# 1. Redirigir tráfico a AWS CloudFront
|
||||
# 2. AWS absorbe y filtra ataque
|
||||
# 3. Tráfico legítimo llega a servidor
|
||||
```
|
||||
|
||||
### Investigación paralela
|
||||
```bash
|
||||
# Mientras se mitiga:
|
||||
# 1. Analizar patrones de ataque
|
||||
# 2. Identificar botnet o atacante
|
||||
# 3. Reportar a ISP del atacante
|
||||
# 4. Notificar law enforcement si necesario
|
||||
|
||||
# Comando: detectar patrón de User-Agent
|
||||
tail -f /var/log/skynet/access.log | grep -o 'User-Agent: [^"]*' | sort | uniq -c | sort -rn | head -5
|
||||
```
|
||||
|
||||
### Resolución
|
||||
- Dejar mitigación activa mientras persista ataque
|
||||
- Bloqueo permanente de IPs confirmadas maliciosas
|
||||
- Mantener WAF rules
|
||||
- Monitoreo intensivo por 24 horas
|
||||
|
||||
### Post-mortem
|
||||
- Análisis de logs del ataque
|
||||
- Identificación de patrones para prevención futura
|
||||
- Actualización de WAF rules
|
||||
- Prueba de carga para validar capacidad
|
||||
|
||||
---
|
||||
|
||||
## Incidente: Breach de Seguridad
|
||||
|
||||
### Severidad
|
||||
**CRÍTICA** - Impacto: Acceso no autorizado a datos sensibles
|
||||
|
||||
### Detección
|
||||
- Alertas de IDS/IPS
|
||||
- Comportamiento anómalo de usuario
|
||||
- Cambios no autorizados en archivos críticos
|
||||
- Alertas de WAF: SQLi, RFI, etc.
|
||||
|
||||
### Confirmación (Inmediato)
|
||||
```bash
|
||||
# Verificar logs de seguridad
|
||||
grep "ALERT\|ERROR\|FAILED" /var/log/auth.log | tail -50
|
||||
|
||||
# Revisar cambios recientes
|
||||
find /var/www /etc /root -mtime -1 -ls
|
||||
|
||||
# Búsqueda de shells web
|
||||
find / -name "*.php" -o -name "*.jsp" -o -name "*.asp" | \
|
||||
xargs grep -l "exec\|system\|shell_exec" 2>/dev/null
|
||||
|
||||
# Revisar procesos anómalos
|
||||
ps auxf | grep -E "bash|nc|perl|python" | grep -v grep
|
||||
```
|
||||
|
||||
### Escalación CRÍTICA + Aislamiento (1 minuto)
|
||||
1. **AISLAR SERVIDOR INMEDIATAMENTE**
|
||||
- Desconectar del firewall si es posible
|
||||
- O bloquear tráfico no autorizado
|
||||
```bash
|
||||
# Bloquear acceso excepto admin
|
||||
iptables -F INPUT
|
||||
iptables -A INPUT -i lo -j ACCEPT
|
||||
iptables -A INPUT -s <ADMIN_IP> -j ACCEPT
|
||||
iptables -A INPUT -j DROP
|
||||
```
|
||||
|
||||
2. **Notificar a**:
|
||||
- CTO / Security lead (inmediato)
|
||||
- Incident commander
|
||||
- Legal team
|
||||
- HR (si credenciales de empleado usadas)
|
||||
|
||||
3. **Crear incident**
|
||||
- INC ticket: "SECURITY BREACH"
|
||||
- Severidad: P1-CRITICAL
|
||||
- Activar crisis management
|
||||
|
||||
4. **Notificar stakeholders**
|
||||
- CEO
|
||||
- Directores de área afectada
|
||||
- Equipo legal
|
||||
|
||||
### Investigación (En paralelo con aislamiento)
|
||||
```bash
|
||||
# NO modificar nada en el servidor comprometido aún
|
||||
# Preservar evidencia
|
||||
|
||||
# 1. Identificar punto de entrada
|
||||
grep "FAILED\|UNAUTHORIZED" /var/log/auth.log | tail -100
|
||||
|
||||
# 2. Buscar malware/backdoors
|
||||
find /tmp /home /var/tmp -mtime -1 -type f | xargs file
|
||||
strings /var/log/syslog | grep -E "curl|wget|chmod" | tail -20
|
||||
|
||||
# 3. Revisar cambios en usuarios/permisos
|
||||
grep "sudo\|usermod\|chmod 777" /var/log/auth.log
|
||||
|
||||
# 4. Revisar conexiones de red
|
||||
netstat -pantu | grep ESTABLISHED | head -20
|
||||
lsof -i -P -n | grep -v LISTEN
|
||||
|
||||
# 5. Examinar sistema de archivos en disco
|
||||
# (hacer copia forense primero)
|
||||
ddrescue /dev/sda /mnt/forensic/sda.img
|
||||
mount -o ro /mnt/forensic/sda.img /mnt/forensic_mount
|
||||
|
||||
# 6. Buscar cambios en archivos críticos
|
||||
find /etc /root /var/www -mtime -3 ! -path "*/.*" -type f -ls
|
||||
```
|
||||
|
||||
### Contención
|
||||
```bash
|
||||
# 1. Si credenciales comprometidas
|
||||
# - Resetear contraseñas de todos los usuarios
|
||||
# - Cambiar API keys
|
||||
# - Revocar OAuth tokens
|
||||
|
||||
# 2. Si datos expuestos
|
||||
# - Inventariar datos expuestos
|
||||
# - Notificar a usuarios afectados (según GDPR/CCPA)
|
||||
# - Contactar a asegurador
|
||||
|
||||
# 3. Parches de seguridad
|
||||
# Aplicar patches a vulnerabilidad explotada
|
||||
# Actualizar software vulnerable
|
||||
```
|
||||
|
||||
### Recovery
|
||||
```bash
|
||||
# Opción 1: Restore desde backup limpio pre-breach
|
||||
systemctl stop skynet-*
|
||||
pg_restore -d postgres /backups/skynet_2025-12-25.sql # Anterior al breach
|
||||
systemctl start skynet-*
|
||||
|
||||
# Opción 2: Rebuild desde source control
|
||||
git clone https://gitea.ttzr/skynet/core.git
|
||||
cd core && git checkout commit_seguro
|
||||
./install.sh
|
||||
```
|
||||
|
||||
### Post-mortem (CRÍTICO)
|
||||
- Análisis forense completo
|
||||
- Publicar breach disclosure si requerido por ley
|
||||
- Auditoría de seguridad completa
|
||||
- Implementar controles preventivos
|
||||
- Revisión de políticas de seguridad
|
||||
|
||||
---
|
||||
|
||||
## Contactos de Emergencia
|
||||
|
||||
### Equipo de On-Call
|
||||
| Rol | Nombre | Teléfono | Email | Backup |
|
||||
|-----|--------|----------|-------|--------|
|
||||
| Principal | [ON-CALL] | +X XXXXXXXXX | oncall@skynet.ttzr | [BACKUP] |
|
||||
| Security | CISO | +X XXXXXXXXX | ciso@skynet.ttzr | Security Lead |
|
||||
| Operations | Ops Manager | +X XXXXXXXXX | ops@skynet.ttzr | DevOps Lead |
|
||||
| Database | DBA Lead | +X XXXXXXXXX | dba@skynet.ttzr | DBA Senior |
|
||||
|
||||
### Escalación Automática
|
||||
```
|
||||
Incidente detectado
|
||||
↓
|
||||
Alertas a Slack #incidents
|
||||
↓
|
||||
Si no confirmado en 5 min → Email a on-call
|
||||
↓
|
||||
Si no responde en 10 min → SMS + teléfono
|
||||
↓
|
||||
Si no responde en 15 min → Escalar a manager
|
||||
↓
|
||||
Si Severidad P1 → Activar crisis team
|
||||
```
|
||||
|
||||
### Proveedores Externos
|
||||
|
||||
#### Datacenter
|
||||
- **Proveedor**: [DATACENTER_NAME]
|
||||
- **Contacto NOC**: +X XXXXXXXXX
|
||||
- **Tickets**: https://support.datacenter.com
|
||||
- **Emergencia 24/7**: [NÚMERO]
|
||||
|
||||
#### ISP
|
||||
- **Proveedor**: [ISP_NAME]
|
||||
- **Contacto**: +X XXXXXXXXX
|
||||
- **Status page**: https://status.isp.com
|
||||
- **Emergencia**: [NÚMERO]
|
||||
|
||||
#### Banco de datos
|
||||
- **Proveedor**: [DB_PROVIDER]
|
||||
- **Support**: [EMAIL/TELÉFONO]
|
||||
- **Documentation**: [URL]
|
||||
|
||||
### Escaleras de escalación según severidad
|
||||
|
||||
#### P1-CRITICAL (Todos afectados)
|
||||
1. On-call engineer (inmediato)
|
||||
2. Tech lead (1 min)
|
||||
3. Engineering manager (2 min)
|
||||
4. CTO (3 min)
|
||||
5. CEO (5 min si no resolviendo)
|
||||
|
||||
#### P2-HIGH (Servicio degradado)
|
||||
1. On-call engineer
|
||||
2. Tech lead (si no resolviendo en 10 min)
|
||||
3. Engineering manager (si no resolviendo en 30 min)
|
||||
|
||||
#### P3-MEDIUM (Funcionalidad limitada)
|
||||
1. On-call engineer
|
||||
2. Tech lead (próximo turno si no urgente)
|
||||
|
||||
#### P4-LOW (Feature requests, problemas menores)
|
||||
1. Queue para próximo sprint
|
||||
2. No escalación urgente
|
||||
|
||||
557
07_OPERACION/monitoring.md
Normal file
557
07_OPERACION/monitoring.md
Normal file
@@ -0,0 +1,557 @@
|
||||
# Monitoreo y Observabilidad - Skynet v8
|
||||
|
||||
## Arquitectura de Monitoreo
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Skynet v8 Services │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ skynet-core │ │ skynet-api │ │ skynet-db │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ └──────────────────┼───────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌──────────────────┴──────────────────┐ │
|
||||
│ ▼ ▼ ▼ │
|
||||
│ ┌─────────────────────────────────────────────────────┐ │
|
||||
│ │ Exporters / Collectors │ │
|
||||
│ │ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ │ │
|
||||
│ │ │ Prometheus │ │ Node Expt │ │ Filebeat │ │ │
|
||||
│ │ │ Exporter │ │ (system) │ │ (logs) │ │ │
|
||||
│ │ └──────────────┘ └──────────────┘ └────────────┘ │ │
|
||||
│ └─────────────────────────────────────────────────────┘ │
|
||||
└──────────────────────┬──────────────────────────────────────┘
|
||||
│
|
||||
┌──────────────┼──────────────┐
|
||||
▼ ▼ ▼
|
||||
┌─────────┐ ┌──────────┐ ┌──────────────┐
|
||||
│ Grafana │ │ ELK │ │ Alert Mgr │
|
||||
│ (Viz) │ │ (Logs) │ │ (Alerts) │
|
||||
└─────────┘ └──────────┘ └──────────────┘
|
||||
│ │ │
|
||||
└──────────────┼───────────────┘
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Notification │
|
||||
│ Channels │
|
||||
│ (Slack/Email) │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Métricas a Monitorear
|
||||
|
||||
### 1. Métricas de Aplicación (skynet-core)
|
||||
|
||||
#### Procesamiento y Throughput
|
||||
```
|
||||
Métrica | Umbral Normal | Alerta Warn | Alerta Critical
|
||||
---------------------------|---------------|-------------|----------------
|
||||
requests_per_second | 100-500 | > 750 | > 1000
|
||||
response_time_p50 | < 100ms | > 200ms | > 500ms
|
||||
response_time_p95 | < 500ms | > 1000ms | > 2000ms
|
||||
response_time_p99 | < 1000ms | > 2000ms | > 5000ms
|
||||
error_rate | < 0.1% | > 0.5% | > 1%
|
||||
success_rate | > 99.9% | < 99.5% | < 99%
|
||||
```
|
||||
|
||||
#### Ejemplos Prometheus
|
||||
```
|
||||
# Request rate (requests/sec)
|
||||
rate(http_requests_total[5m])
|
||||
|
||||
# Response time percentiles
|
||||
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
|
||||
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))
|
||||
|
||||
# Error rate
|
||||
rate(http_requests_total{status=~"5.."}[5m]) /
|
||||
rate(http_requests_total[5m])
|
||||
|
||||
# Active connections
|
||||
skynet_active_connections
|
||||
```
|
||||
|
||||
### 2. Métricas de Base de Datos (skynet-database)
|
||||
|
||||
#### Performance
|
||||
```
|
||||
Métrica | Umbral Normal | Alerta | Critical
|
||||
-----------------------------|---------------|---------|----------
|
||||
query_execution_time_p95 | < 100ms | > 500ms | > 2000ms
|
||||
transactions_per_second | 100-1000 | > 2000 | > 5000
|
||||
active_connections | 10-50 | > 100 | > 150
|
||||
connection_utilization_pct | < 50% | > 80% | > 95%
|
||||
replication_lag_bytes | < 1MB | > 100MB | > 1GB
|
||||
```
|
||||
|
||||
#### Ejemplo Prometheus
|
||||
```
|
||||
# Query latency
|
||||
histogram_quantile(0.95, rate(pg_slow_queries_duration_seconds_bucket[5m]))
|
||||
|
||||
# Transactions/sec
|
||||
rate(pg_transactions_total[1m])
|
||||
|
||||
# Active connections
|
||||
pg_stat_activity_count{state="active"}
|
||||
|
||||
# Replication lag
|
||||
pg_replication_lag_bytes / 1024 / 1024 # MB
|
||||
|
||||
# Connection ratio
|
||||
pg_stat_activity_count / pg_settings_max_connections * 100
|
||||
```
|
||||
|
||||
### 3. Métricas de Sistema (Node Exporter)
|
||||
|
||||
#### CPU y Memoria
|
||||
```
|
||||
Métrica | Umbral Normal | Alerta Warn | Critical
|
||||
---------------------------|---------------|-------------|----------
|
||||
cpu_usage_percent | < 70% | > 80% | > 95%
|
||||
load_average_1min | < cores | > cores*1.5 | > cores*2
|
||||
memory_usage_percent | < 80% | > 85% | > 95%
|
||||
swap_usage_percent | < 10% | > 30% | > 50%
|
||||
```
|
||||
|
||||
#### Disco e I/O
|
||||
```
|
||||
Métrica | Umbral Normal | Alerta Warn | Critical
|
||||
---------------------------|---------------|-------------|----------
|
||||
disk_usage_percent | < 70% | > 80% | > 95%
|
||||
disk_io_read_mb_sec | variable | > 500MB/s | > 1GB/s
|
||||
disk_io_write_mb_sec | variable | > 500MB/s | > 1GB/s
|
||||
inode_usage_percent | < 70% | > 80% | > 95%
|
||||
```
|
||||
|
||||
#### Red
|
||||
```
|
||||
Métrica | Umbral Normal | Alerta Warn | Critical
|
||||
---------------------------|---------------|-------------|----------
|
||||
network_in_mbps | variable | > 900Mbps | > 980Mbps
|
||||
network_out_mbps | variable | > 900Mbps | > 980Mbps
|
||||
packet_loss_percent | < 0.1% | > 0.5% | > 1%
|
||||
tcp_connections | < 10000 | > 20000 | > 30000
|
||||
tcp_time_wait | < 5000 | > 10000 | > 20000
|
||||
```
|
||||
|
||||
#### Ejemplos Prometheus
|
||||
```
|
||||
# CPU usage
|
||||
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
|
||||
|
||||
# Memory usage
|
||||
(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100
|
||||
|
||||
# Disk usage
|
||||
(node_filesystem_size_bytes{fstype!="tmpfs"} - node_filesystem_avail_bytes) /
|
||||
node_filesystem_size_bytes * 100
|
||||
|
||||
# Network throughput
|
||||
rate(node_network_transmit_bytes_total{device="eth0"}[5m]) / 1024 / 1024 # MB/s
|
||||
```
|
||||
|
||||
### 4. Métricas de Seguridad
|
||||
|
||||
#### Acceso y Autenticación
|
||||
```
|
||||
Métrica | Umbral Normal | Alerta
|
||||
-----------------------------|---------------|--------
|
||||
failed_login_attempts_per_min | < 5 | > 20
|
||||
ssh_login_failures | < 3/10min | > 10/10min
|
||||
sudo_usage_anomaly | histórico | +50% desviación
|
||||
unauthorized_api_calls | < 1/min | > 10/min
|
||||
```
|
||||
|
||||
#### Integridad de datos
|
||||
```
|
||||
Métrica | Acción
|
||||
-----------------------------|------
|
||||
database_checksum_errors | Alerta + Investigar inmediatamente
|
||||
file_integrity_changes | Log + Review semanal
|
||||
unauthorized_user_creation | Alerta crítica
|
||||
privilege_escalation_attempt | Alerta crítica + Log forense
|
||||
```
|
||||
|
||||
#### Ejemplo: Detección de anomalías
|
||||
```bash
|
||||
# Buscar cambios no autorizados en archivos críticos
|
||||
aide --check --config=/etc/aide/aide.conf
|
||||
|
||||
# Auditar cambios de permisos
|
||||
auditctl -l
|
||||
ausearch -k privileged | tail -100
|
||||
|
||||
# Monitorear login attempts
|
||||
faillog -a # Summary de todos los usuarios
|
||||
lastb # Últimas 10 sesiones fallidas
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Alertas Configuradas
|
||||
|
||||
### Sistema de Alertas
|
||||
|
||||
Archivo: `/etc/prometheus/alert_rules.yml`
|
||||
|
||||
#### Alertas P1 (CRÍTICAS - 1 minuto)
|
||||
```yaml
|
||||
- alert: ServiceDown
|
||||
expr: up == 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "{{ $labels.instance }} DOWN"
|
||||
action: "Verificar immediately, ejecutar runbook de reinicio"
|
||||
|
||||
- alert: DiskFull
|
||||
expr: (node_filesystem_avail_bytes / node_filesystem_size_bytes) < 0.05
|
||||
for: 5m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Disco al 95% en {{ $labels.instance }}"
|
||||
action: "Ejecutar escalado de almacenamiento"
|
||||
|
||||
- alert: HighErrorRate
|
||||
expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.05
|
||||
for: 2m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Error rate > 5% en {{ $labels.job }}"
|
||||
action: "Investigar logs, posible DDoS o fallo de aplicación"
|
||||
|
||||
- alert: DatabaseDown
|
||||
expr: pg_up == 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "PostgreSQL DOWN en {{ $labels.instance }}"
|
||||
action: "Ejecutar runbook de failover o reinicio"
|
||||
|
||||
- alert: ReplicationLagCritical
|
||||
expr: (pg_replication_lag_bytes / 1024 / 1024) > 1000 # 1GB
|
||||
for: 5m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Replication lag {{ $value }}MB"
|
||||
action: "Verificar red, aumentar bandwidth, o promover replica"
|
||||
```
|
||||
|
||||
#### Alertas P2 (ALTAS - 5 minutos)
|
||||
```yaml
|
||||
- alert: HighCPU
|
||||
expr: (100 - (avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)) > 80
|
||||
for: 5m
|
||||
labels:
|
||||
severity: high
|
||||
annotations:
|
||||
summary: "CPU > 80% en {{ $labels.instance }}"
|
||||
action: "Investigar procesos, considerar escalado"
|
||||
|
||||
- alert: HighMemory
|
||||
expr: (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) > 0.85
|
||||
for: 5m
|
||||
labels:
|
||||
severity: high
|
||||
annotations:
|
||||
summary: "Memoria > 85% en {{ $labels.instance }}"
|
||||
action: "Investigar memory leaks, escalar RAM"
|
||||
|
||||
- alert: SlowQueries
|
||||
expr: histogram_quantile(0.95, rate(pg_slow_queries_duration_seconds_bucket[5m])) > 1
|
||||
for: 5m
|
||||
labels:
|
||||
severity: high
|
||||
annotations:
|
||||
summary: "Queries lentas p95 {{ $value }}s"
|
||||
action: "Analizar EXPLAIN PLAN, optimizar índices"
|
||||
|
||||
- alert: HighConnectionCount
|
||||
expr: (pg_stat_activity_count / pg_settings_max_connections) > 0.8
|
||||
for: 10m
|
||||
labels:
|
||||
severity: high
|
||||
annotations:
|
||||
summary: "Conexiones DB {{ $value }}%"
|
||||
action: "Investigar connection leaks, escalar max_connections"
|
||||
|
||||
- alert: DDoSDetected
|
||||
expr: rate(http_requests_total[5m]) > 10000
|
||||
for: 2m
|
||||
labels:
|
||||
severity: high
|
||||
annotations:
|
||||
summary: "Posible DDoS: {{ $value }} req/sec"
|
||||
action: "Activar rate limiting, contactar ISP"
|
||||
```
|
||||
|
||||
#### Alertas P3 (MEDIAS - 15 minutos)
|
||||
```yaml
|
||||
- alert: DiskSpaceLow
|
||||
expr: (node_filesystem_avail_bytes / node_filesystem_size_bytes) < 0.15
|
||||
for: 15m
|
||||
labels:
|
||||
severity: medium
|
||||
annotations:
|
||||
summary: "Disco < 15% en {{ $labels.instance }}"
|
||||
action: "Agendar escalado de almacenamiento"
|
||||
|
||||
- alert: BackupFailed
|
||||
expr: time() - backup_last_successful_timestamp > 86400 # 24h
|
||||
for: 1h
|
||||
labels:
|
||||
severity: medium
|
||||
annotations:
|
||||
summary: "Backup no completado en > 24h"
|
||||
action: "Verificar proceso de backup, logs"
|
||||
|
||||
- alert: CertificateExpiring
|
||||
expr: (ssl_cert_expire_timestamp - time()) / 86400 < 30
|
||||
labels:
|
||||
severity: medium
|
||||
annotations:
|
||||
summary: "SSL cert vence en {{ $value }} días"
|
||||
action: "Renovar certificado"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dashboards Disponibles
|
||||
|
||||
### Dashboard 1: Visión General (System Overview)
|
||||
|
||||
**URL**: `http://grafana.skynet.ttzr/d/overview`
|
||||
|
||||
**Paneles**:
|
||||
- Estado de servicios (verde/rojo)
|
||||
- Request rate (últimas 24h)
|
||||
- Error rate (trending)
|
||||
- CPU/Memoria (gauges)
|
||||
- Disk space (stacked)
|
||||
- Network I/O (dual axis)
|
||||
- Database connections
|
||||
- Top errors (tabla)
|
||||
|
||||
### Dashboard 2: Rendimiento de Aplicación (Application Performance)
|
||||
|
||||
**URL**: `http://grafana.skynet.ttzr/d/app-performance`
|
||||
|
||||
**Paneles**:
|
||||
- Response time p50/p95/p99
|
||||
- Throughput (requests/sec)
|
||||
- Error rate by endpoint
|
||||
- Hot endpoints (top 10)
|
||||
- Request distribution (by method)
|
||||
- Slowest endpoints
|
||||
- Error distribution by type
|
||||
- Request size distribution
|
||||
|
||||
### Dashboard 3: Rendimiento de Base de Datos (Database Performance)
|
||||
|
||||
**URL**: `http://grafana.skynet.ttzr/d/db-performance`
|
||||
|
||||
**Paneles**:
|
||||
- Transactions/sec
|
||||
- Query execution time percentiles
|
||||
- Slow queries (top 10)
|
||||
- Table sizes
|
||||
- Index usage
|
||||
- Cache hit ratio
|
||||
- Replication lag
|
||||
- Active connections
|
||||
- Lock contention
|
||||
- Autovacuum status
|
||||
|
||||
### Dashboard 4: Infraestructura y Hardware (Infrastructure)
|
||||
|
||||
**URL**: `http://grafana.skynet.ttzr/d/infrastructure`
|
||||
|
||||
**Paneles**:
|
||||
- CPU utilization (por core)
|
||||
- Memory breakdown (used/buffers/cache)
|
||||
- Load average
|
||||
- Disk I/O (read/write MB/s)
|
||||
- Disk space by mount point
|
||||
- Network throughput (in/out)
|
||||
- Network errors/dropped packets
|
||||
- TCP connection states
|
||||
- Inode usage
|
||||
|
||||
### Dashboard 5: Seguridad y Logs (Security)
|
||||
|
||||
**URL**: `http://grafana.skynet.ttzr/d/security`
|
||||
|
||||
**Paneles**:
|
||||
- Failed login attempts
|
||||
- SSH connection attempts
|
||||
- Firewall blocks (top IPs)
|
||||
- Privilege escalation attempts
|
||||
- API calls unauthorized
|
||||
- File integrity changes
|
||||
- Process anomalies
|
||||
- Network connections unusual
|
||||
|
||||
---
|
||||
|
||||
## Logs Importantes
|
||||
|
||||
### Ubicaciones de logs
|
||||
|
||||
```
|
||||
/var/log/skynet/
|
||||
├── core.log # Logs de aplicación principal
|
||||
├── api.log # Logs de API server
|
||||
├── database.log # Logs de conexiones DB
|
||||
└── error.log # Errores consolidados
|
||||
|
||||
/var/log/
|
||||
├── auth.log # Logins, sudo
|
||||
├── syslog # Mensajes del kernel
|
||||
├── fail2ban.log # Intentos de acceso fallidos
|
||||
└── postgresql/
|
||||
└── postgresql.log # Logs de PostgreSQL
|
||||
|
||||
/var/lib/postgresql/
|
||||
└── pg_log/ # Logs detallados de DB
|
||||
```
|
||||
|
||||
### Log Analysis Queries
|
||||
|
||||
#### ELK / Kibana
|
||||
|
||||
```json
|
||||
# Top 10 endpoints por error
|
||||
{
|
||||
"aggs": {
|
||||
"endpoints": {
|
||||
"terms": {
|
||||
"field": "endpoint.keyword",
|
||||
"size": 10,
|
||||
"order": {"errors": "desc"}
|
||||
},
|
||||
"aggs": {
|
||||
"errors": {
|
||||
"filter": {"range": {"status": {"gte": 500}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Response time trend
|
||||
{
|
||||
"aggs": {
|
||||
"time_trend": {
|
||||
"date_histogram": {
|
||||
"field": "@timestamp",
|
||||
"interval": "1m"
|
||||
},
|
||||
"aggs": {
|
||||
"p95_latency": {
|
||||
"percentiles": {
|
||||
"field": "response_time_ms",
|
||||
"percents": [95]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Failed logins por IP
|
||||
{
|
||||
"query": {
|
||||
"term": {"event": "failed_login"}
|
||||
},
|
||||
"aggs": {
|
||||
"by_ip": {
|
||||
"terms": {"field": "source_ip", "size": 20}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Comandos útiles de análisis
|
||||
|
||||
```bash
|
||||
# Top errores en última hora
|
||||
grep ERROR /var/log/skynet/error.log | grep -o "ERROR [^:]]*" | \
|
||||
sort | uniq -c | sort -rn | head -10
|
||||
|
||||
# Endpoints lentos
|
||||
grep "response_time" /var/log/skynet/api.log | \
|
||||
awk '{print $5, $1}' | sort -n | tail -10
|
||||
|
||||
# Intentos de acceso fallidos
|
||||
grep "Failed" /var/log/auth.log | \
|
||||
grep -o "from [0-9.]*" | sort | uniq -c | sort -rn
|
||||
|
||||
# Errors por hora
|
||||
grep ERROR /var/log/skynet/error.log | \
|
||||
cut -d' ' -f1 | cut -d: -f1-2 | uniq -c
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Instrumentación y Exporters
|
||||
|
||||
### Prometheus Node Exporter
|
||||
```bash
|
||||
# Verificar que está corriendo
|
||||
systemctl status prometheus-node-exporter
|
||||
|
||||
# Metrics disponibles
|
||||
curl http://localhost:9100/metrics | head -50
|
||||
|
||||
# Configuración
|
||||
cat /etc/prometheus/node_exporter_args
|
||||
# Típicamente: --collector.textfile.directory=/var/lib/node_exporter/textfile_collector
|
||||
```
|
||||
|
||||
### Custom Exporter (skynet-exporter)
|
||||
```bash
|
||||
# Métricas customizadas de Skynet
|
||||
curl http://localhost:9200/metrics | grep skynet_
|
||||
|
||||
# Ejemplos:
|
||||
# skynet_requests_total{endpoint="/api/v1/data"}
|
||||
# skynet_response_time_seconds_bucket{endpoint="/api/v1/data", le="0.1"}
|
||||
# skynet_database_connections{state="active"}
|
||||
# skynet_cache_hit_ratio
|
||||
```
|
||||
|
||||
### PostgreSQL Exporter
|
||||
```bash
|
||||
# Verificar exporter de PostgreSQL
|
||||
curl http://localhost:9187/metrics | grep pg_
|
||||
|
||||
# Métricas principales:
|
||||
# pg_stat_database_tup_fetched
|
||||
# pg_stat_database_tup_inserted
|
||||
# pg_stat_database_tup_updated
|
||||
# pg_stat_database_tup_deleted
|
||||
# pg_up (1 si DB está up, 0 si down)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checklist de Monitoreo Diario
|
||||
|
||||
- [ ] Revisar estado de todos los dashboards
|
||||
- [ ] Verificar que no hay alertas P1 sin resolver
|
||||
- [ ] Analizar tendencias de performance (¿empeorando?)
|
||||
- [ ] Verificar backup completó exitosamente
|
||||
- [ ] Revisar log de acceso para anomalías
|
||||
- [ ] Confirmar que replicación está al día
|
||||
- [ ] Verificar espacio en disco (< 85%)
|
||||
- [ ] Revisar certificados SSL (> 30 días para expirar)
|
||||
- [ ] Documentar incident report si hubo P1/P2
|
||||
|
||||
294
07_OPERACION/runbooks.md
Normal file
294
07_OPERACION/runbooks.md
Normal file
@@ -0,0 +1,294 @@
|
||||
# Runbooks - Operación Skynet v8
|
||||
|
||||
## Runbook: Reinicio de servicios
|
||||
|
||||
### Objetivo
|
||||
Reiniciar servicios del sistema sin afectar operaciones críticas.
|
||||
|
||||
### Procedimiento
|
||||
1. **Verificar estado actual**
|
||||
```bash
|
||||
systemctl status skynet-core
|
||||
systemctl status skynet-database
|
||||
systemctl status skynet-api
|
||||
```
|
||||
|
||||
2. **Notificar a usuarios (si aplica)**
|
||||
- Enviar notificación de mantenimiento planeado
|
||||
- Esperar confirmación de ventana de mantenimiento
|
||||
|
||||
3. **Reiniciar servicios en orden**
|
||||
```bash
|
||||
# Primero servicios auxiliares
|
||||
systemctl restart skynet-cache
|
||||
systemctl restart skynet-broker
|
||||
|
||||
# Luego servicios principales
|
||||
systemctl restart skynet-database
|
||||
sleep 30
|
||||
systemctl restart skynet-api
|
||||
sleep 20
|
||||
systemctl restart skynet-core
|
||||
```
|
||||
|
||||
4. **Verificar estado post-reinicio**
|
||||
```bash
|
||||
systemctl status skynet-core
|
||||
systemctl status skynet-database
|
||||
systemctl status skynet-api
|
||||
|
||||
# Verificar conectividad
|
||||
curl -s http://localhost:8080/health
|
||||
curl -s http://localhost:5432/ping
|
||||
```
|
||||
|
||||
5. **Validar operación normal**
|
||||
- Verificar logs sin errores críticos
|
||||
- Ejecutar health checks
|
||||
- Monitorear métricas durante 5 minutos
|
||||
|
||||
### Rollback
|
||||
Si hay fallos:
|
||||
```bash
|
||||
systemctl stop skynet-core
|
||||
systemctl stop skynet-api
|
||||
systemctl stop skynet-database
|
||||
|
||||
# Restaurar desde último snapshot conocido
|
||||
pg_restore -d skynet /backups/skynet_latest.sql
|
||||
systemctl start skynet-database
|
||||
systemctl start skynet-api
|
||||
systemctl start skynet-core
|
||||
```
|
||||
|
||||
### Tiempo estimado
|
||||
20-30 minutos con validación
|
||||
|
||||
---
|
||||
|
||||
## Runbook: Failover de base de datos
|
||||
|
||||
### Objetivo
|
||||
Cambiar a base de datos secundaria en caso de fallo de primaria.
|
||||
|
||||
### Prerrequisitos
|
||||
- Replicación configurada y activa
|
||||
- Sistema de monitoreo detectó fallo de primaria
|
||||
- Base de datos secundaria disponible
|
||||
|
||||
### Procedimiento
|
||||
|
||||
1. **Confirmar fallo de primaria**
|
||||
```bash
|
||||
# Intentar conectarse a primaria
|
||||
psql -h skynet-primary -U postgres -d skynet -c "SELECT 1"
|
||||
|
||||
# Verificar lag de replicación
|
||||
psql -h skynet-primary -U postgres -c "SELECT slot_name, restart_lsn FROM pg_replication_slots"
|
||||
```
|
||||
|
||||
2. **Promover secundaria**
|
||||
```bash
|
||||
# En servidor secundario
|
||||
pg_ctl promote -D /var/lib/postgresql/14/main
|
||||
|
||||
# Esperar 30 segundos para que complete
|
||||
sleep 30
|
||||
|
||||
# Verificar estado
|
||||
psql -U postgres -c "SELECT pg_is_wal_replay_paused()"
|
||||
```
|
||||
|
||||
3. **Redirigir aplicaciones**
|
||||
```bash
|
||||
# Actualizar DNS o connection string
|
||||
# En skynet-api.conf:
|
||||
# database_host = skynet-secondary
|
||||
|
||||
systemctl restart skynet-api
|
||||
```
|
||||
|
||||
4. **Verificar operación normal**
|
||||
```bash
|
||||
# Validar escrituras en nueva primaria
|
||||
psql -h skynet-secondary -U postgres -d skynet -c "INSERT INTO test VALUES (NOW())"
|
||||
|
||||
# Monitorear performance
|
||||
watch -n 2 'psql -h skynet-secondary -U postgres -c "SELECT count(*) FROM skynet_logs"'
|
||||
```
|
||||
|
||||
5. **Informar del failover**
|
||||
- Registrar en incident log
|
||||
- Notificar al equipo
|
||||
- Agendar recuperación de primaria
|
||||
|
||||
### Recovery de primaria
|
||||
```bash
|
||||
# Una vez primaria se recupere:
|
||||
pg_basebackup -h skynet-primary -D /var/lib/postgresql/14/main -U replication
|
||||
systemctl start postgresql
|
||||
```
|
||||
|
||||
### Tiempo estimado
|
||||
5-10 minutos
|
||||
|
||||
---
|
||||
|
||||
## Runbook: Restauración de backups
|
||||
|
||||
### Objetivo
|
||||
Restaurar datos desde backups en caso de corrupción o pérdida de datos.
|
||||
|
||||
### Tipos de restauración
|
||||
|
||||
#### 1. Restauración completa
|
||||
```bash
|
||||
# Detener servicios
|
||||
systemctl stop skynet-core
|
||||
systemctl stop skynet-api
|
||||
systemctl stop skynet-database
|
||||
|
||||
# Restaurar backup completo
|
||||
pg_restore -C -d postgres /backups/skynet_full_2025-12-30.sql
|
||||
|
||||
# Reiniciar servicios
|
||||
systemctl start skynet-database
|
||||
sleep 30
|
||||
systemctl start skynet-api
|
||||
systemctl start skynet-core
|
||||
```
|
||||
|
||||
#### 2. Restauración point-in-time (PITR)
|
||||
```bash
|
||||
# Restaurar hasta timestamp específico
|
||||
psql -U postgres -d skynet -c "
|
||||
SELECT pg_wal_replay_pause();
|
||||
SELECT pg_xact_xmin(xid) FROM pg_xact;
|
||||
"
|
||||
|
||||
# Restaurar WAL archive hasta timestamp
|
||||
pg_restore -U postgres -d skynet \
|
||||
-e -t tabla_critica /backups/skynet_full.sql
|
||||
|
||||
# Aplicar WAL hasta punto
|
||||
pg_wal_replay_start()
|
||||
```
|
||||
|
||||
#### 3. Restauración de tabla específica
|
||||
```bash
|
||||
# Restaurar solo tabla corrupta
|
||||
pg_restore -d skynet -t tabla_corrupta /backups/skynet_full.sql
|
||||
|
||||
# Validar integridad
|
||||
ANALYZE tabla_corrupta;
|
||||
```
|
||||
|
||||
### Validación post-restauración
|
||||
```bash
|
||||
# Verificar integridad
|
||||
psql -U postgres -d skynet -c "SELECT COUNT(*) FROM pg_stat_user_tables"
|
||||
|
||||
# Comparar checksums
|
||||
pg_basebackup --wal-method=fetch -l "restore_$(date +%s)"
|
||||
|
||||
# Validar índices
|
||||
REINDEX DATABASE skynet;
|
||||
```
|
||||
|
||||
### Tiempo estimado
|
||||
- Completa: 30-60 minutos (depende tamaño)
|
||||
- PITR: 15-45 minutos
|
||||
- Tabla: 5-15 minutos
|
||||
|
||||
---
|
||||
|
||||
## Runbook: Escalado de recursos
|
||||
|
||||
### Objetivo
|
||||
Aumentar capacidad de computo o almacenamiento sin downtime.
|
||||
|
||||
### Escalado de CPU/RAM
|
||||
|
||||
1. **Evaluar necesidad**
|
||||
```bash
|
||||
# Monitorear uso actual
|
||||
top -n 1 | head -20
|
||||
free -h
|
||||
|
||||
# Proyectar crecimiento
|
||||
# Si uso > 80%, escalar inmediatamente
|
||||
# Si proyectado > 80% en 7 días, escalar
|
||||
```
|
||||
|
||||
2. **Escalar infraestructura**
|
||||
```bash
|
||||
# En cloud provider o hypervisor
|
||||
# Aumentar CPU cores
|
||||
# Aumentar memoria RAM
|
||||
# Aplicar cambios sin reinicio (si soportado)
|
||||
```
|
||||
|
||||
3. **Verificar en SO**
|
||||
```bash
|
||||
lscpu
|
||||
free -h
|
||||
```
|
||||
|
||||
4. **Rebalancear servicios**
|
||||
```bash
|
||||
# Aumentar workers/threads en config
|
||||
systemctl restart skynet-api
|
||||
|
||||
# Aumentar shared_buffers en PostgreSQL
|
||||
# postgresql.conf: shared_buffers = 16GB (en lugar de 8GB)
|
||||
systemctl restart skynet-database
|
||||
```
|
||||
|
||||
### Escalado de almacenamiento
|
||||
|
||||
1. **Monitorear uso**
|
||||
```bash
|
||||
df -h /var/lib/postgresql
|
||||
du -sh /backups
|
||||
|
||||
# Alerta si > 80% utilizado
|
||||
```
|
||||
|
||||
2. **Agregar espacio**
|
||||
```bash
|
||||
# Opción 1: Aumentar volumen existente
|
||||
lvextend -l +50G /dev/vg0/lv_data
|
||||
resize2fs /dev/vg0/lv_data
|
||||
|
||||
# Opción 2: Agregar nuevo volumen
|
||||
# Montar en /data2
|
||||
# Configurar replicación a nuevo volumen
|
||||
```
|
||||
|
||||
3. **Validar cambios**
|
||||
```bash
|
||||
df -h /var/lib/postgresql
|
||||
# Debe mostrar nuevo tamaño
|
||||
```
|
||||
|
||||
4. **Monitorear performance**
|
||||
- Velocidad I/O
|
||||
- Latencia de queries
|
||||
- Crecimiento de espacios
|
||||
|
||||
### Tiempo estimado
|
||||
- CPU/RAM: 30 minutos - 2 horas (depende downtime)
|
||||
- Almacenamiento: 1-4 horas (sin downtime posible)
|
||||
|
||||
---
|
||||
|
||||
## Escalabilidad Matriz
|
||||
|
||||
| Recurso | Umbral Acción | Aumento | Tiempo |
|
||||
|---------|---|---|---|
|
||||
| CPU | >85% x 5min | +2 cores | 30min-2h |
|
||||
| RAM | >80% x 10min | +8GB | 30min-2h |
|
||||
| Disco | >85% utilizado | +50% capacidad | 1-4h |
|
||||
| Conexiones DB | >80% max_connections | +50 conexiones | 15min |
|
||||
| Replication lag | >10GB | Increase bandwidth | Immediate |
|
||||
|
||||
Reference in New Issue
Block a user