# Guia de Despliegue - CBCFacil Esta guia describe las opciones y procedimientos para desplegar CBCFacil en diferentes entornos. ## Opciones de Despliegue | Metodo | Complejidad | Recomendado para | |--------|-------------|------------------| | Docker Compose | Baja | Desarrollo, Produccion ligera | | Docker Standalone | Media | Produccion con orquestacion | | Virtual Environment | Baja | Desarrollo local | | Kubernetes | Alta | Produccion a escala | ## Despliegue con Docker Compose ### Prerrequisitos - Docker 24.0+ - Docker Compose 2.20+ - NVIDIA Container Toolkit (para GPU) ### Configuracion 1. Crear archivo de configuracion: ```bash cp .env.example .env.production nano .env.production ``` 2. Configurar variables sensibles: ```bash # .env.production NEXTCLOUD_URL=https://nextcloud.example.com/remote.php/webdav NEXTCLOUD_USER=tu_usuario NEXTCLOUD_PASSWORD=tu_contrasena_segura ANTHROPIC_AUTH_TOKEN=sk-ant-... GEMINI_API_KEY=AIza... TELEGRAM_TOKEN=bot_token TELEGRAM_CHAT_ID=chat_id CUDA_VISIBLE_DEVICES=all LOG_LEVEL=INFO ``` 3. Verificar docker-compose.yml: ```yaml # docker-compose.yml version: '3.8' services: cbcfacil: build: . container_name: cbcfacil restart: unless-stopped ports: - "5000:5000" volumes: - ./downloads:/app/downloads - ./resumenes_docx:/app/resumenes_docx - ./logs:/app/logs - ./data:/app/data environment: - NEXTCLOUD_URL=${NEXTCLOUD_URL} - NEXTCLOUD_USER=${NEXTCLOUD_USER} - NEXTCLOUD_PASSWORD=${NEXTCLOUD_PASSWORD} - ANTHROPIC_AUTH_TOKEN=${ANTHROPIC_AUTH_TOKEN} - GEMINI_API_KEY=${GEMINI_API_KEY} - TELEGRAM_TOKEN=${TELEGRAM_TOKEN} - TELEGRAM_CHAT_ID=${TELEGRAM_CHAT_ID} - CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES} - LOG_LEVEL=${LOG_LEVEL} deploy: resources: reservations: devices: - driver: nvidia count: all capabilities: [gpu] healthcheck: test: ["CMD", "curl", "-f", "http://localhost:5000/health"] interval: 30s timeout: 10s retries: 3 ``` ### Despliegue ```bash # Construir y levantar docker compose up -d --build # Ver logs docker compose logs -f cbcfacil # Ver estado docker compose ps # Reiniciar docker compose restart cbcfacil # Detener docker compose down ``` ### Actualizacion ```bash # Hacer backup de datos docker cp cbcfacil:/app/data ./backup/data # Actualizar imagen docker compose pull docker compose up -d --build # Verificar docker compose logs -f cbcfacil ``` ## Despliegue con Docker Standalone ### Construir Imagen ```bash # Construir imagen docker build -t cbcfacil:latest . # Verificar imagen docker images cbcfacil ``` ### Ejecutar Contenedor ```bash # Con GPU docker run -d \ --name cbcfacil \ --gpus all \ -p 5000:5000 \ -v $(pwd)/downloads:/app/downloads \ -v $(pwd)/resumenes_docx:/app/resumenes_docx \ -v $(pwd)/logs:/app/logs \ -e NEXTCLOUD_URL=${NEXTCLOUD_URL} \ -e NEXTCLOUD_USER=${NEXTCLOUD_USER} \ -e NEXTCLOUD_PASSWORD=${NEXTCLOUD_PASSWORD} \ -e ANTHROPIC_AUTH_TOKEN=${ANTHROPIC_AUTH_TOKEN} \ -e GEMINI_API_KEY=${GEMINI_API_KEY} \ cbcfacil:latest # Ver logs docker logs -f cbcfacil # Detener docker stop cbcfacil && docker rm cbcfacil ``` ## Despliegue Local (Virtual Environment) ### Prerrequisitos - Python 3.10+ - NVIDIA drivers (opcional) ### Instalacion ```bash # Clonar y entrar al directorio git clone cd cbcfacil # Crear entorno virtual python3 -m venv .venv source .venv/bin/activate # Instalar dependencias pip install -r requirements.txt # Configurar variables de entorno cp .env.example .env.production nano .env.production # Crear directorios mkdir -p downloads resumenes_docx logs data # Ejecutar python main.py ``` ### Como Servicio Systemd ```ini # /etc/systemd/system/cbcfacil.service [Unit] Description=CBCFacil AI Service After=network.target [Service] Type=simple User=cbcfacil WorkingDirectory=/opt/cbcfacil Environment="PATH=/opt/cbcfacil/.venv/bin" EnvironmentFile=/opt/cbcfacil/.env.production ExecStart=/opt/cbcfacil/.venv/bin/python main.py Restart=always RestartSec=10 # Logging StandardOutput=journal StandardError=journal SyslogIdentifier=cbcfacil [Install] WantedBy=multi-user.target ``` ```bash # Instalar servicio sudo cp cbcfacil.service /etc/systemd/system/ sudo systemctl daemon-reload sudo systemctl enable cbcfacil sudo systemctl start cbcfacil # Verificar estado sudo systemctl status cbcfacil # Ver logs journalctl -u cbcfacil -f ``` ## Configuracion de Produccion ### Variables de Entorno Criticas ```bash # Obligatorias NEXTCLOUD_URL=... NEXTCLOUD_USER=... NEXTCLOUD_PASSWORD=... # Recomendadas para produccion DEBUG=false LOG_LEVEL=WARNING POLL_INTERVAL=10 # GPU CUDA_VISIBLE_DEVICES=all ``` ### Optimizaciones ```bash # En .env.production # Reducir polling para menor carga POLL_INTERVAL=10 # Optimizar memoria GPU PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:512 # Limitar threads OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 ``` ### Seguridad ```bash # Crear usuario dedicado sudo useradd -r -s /bin/false cbcfacil # Asignar permisos sudo chown -R cbcfacil:cbcfacil /opt/cbcfacil # Proteger archivo de variables sudo chmod 600 /opt/cbcfacil/.env.production ``` ## Monitoreo ### Health Check ```bash # Endpoint de salud curl http://localhost:5000/health # Respuesta esperada {"status": "healthy"} ``` ### Logging ```bash # Ver logs en tiempo real docker logs -f cbcfacil # O con journalctl journalctl -u cbcfacil -f # Logs estructurados en JSON (produccion) LOG_LEVEL=WARNING ``` ### Metricas El sistema expone metricas via API: ```bash # Estado del servicio curl http://localhost:5000/api/status ``` ## Respaldo y Recuperacion ### Respaldo de Datos ```bash # Directorios a respaldar # - downloads/ (archivos procesados) # - resumenes_docx/ (documentos generados) # - data/ (registros y estados) # - logs/ (logs del sistema) # Script de backup #!/bin/bash DATE=$(date +%Y%m%d_%H%M%S) BACKUP_DIR=/backup/cbcfacil mkdir -p $BACKUP_DIR tar -czf $BACKUP_DIR/cbcfacil_$DATE.tar.gz \ /opt/cbcfacil/downloads \ /opt/cbcfacil/resumenes_docx \ /opt/cbcfacil/data # Limpiar backups antiguos (mantener ultimos 7 dias) find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete ``` ### Recuperacion ```bash # Detener servicio docker compose down # Restaurar datos tar -xzf backup_*.tar.gz -C /opt/cbcfacil/ # Verificar permisos chown -R cbcfacil:cbcfacil /opt/cbcfacil # Reiniciar servicio docker compose up -d ``` ## Troubleshooting de Produccion ### Contenedor no Inicia ```bash # Verificar logs docker logs cbcfacil # Verificar configuracion docker exec -it cbcfacil python -c "from config import settings; print(settings.has_webdav_config)" ``` ### Error de Memoria GPU ```bash # Verificar GPUs disponibles nvidia-smi # Liberar memoria sudo nvidia-smi --gpu-reset # O limitar GPU CUDA_VISIBLE_DEVICES=0 ``` ### WebDAV Connection Failed ```bash # Verificar conectividad curl -u $NEXTCLOUD_USER:$NEXTCLOUD_PASSWORD $NEXTCLOUD_URL # Verificar credenciales echo "URL: $NEXTCLOUD_URL" echo "User: $NEXTCLOUD_USER" ``` ### High CPU Usage ```bash # Reducir threads OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 # Aumentar intervalo de polling POLL_INTERVAL=15 ``` ## Checklist de Produccion - [ ] Variables de entorno configuradas - [ ] Credenciales seguras (.env.production) - [ ] Usuario dedicado creado - [ ] Permisos correctos asignados - [ ] Logs configurados - [ ] Health check funcionando - [ ] Backup automatizado configurado - [ ] Monitoreo activo - [ ] SSL/TLS configurado (si aplica) - [ ] Firewall configurado ## Recursos Adicionales - `docs/SETUP.md` - Guia de configuracion inicial - `docs/TESTING.md` - Guia de testing - `ARCHITECTURE.md` - Documentacion arquitectonica