📋 PROMPT DE CONTINUACIÓN - Fase 4: Sistema de Control Local + Integración Cloud =============================================================================== CONTEXTO ARQUITECTÓNICO CONFIRMADO =============================================================================== ┌─────────────────────────────────────────────────────┐ │ API Central Cloud (ya existe) │ │ https://api.siax-system.net │ │ - Dashboard público para analytics │ │ - Recibe reportes de estado de agents │ │ - NO controla directamente los procesos │ └─────────────────────────────────────────────────────┘ ▲ │ POST /apps_servcs/apps │ (reportes de estado) │ ┌────────────────────────┴─────────────────────────────┐ │ SIAX Agent (este proyecto) │ │ http://192.168.x.x:8080 (solo VPN) │ │ │ │ ✅ YA TIENE: │ │ - monitor.rs: Detecta procesos Node.js │ │ - interface.rs: Panel web local │ │ - logger.rs: Sistema de logs │ │ - config.rs: Gestión de apps monitoreadas │ │ │ │ 🎯 NECESITA (Fase 4): │ │ 1. Panel Web: Start/Stop/Restart procesos │ │ 2. Systemd: Gestionar servicios .service │ │ 3. Logs en Tiempo Real: journalctl streaming │ │ 4. Webhook (opcional): Recibir comandos externos │ │ 5. Evolución monitor.rs: Reconciliar systemd │ └───────────────────────────────────────────────────────┘ =============================================================================== REQUISITOS TÉCNICOS - FASE 4 =============================================================================== ------------------------------------------------------------------------------- A. SYSTEMD INTEGRATION (src/systemd/) ------------------------------------------------------------------------------- Objetivo: Gestionar servicios systemd para Node.js y Python (FastAPI). Funcionalidades: 1. service_generator.rs: Generar archivos .service dinámicamente pub fn create_service(config: ServiceConfig) -> Result<(), SystemdError> // Genera /etc/systemd/system/{app_name}.service // Soporta Node.js y Python/FastAPI 2. systemctl.rs: Wrapper de comandos systemctl pub fn start(service_name: &str) -> Result<(), SystemdError> pub fn stop(service_name: &str) -> Result<(), SystemdError> pub fn restart(service_name: &str) -> Result<(), SystemdError> pub fn status(service_name: &str) -> ServiceStatus pub fn enable(service_name: &str) -> Result<(), SystemdError> 3. parser.rs: Parsear salida de systemctl pub fn parse_status_output(output: &str) -> ServiceStatus // Detecta: active, inactive, failed, restarting 4. Manejo de permisos sudo: - Detectar si comandos fallan por permisos - Loggear claramente en UI si falta configuración sudoers - Validaciones previas: verificar que script_path existe, user existe, working_dir válido ------------------------------------------------------------------------------- B. ORCHESTRATOR (src/orchestrator/) ------------------------------------------------------------------------------- Objetivo: Lógica de ciclo de vida de aplicaciones. Funcionalidades: 1. app_manager.rs: CRUD de aplicaciones pub fn register_app(config: ServiceConfig) -> Result<(), OrchestratorError> pub fn unregister_app(app_name: &str) -> Result<(), OrchestratorError> pub fn list_apps() -> Vec 2. lifecycle.rs: Control de estados pub fn start_app(app_name: &str) -> Result<(), OrchestratorError> pub fn stop_app(app_name: &str) -> Result<(), OrchestratorError> pub fn restart_app(app_name: &str) -> Result<(), OrchestratorError> 3. Rate limiting: Máximo 1 operación por segundo por app (prevenir spam) 4. Recovery automático: Si estado inconsistente → intentar reconciliar ------------------------------------------------------------------------------- C. API LOCAL (src/api/) ------------------------------------------------------------------------------- Objetivo: Endpoints HTTP para el panel web local. Funcionalidades: 1. handlers.rs: Endpoints REST POST /api/apps/:name/start POST /api/apps/:name/stop POST /api/apps/:name/restart GET /api/apps/:name/status GET /api/apps POST /api/apps/register // Crear nuevo servicio systemd DELETE /api/apps/:name // Eliminar servicio 2. websocket.rs: LogStreamer en tiempo real pub struct LogStreamer { app_name: String, process: Child, // journalctl -u {app_name} -f --output=json } // WS /logs/:app_name // - Parsear JSON de journalctl // - Enviar líneas vía WebSocket // - Manejo de backpressure // - Cleanup al desconectar // - Límite de conexiones simultáneas por app 3. Webhook (opcional, análisis futuro): POST /webhook/command { "action": "restart", "app_name": "fidelizacion", "secret": "..." } 4. dto.rs: Schemas de validación (request/response) ------------------------------------------------------------------------------- D. EVOLUCIÓN DE monitor.rs ------------------------------------------------------------------------------- Objetivo: Reconciliar detección automática (sysinfo) vs systemd. Cambios: 1. Doble detección: for app in apps_to_monitor { let process_detected = detect_in_sysinfo(&app.name); let systemd_status = systemctl::status(&app.name); let final_status = match (process_detected, systemd_status) { (true, ServiceStatus::Active) => "running", (false, ServiceStatus::Active) => "crashed", // ⚠️ Alerta (false, ServiceStatus::Failed) => "failed", (true, ServiceStatus::Inactive) => "zombie", // ⚠️ Alerta _ => "unknown" }; send_to_cloud(final_status); } 2. Reportar discrepancias a logs y API central 3. Mantener compatibilidad con detección actual (no romper funcionalidad existente) ------------------------------------------------------------------------------- E. INTERFACE WEB (evolucionar interface.rs) ------------------------------------------------------------------------------- Objetivo: Panel de control completo sin eliminar funcionalidad actual. Nuevas features: 1. Página de gestión de apps: - Tabla con: App Name | Status | PID | CPU | RAM | Actions - Botones: ▶️ Start | ⏹️ Stop | 🔄 Restart | 📊 Logs | 🗑️ Delete - Indicador visual si falta sudo (banner amarillo) 2. Formulario de registro de apps: - Campos: app_name, script_path, user, working_dir, environment vars - Validación client-side y server-side - Soporte para Node.js y Python 3. Visor de logs en tiempo real: - Conectar vía WebSocket a /logs/:app_name - Auto-scroll, filtros por nivel, búsqueda - Botón de pause/resume 4. Mantener páginas actuales: - /scan (escaneo de procesos) - /select (selección de procesos) - /logs (logs del sistema) ------------------------------------------------------------------------------- F. TESTING (nuevo archivo tests/integration_test.rs) ------------------------------------------------------------------------------- Objetivo: Tests de integración end-to-end. Casos de prueba: 1. Registrar app de prueba (Node.js y Python) 2. Start → verificar PID existe 3. Stop → verificar PID desaparece 4. Restart → verificar nuevo PID 5. Leer logs vía WebSocket (primeras 10 líneas) 6. Eliminar app → verificar limpieza completa 7. Test de rate limiting 8. Test de validaciones (script inexistente, user inválido) ------------------------------------------------------------------------------- G. DEPLOYMENT (desplegar_agent.sh) ------------------------------------------------------------------------------- Objetivo: Script de instalación automática production-ready. Funcionalidades: 1. Verificar dependencias (systemd, sudo, rust) 2. Compilar release 3. Configurar sudoers si es necesario: # /etc/sudoers.d/siax-agent siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl 4. Crear servicio systemd para el agente mismo 5. Verificación post-deploy (health check) 6. Rollback automático si falla =============================================================================== CRITERIOS DE ACEPTACIÓN =============================================================================== ✅ Panel web permite start/stop/restart desde UI ✅ Soporte Node.js y Python (FastAPI) ✅ Logs en tiempo real vía WebSocket ✅ Detección de apps crasheadas (reconciliación systemd) ✅ Validaciones de permisos, paths, users ✅ Rate limiting funcional ✅ Tests de integración pasando ✅ Script de deploy funcional ✅ Sin eliminar funcionalidad existente =============================================================================== PRÓXIMOS PASOS =============================================================================== 1. Implementar src/models/ (ServiceConfig, ManagedApp, etc.) 2. Implementar src/systemd/ (service_generator, systemctl, parser) 3. Implementar src/orchestrator/ (app_manager, lifecycle) 4. Implementar src/api/ (handlers, websocket, dto) 5. Evolucionar monitor.rs (reconciliación systemd) 6. Evolucionar interface.rs (panel de control completo) 7. Crear tests/integration_test.rs 8. Crear desplegar_agent.sh 9. Actualizar Cargo.toml con nuevas dependencias 10. Testing completo y ajustes finales