From 8822e9e6b58098b2f51dedb30cf338d0c64f795e Mon Sep 17 00:00:00 2001 From: pablinux Date: Sun, 18 Jan 2026 03:26:42 -0500 Subject: [PATCH] feat: Mejorar estructura de monitored_apps.json con metadata completa MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Añadir campos al modelo MonitoredApp: * service_name: Nombre del servicio systemd * path: WorkingDirectory de la aplicación * entry_point: Archivo de entrada (server.js, app.js, etc.) * node_bin: Ruta completa al binario de node/python * mode: Modo de ejecución (production, development, test) * service_file_path: Ruta al archivo .service de systemd * registered_at: Timestamp de registro (ISO 8601) - Actualizar discovery.rs para extraer toda la información: * Parsear ExecStart para obtener node_bin y entry_point * Extraer NODE_ENV para determinar el modo * Guardar ruta completa al archivo .service * Usar add_app_full() con información completa - Integrar ConfigManager en AppManager: * Guardar automáticamente en monitored_apps.json al registrar apps * Eliminar del JSON al desregistrar apps * Extraer metadata desde ServiceConfig (puerto, entry_point, mode, etc.) - Mantener retrocompatibilidad con JSON antiguo mediante campos deprecated - Todos los nuevos campos usan #[serde(default)] para evitar errores de deserialización --- desplegar_agent.sh | 368 ++------------ instalador.sh | 347 ++++++++++++++ install-remote.sh | 315 ++++++++++++ logs/errors.log | 240 ++++++++++ preparar_binario.sh | 66 +++ src/config.rs | 77 ++- src/discovery.rs | 87 +++- src/orchestrator/app_manager.rs | 50 ++ web/api-docs.html | 648 +++++++++++++++++++------ web/blog.html | 764 ++++++++++++++++++++++++++++++ web/health.html | 563 ++++++++++++++++++++++ web/index.html | 173 ++++--- web/logs.html | 33 +- web/register.html | 39 +- web/scan.html | 23 +- web/select.html | 28 +- web/static/icon/favicon.ico | Bin 0 -> 41624 bytes web/static/icon/favicon.svg | 44 ++ web/static/icon/logo.png | Bin 0 -> 11497 bytes web/static/icon/logo_telco128.png | Bin 0 -> 5832 bytes web/success.html | 23 +- 21 files changed, 3246 insertions(+), 642 deletions(-) create mode 100755 instalador.sh create mode 100644 install-remote.sh create mode 100755 preparar_binario.sh create mode 100644 web/blog.html create mode 100644 web/health.html create mode 100644 web/static/icon/favicon.ico create mode 100644 web/static/icon/favicon.svg create mode 100644 web/static/icon/logo.png create mode 100644 web/static/icon/logo_telco128.png diff --git a/desplegar_agent.sh b/desplegar_agent.sh index 1581f0b..7d864ea 100755 --- a/desplegar_agent.sh +++ b/desplegar_agent.sh @@ -1,347 +1,51 @@ #!/bin/bash -####################################### -# SIAX Agent - Script de Despliegue -# Instalación automática production-ready -####################################### +# --- CONFIGURACIÓN --- +BINARY_NAME="siax_monitor" +TARGET="x86_64-unknown-linux-gnu" +LOCAL_PATH="target/$TARGET/release/$BINARY_NAME" -set -e # Salir si hay errores +# 1. Preguntar método de transferencia +echo "Selecciona el método de transferencia:" +select METODO in "scp" "rsync"; do + case $METODO in + scp|rsync) break ;; + *) echo "Opción inválida, elige 1 o 2." ;; + esac +done -# Colores para output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color +# 2. Compilar +echo "📦 Compilando..." +cargo build --release --target $TARGET +if [ $? -ne 0 ]; then echo "❌ Error en compilación"; exit 1; fi -# Variables -INSTALL_DIR="/opt/siax-agent" -SERVICE_USER="siax-agent" -BACKUP_DIR="/tmp/siax-agent-backup-$(date +%s)" +# --- FUNCIÓN DE SUBIDA --- +upload_file() { + local IP=$1 + local USER=$2 + local DEST=$3 -####################################### -# Funciones -####################################### + echo "🚀 Subiendo a $USER@$IP vía $METODO..." -print_header() { - echo -e "${BLUE}" - echo "============================================" - echo " SIAX Agent - Deployment Script" - echo "============================================" - echo -e "${NC}" -} - -print_success() { - echo -e "${GREEN}✅ $1${NC}" -} - -print_error() { - echo -e "${RED}❌ $1${NC}" -} - -print_warning() { - echo -e "${YELLOW}⚠️ $1${NC}" -} - -print_info() { - echo -e "${BLUE}ℹ️ $1${NC}" -} - -check_root() { - if [ "$EUID" -ne 0 ]; then - print_error "Este script debe ejecutarse como root" - echo "Usa: sudo ./desplegar_agent.sh" - exit 1 - fi -} - -check_dependencies() { - print_info "Verificando dependencias..." - - local deps=("systemctl" "cargo" "rustc") - local missing=() - - for dep in "${deps[@]}"; do - if ! command -v $dep &> /dev/null; then - missing+=($dep) - fi - done - - if [ ${#missing[@]} -ne 0 ]; then - print_error "Faltan dependencias: ${missing[*]}" - echo "" - echo "Instalación de Rust:" - echo " curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh" - echo "" - echo "Instalación de systemd (debería estar instalado por defecto):" - echo " sudo apt-get install systemd # Debian/Ubuntu" - echo " sudo yum install systemd # RedHat/CentOS" - exit 1 - fi - - print_success "Todas las dependencias están instaladas" -} - -backup_existing() { - if [ -d "$INSTALL_DIR" ]; then - print_warning "Instalación existente detectada" - print_info "Creando backup en: $BACKUP_DIR" - mkdir -p "$BACKUP_DIR" - cp -r "$INSTALL_DIR" "$BACKUP_DIR/" - print_success "Backup creado" - fi -} - -compile_release() { - print_info "Compilando SIAX Agent en modo release..." - - if cargo build --release; then - print_success "Compilación exitosa" + if [ "$METODO" = "scp" ]; then + scp "$LOCAL_PATH" "$USER@$IP:$DEST/" else - print_error "Error en la compilación" - rollback - exit 1 + # rsync -avz: a (archivo/permisos), v (visual), z (comprimido) + rsync -avz "$LOCAL_PATH" "$USER@$IP:$DEST/" fi -} -create_user() { - if id "$SERVICE_USER" &>/dev/null; then - print_info "Usuario $SERVICE_USER ya existe" + if [ $? -eq 0 ]; then + echo "✅ $IP: Completado." else - print_info "Creando usuario del sistema: $SERVICE_USER" - useradd --system --no-create-home --shell /bin/false "$SERVICE_USER" - print_success "Usuario creado" + echo "❌ $IP: Falló la subida." fi } -install_binary() { - print_info "Instalando binario en $INSTALL_DIR..." +# --- LISTA DE SERVIDORES --- +# Formato: upload_file "IP" "USUARIO" "RUTA_DESTINO" +upload_file "192.168.10.145" "root" "/root/app" +upload_file "192.168.10.150" "pablinux" "/home/pablinux/app" +upload_file "192.168.10.160" "user_apps" "/home/user_apps/apps" - mkdir -p "$INSTALL_DIR" - mkdir -p "$INSTALL_DIR/config" - mkdir -p "$INSTALL_DIR/logs" - - cp target/release/siax_monitor "$INSTALL_DIR/siax-agent" - chmod +x "$INSTALL_DIR/siax-agent" - - # Copiar archivos de configuración si existen - if [ -f "config/monitored_apps.json" ]; then - cp config/monitored_apps.json "$INSTALL_DIR/config/" - fi - - # Copiar archivos web - if [ -d "web" ]; then - cp -r web "$INSTALL_DIR/" - fi - - # Permisos - chown -R $SERVICE_USER:$SERVICE_USER "$INSTALL_DIR" - - print_success "Binario instalado" -} - -configure_sudoers() { - print_info "Configurando permisos sudo para systemctl..." - - local sudoers_file="/etc/sudoers.d/siax-agent" - - cat > "$sudoers_file" << EOF -# SIAX Agent - Permisos para gestionar servicios systemd -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl start * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl stop * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl restart * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl status * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl enable * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl disable * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl daemon-reload -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl is-active * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl list-unit-files * -$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/journalctl * -EOF - - chmod 0440 "$sudoers_file" - - # Validar sintaxis - if visudo -c -f "$sudoers_file" &>/dev/null; then - print_success "Configuración de sudoers creada" - else - print_error "Error en configuración de sudoers" - rm -f "$sudoers_file" - exit 1 - fi -} - -create_systemd_service() { - print_info "Creando servicio systemd para SIAX Agent..." - - cat > /etc/systemd/system/siax-agent.service << EOF -[Unit] -Description=SIAX Agent - Process Monitor and Manager -After=network.target - -[Service] -Type=simple -User=$SERVICE_USER -WorkingDirectory=$INSTALL_DIR -ExecStart=$INSTALL_DIR/siax-agent -Restart=always -RestartSec=10 -StandardOutput=journal -StandardError=journal - -# Security hardening -NoNewPrivileges=true -PrivateTmp=true -ProtectSystem=strict -ReadWritePaths=$INSTALL_DIR/config $INSTALL_DIR/logs /etc/systemd/system -ProtectHome=true - -[Install] -WantedBy=multi-user.target -EOF - - systemctl daemon-reload - systemctl enable siax-agent.service - - print_success "Servicio systemd creado y habilitado" -} - -verify_installation() { - print_info "Verificando instalación..." - - local errors=0 - - # Verificar binario - if [ ! -f "$INSTALL_DIR/siax-agent" ]; then - print_error "Binario no encontrado" - ((errors++)) - fi - - # Verificar permisos - if [ ! -r "$INSTALL_DIR/siax-agent" ]; then - print_error "Permisos incorrectos en binario" - ((errors++)) - fi - - # Verificar servicio - if ! systemctl is-enabled siax-agent.service &>/dev/null; then - print_error "Servicio no habilitado" - ((errors++)) - fi - - # Verificar sudoers - if [ ! -f "/etc/sudoers.d/siax-agent" ]; then - print_warning "Configuración de sudoers no encontrada" - echo " El agente podría tener problemas para gestionar servicios" - fi - - if [ $errors -eq 0 ]; then - print_success "Verificación exitosa" - return 0 - else - print_error "Verificación falló con $errors errores" - return 1 - fi -} - -start_service() { - print_info "Iniciando SIAX Agent..." - - if systemctl start siax-agent.service; then - sleep 2 - if systemctl is-active siax-agent.service &>/dev/null; then - print_success "SIAX Agent iniciado correctamente" - return 0 - else - print_error "SIAX Agent no pudo iniciarse" - echo "" - echo "Ver logs con: journalctl -u siax-agent.service -n 50" - return 1 - fi - else - print_error "Error al iniciar el servicio" - return 1 - fi -} - -rollback() { - print_warning "Ejecutando rollback..." - - systemctl stop siax-agent.service 2>/dev/null || true - systemctl disable siax-agent.service 2>/dev/null || true - - if [ -d "$BACKUP_DIR" ]; then - rm -rf "$INSTALL_DIR" - cp -r "$BACKUP_DIR/siax-agent" "$INSTALL_DIR" - systemctl start siax-agent.service 2>/dev/null || true - print_success "Rollback completado" - else - print_warning "No hay backup disponible para rollback" - fi -} - -print_summary() { - echo "" - echo -e "${GREEN}============================================${NC}" - echo -e "${GREEN} ✅ SIAX Agent instalado exitosamente${NC}" - echo -e "${GREEN}============================================${NC}" - echo "" - echo "📊 Interface Web: http://localhost:8080" - echo "🔌 API REST: http://localhost:8081/api" - echo "📡 WebSocket: ws://localhost:8081/ws/logs/:app_name" - echo "" - echo "Comandos útiles:" - echo " Estado: sudo systemctl status siax-agent" - echo " Logs: sudo journalctl -u siax-agent -f" - echo " Reiniciar: sudo systemctl restart siax-agent" - echo " Detener: sudo systemctl stop siax-agent" - echo "" - echo "Directorio de instalación: $INSTALL_DIR" - echo "Configuración: $INSTALL_DIR/config/monitored_apps.json" - echo "" -} - -####################################### -# Main -####################################### - -main() { - print_header - - check_root - check_dependencies - backup_existing - compile_release - create_user - install_binary - configure_sudoers - create_systemd_service - - if verify_installation; then - if start_service; then - print_summary - exit 0 - else - print_error "El servicio no pudo iniciarse correctamente" - print_info "Revisa los logs: journalctl -u siax-agent -n 50" - echo "" - echo "¿Deseas hacer rollback? (y/n)" - read -r response - if [[ "$response" =~ ^[Yy]$ ]]; then - rollback - fi - exit 1 - fi - else - print_error "La verificación falló" - echo "" - echo "¿Deseas hacer rollback? (y/n)" - read -r response - if [[ "$response" =~ ^[Yy]$ ]]; then - rollback - fi - exit 1 - fi -} - -main +echo "------------------------------------------------" +echo "Done!" diff --git a/instalador.sh b/instalador.sh new file mode 100755 index 0000000..1581f0b --- /dev/null +++ b/instalador.sh @@ -0,0 +1,347 @@ +#!/bin/bash + +####################################### +# SIAX Agent - Script de Despliegue +# Instalación automática production-ready +####################################### + +set -e # Salir si hay errores + +# Colores para output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Variables +INSTALL_DIR="/opt/siax-agent" +SERVICE_USER="siax-agent" +BACKUP_DIR="/tmp/siax-agent-backup-$(date +%s)" + +####################################### +# Funciones +####################################### + +print_header() { + echo -e "${BLUE}" + echo "============================================" + echo " SIAX Agent - Deployment Script" + echo "============================================" + echo -e "${NC}" +} + +print_success() { + echo -e "${GREEN}✅ $1${NC}" +} + +print_error() { + echo -e "${RED}❌ $1${NC}" +} + +print_warning() { + echo -e "${YELLOW}⚠️ $1${NC}" +} + +print_info() { + echo -e "${BLUE}ℹ️ $1${NC}" +} + +check_root() { + if [ "$EUID" -ne 0 ]; then + print_error "Este script debe ejecutarse como root" + echo "Usa: sudo ./desplegar_agent.sh" + exit 1 + fi +} + +check_dependencies() { + print_info "Verificando dependencias..." + + local deps=("systemctl" "cargo" "rustc") + local missing=() + + for dep in "${deps[@]}"; do + if ! command -v $dep &> /dev/null; then + missing+=($dep) + fi + done + + if [ ${#missing[@]} -ne 0 ]; then + print_error "Faltan dependencias: ${missing[*]}" + echo "" + echo "Instalación de Rust:" + echo " curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh" + echo "" + echo "Instalación de systemd (debería estar instalado por defecto):" + echo " sudo apt-get install systemd # Debian/Ubuntu" + echo " sudo yum install systemd # RedHat/CentOS" + exit 1 + fi + + print_success "Todas las dependencias están instaladas" +} + +backup_existing() { + if [ -d "$INSTALL_DIR" ]; then + print_warning "Instalación existente detectada" + print_info "Creando backup en: $BACKUP_DIR" + mkdir -p "$BACKUP_DIR" + cp -r "$INSTALL_DIR" "$BACKUP_DIR/" + print_success "Backup creado" + fi +} + +compile_release() { + print_info "Compilando SIAX Agent en modo release..." + + if cargo build --release; then + print_success "Compilación exitosa" + else + print_error "Error en la compilación" + rollback + exit 1 + fi +} + +create_user() { + if id "$SERVICE_USER" &>/dev/null; then + print_info "Usuario $SERVICE_USER ya existe" + else + print_info "Creando usuario del sistema: $SERVICE_USER" + useradd --system --no-create-home --shell /bin/false "$SERVICE_USER" + print_success "Usuario creado" + fi +} + +install_binary() { + print_info "Instalando binario en $INSTALL_DIR..." + + mkdir -p "$INSTALL_DIR" + mkdir -p "$INSTALL_DIR/config" + mkdir -p "$INSTALL_DIR/logs" + + cp target/release/siax_monitor "$INSTALL_DIR/siax-agent" + chmod +x "$INSTALL_DIR/siax-agent" + + # Copiar archivos de configuración si existen + if [ -f "config/monitored_apps.json" ]; then + cp config/monitored_apps.json "$INSTALL_DIR/config/" + fi + + # Copiar archivos web + if [ -d "web" ]; then + cp -r web "$INSTALL_DIR/" + fi + + # Permisos + chown -R $SERVICE_USER:$SERVICE_USER "$INSTALL_DIR" + + print_success "Binario instalado" +} + +configure_sudoers() { + print_info "Configurando permisos sudo para systemctl..." + + local sudoers_file="/etc/sudoers.d/siax-agent" + + cat > "$sudoers_file" << EOF +# SIAX Agent - Permisos para gestionar servicios systemd +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl start * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl stop * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl restart * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl status * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl enable * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl disable * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl daemon-reload +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl is-active * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/systemctl list-unit-files * +$SERVICE_USER ALL=(ALL) NOPASSWD: /bin/journalctl * +EOF + + chmod 0440 "$sudoers_file" + + # Validar sintaxis + if visudo -c -f "$sudoers_file" &>/dev/null; then + print_success "Configuración de sudoers creada" + else + print_error "Error en configuración de sudoers" + rm -f "$sudoers_file" + exit 1 + fi +} + +create_systemd_service() { + print_info "Creando servicio systemd para SIAX Agent..." + + cat > /etc/systemd/system/siax-agent.service << EOF +[Unit] +Description=SIAX Agent - Process Monitor and Manager +After=network.target + +[Service] +Type=simple +User=$SERVICE_USER +WorkingDirectory=$INSTALL_DIR +ExecStart=$INSTALL_DIR/siax-agent +Restart=always +RestartSec=10 +StandardOutput=journal +StandardError=journal + +# Security hardening +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ReadWritePaths=$INSTALL_DIR/config $INSTALL_DIR/logs /etc/systemd/system +ProtectHome=true + +[Install] +WantedBy=multi-user.target +EOF + + systemctl daemon-reload + systemctl enable siax-agent.service + + print_success "Servicio systemd creado y habilitado" +} + +verify_installation() { + print_info "Verificando instalación..." + + local errors=0 + + # Verificar binario + if [ ! -f "$INSTALL_DIR/siax-agent" ]; then + print_error "Binario no encontrado" + ((errors++)) + fi + + # Verificar permisos + if [ ! -r "$INSTALL_DIR/siax-agent" ]; then + print_error "Permisos incorrectos en binario" + ((errors++)) + fi + + # Verificar servicio + if ! systemctl is-enabled siax-agent.service &>/dev/null; then + print_error "Servicio no habilitado" + ((errors++)) + fi + + # Verificar sudoers + if [ ! -f "/etc/sudoers.d/siax-agent" ]; then + print_warning "Configuración de sudoers no encontrada" + echo " El agente podría tener problemas para gestionar servicios" + fi + + if [ $errors -eq 0 ]; then + print_success "Verificación exitosa" + return 0 + else + print_error "Verificación falló con $errors errores" + return 1 + fi +} + +start_service() { + print_info "Iniciando SIAX Agent..." + + if systemctl start siax-agent.service; then + sleep 2 + if systemctl is-active siax-agent.service &>/dev/null; then + print_success "SIAX Agent iniciado correctamente" + return 0 + else + print_error "SIAX Agent no pudo iniciarse" + echo "" + echo "Ver logs con: journalctl -u siax-agent.service -n 50" + return 1 + fi + else + print_error "Error al iniciar el servicio" + return 1 + fi +} + +rollback() { + print_warning "Ejecutando rollback..." + + systemctl stop siax-agent.service 2>/dev/null || true + systemctl disable siax-agent.service 2>/dev/null || true + + if [ -d "$BACKUP_DIR" ]; then + rm -rf "$INSTALL_DIR" + cp -r "$BACKUP_DIR/siax-agent" "$INSTALL_DIR" + systemctl start siax-agent.service 2>/dev/null || true + print_success "Rollback completado" + else + print_warning "No hay backup disponible para rollback" + fi +} + +print_summary() { + echo "" + echo -e "${GREEN}============================================${NC}" + echo -e "${GREEN} ✅ SIAX Agent instalado exitosamente${NC}" + echo -e "${GREEN}============================================${NC}" + echo "" + echo "📊 Interface Web: http://localhost:8080" + echo "🔌 API REST: http://localhost:8081/api" + echo "📡 WebSocket: ws://localhost:8081/ws/logs/:app_name" + echo "" + echo "Comandos útiles:" + echo " Estado: sudo systemctl status siax-agent" + echo " Logs: sudo journalctl -u siax-agent -f" + echo " Reiniciar: sudo systemctl restart siax-agent" + echo " Detener: sudo systemctl stop siax-agent" + echo "" + echo "Directorio de instalación: $INSTALL_DIR" + echo "Configuración: $INSTALL_DIR/config/monitored_apps.json" + echo "" +} + +####################################### +# Main +####################################### + +main() { + print_header + + check_root + check_dependencies + backup_existing + compile_release + create_user + install_binary + configure_sudoers + create_systemd_service + + if verify_installation; then + if start_service; then + print_summary + exit 0 + else + print_error "El servicio no pudo iniciarse correctamente" + print_info "Revisa los logs: journalctl -u siax-agent -n 50" + echo "" + echo "¿Deseas hacer rollback? (y/n)" + read -r response + if [[ "$response" =~ ^[Yy]$ ]]; then + rollback + fi + exit 1 + fi + else + print_error "La verificación falló" + echo "" + echo "¿Deseas hacer rollback? (y/n)" + read -r response + if [[ "$response" =~ ^[Yy]$ ]]; then + rollback + fi + exit 1 + fi +} + +main diff --git a/install-remote.sh b/install-remote.sh new file mode 100644 index 0000000..d04f6b8 --- /dev/null +++ b/install-remote.sh @@ -0,0 +1,315 @@ +#!/bin/bash + +####################################### +# SIAX Agent - Script de Instalación Remota +# Descarga e instala SIAX Agent desde servidor central +####################################### + +set -e # Salir si hay errores + +# Variables (CONFIGURAR AQUÍ) +CENTRAL_SERVER="${SIAX_SERVER:-localhost:8080}" # Servidor central +INSTALL_DIR="/opt/siax-agent" +SERVICE_USER="siax-agent" +BACKUP_DIR="/tmp/siax-agent-backup-$(date +%s)" +DOWNLOAD_DIR="/tmp/siax-agent-download-$(date +%s)" + +# Colores para output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +####################################### +# Funciones +####################################### + +print_header() { + echo -e "${BLUE}" + echo "============================================" + echo " SIAX Agent - Remote Installation" + echo " Server: $CENTRAL_SERVER" + echo "============================================" + echo -e "${NC}" +} + +print_success() { + echo -e "${GREEN}✅ $1${NC}" +} + +print_error() { + echo -e "${RED}❌ $1${NC}" +} + +print_warning() { + echo -e "${YELLOW}⚠️ $1${NC}" +} + +print_info() { + echo -e "${BLUE}ℹ️ $1${NC}" +} + +check_root() { + if [ "$EUID" -ne 0 ]; then + print_error "Este script debe ejecutarse como root" + echo "Usa: curl -sSL http://$CENTRAL_SERVER/install.sh | sudo bash" + echo "O con variable: curl -sSL http://$CENTRAL_SERVER/install.sh | sudo SIAX_SERVER=tu-servidor:8080 bash" + exit 1 + fi +} + +check_dependencies() { + print_info "Verificando dependencias..." + + local deps=("systemctl" "curl") + local missing=() + + for dep in "${deps[@]}"; do + if ! command -v $dep &> /dev/null; then + missing+=($dep) + fi + done + + if [ ${#missing[@]} -ne 0 ]; then + print_error "Faltan dependencias: ${missing[*]}" + echo "" + echo "Instalación en Debian/Ubuntu:" + echo " sudo apt-get update && sudo apt-get install -y curl systemd" + echo "" + echo "Instalación en RedHat/CentOS:" + echo " sudo yum install -y curl systemd" + exit 1 + fi + + print_success "Todas las dependencias están instaladas" +} + +download_binary() { + print_info "Descargando binario desde $CENTRAL_SERVER..." + + mkdir -p "$DOWNLOAD_DIR" + + # Intentar descargar el binario pre-compilado + if curl -f -L -o "$DOWNLOAD_DIR/siax-agent" "http://$CENTRAL_SERVER/static/binary/siax-agent"; then + chmod +x "$DOWNLOAD_DIR/siax-agent" + print_success "Binario descargado" + else + print_error "No se pudo descargar el binario desde http://$CENTRAL_SERVER/static/binary/siax-agent" + echo "" + echo "Asegúrate de que:" + echo " 1. El servidor $CENTRAL_SERVER está accesible" + echo " 2. El binario está en web/static/binary/siax-agent" + echo " 3. Compilaste con: cargo build --release && cp target/release/siax_monitor web/static/binary/siax-agent" + rm -rf "$DOWNLOAD_DIR" + exit 1 + fi +} + +download_web_files() { + print_info "Descargando archivos web..." + + mkdir -p "$DOWNLOAD_DIR/web" + + # Descargar archivos HTML principales (opcional, solo si quieres que cada agente tenga su propia interfaz) + # Para agentes worker, probablemente no necesites esto + print_info "Archivos web no necesarios para worker nodes (omitiendo)" +} + +backup_existing() { + if [ -d "$INSTALL_DIR" ]; then + print_warning "Instalación existente detectada" + print_info "Creando backup en: $BACKUP_DIR" + mkdir -p "$BACKUP_DIR" + cp -r "$INSTALL_DIR" "$BACKUP_DIR/" + print_success "Backup creado" + fi +} + +create_user() { + if id "$SERVICE_USER" &>/dev/null; then + print_info "Usuario $SERVICE_USER ya existe" + else + print_info "Creando usuario del sistema: $SERVICE_USER" + useradd --system --no-create-home --shell /bin/false "$SERVICE_USER" + print_success "Usuario creado" + fi +} + +install_binary() { + print_info "Instalando binario en $INSTALL_DIR..." + + mkdir -p "$INSTALL_DIR" + mkdir -p "$INSTALL_DIR/config" + mkdir -p "$INSTALL_DIR/logs" + mkdir -p "$INSTALL_DIR/web/static" + + # Copiar binario + cp "$DOWNLOAD_DIR/siax-agent" "$INSTALL_DIR/siax-agent" + chmod +x "$INSTALL_DIR/siax-agent" + + # Crear configuración inicial vacía si no existe + if [ ! -f "$INSTALL_DIR/config/monitored_apps.json" ]; then + echo '{"apps":[]}' > "$INSTALL_DIR/config/monitored_apps.json" + fi + + # Permisos + chown -R $SERVICE_USER:$SERVICE_USER "$INSTALL_DIR" + + print_success "Binario instalado" +} + +configure_sudoers() { + print_info "Configurando permisos sudo para systemctl..." + + local sudoers_file="/etc/sudoers.d/siax-agent" + + cat > "$sudoers_file" << 'EOF' +# SIAX Agent - Permisos para gestionar servicios systemd +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl start * +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl stop * +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl restart * +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl status * +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl enable * +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl disable * +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl daemon-reload +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl is-active * +siax-agent ALL=(ALL) NOPASSWD: /bin/systemctl list-unit-files * +siax-agent ALL=(ALL) NOPASSWD: /bin/journalctl * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl start * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl stop * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl status * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl enable * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl disable * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl daemon-reload +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl is-active * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/systemctl list-unit-files * +siax-agent ALL=(ALL) NOPASSWD: /usr/bin/journalctl * +EOF + + chmod 0440 "$sudoers_file" + + # Validar sintaxis + if visudo -c -f "$sudoers_file" &>/dev/null; then + print_success "Configuración de sudoers creada" + else + print_error "Error en configuración de sudoers" + rm -f "$sudoers_file" + exit 1 + fi +} + +create_systemd_service() { + print_info "Creando servicio systemd para SIAX Agent..." + + cat > /etc/systemd/system/siax-agent.service << EOF +[Unit] +Description=SIAX Agent - Process Monitor and Manager +After=network.target + +[Service] +Type=simple +User=$SERVICE_USER +WorkingDirectory=$INSTALL_DIR +ExecStart=$INSTALL_DIR/siax-agent +Restart=always +RestartSec=10 +StandardOutput=journal +StandardError=journal + +# Security hardening +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ReadWritePaths=$INSTALL_DIR/config $INSTALL_DIR/logs /etc/systemd/system +ProtectHome=true + +[Install] +WantedBy=multi-user.target +EOF + + systemctl daemon-reload + systemctl enable siax-agent.service + + print_success "Servicio systemd creado y habilitado" +} + +start_service() { + print_info "Iniciando SIAX Agent..." + + if systemctl start siax-agent.service; then + sleep 2 + if systemctl is-active siax-agent.service &>/dev/null; then + print_success "SIAX Agent iniciado correctamente" + return 0 + else + print_error "SIAX Agent no pudo iniciarse" + echo "" + echo "Ver logs con: journalctl -u siax-agent.service -n 50" + return 1 + fi + else + print_error "Error al iniciar el servicio" + return 1 + fi +} + +cleanup() { + print_info "Limpiando archivos temporales..." + rm -rf "$DOWNLOAD_DIR" + print_success "Limpieza completada" +} + +print_summary() { + echo "" + echo -e "${GREEN}============================================${NC}" + echo -e "${GREEN} ✅ SIAX Agent instalado exitosamente${NC}" + echo -e "${GREEN}============================================${NC}" + echo "" + echo "📊 Interface Web: http://localhost:8080" + echo "🔌 API REST: http://localhost:8080/api" + echo "📡 WebSocket: ws://localhost:8080/api/apps/:name/logs" + echo "" + echo "Comandos útiles:" + echo " Estado: sudo systemctl status siax-agent" + echo " Logs: sudo journalctl -u siax-agent -f" + echo " Reiniciar: sudo systemctl restart siax-agent" + echo " Detener: sudo systemctl stop siax-agent" + echo "" + echo "Directorio de instalación: $INSTALL_DIR" + echo "Configuración: $INSTALL_DIR/config/monitored_apps.json" + echo "" + echo "🌐 Servidor Central: $CENTRAL_SERVER" + echo "" +} + +####################################### +# Main +####################################### + +main() { + print_header + + check_root + check_dependencies + backup_existing + download_binary + create_user + install_binary + configure_sudoers + create_systemd_service + + if start_service; then + cleanup + print_summary + exit 0 + else + print_error "El servicio no pudo iniciarse correctamente" + print_info "Revisa los logs: journalctl -u siax-agent -n 50" + cleanup + exit 1 + fi +} + +main diff --git a/logs/errors.log b/logs/errors.log index c1a5624..d42516f 100644 --- a/logs/errors.log +++ b/logs/errors.log @@ -117,3 +117,243 @@ [2026-01-13 08:16:16] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 [2026-01-13 08:16:16] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 [2026-01-13 08:16:16] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 11:34:33] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 11:34:33] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 11:34:33] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 11:34:33] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 11:37:28] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 11:37:28] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 11:37:28] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 11:37:28] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 11:43:43] [ERROR] [Monitor] Error enviando app_tareas | error sending request for url (https://api.siax-system.net/api/apps_servcs/apps): operation timed out +[2026-01-13 11:43:54] [ERROR] [Monitor] Error enviando fidelizacion | error sending request for url (https://api.siax-system.net/api/apps_servcs/apps): operation timed out +[2026-01-13 11:48:54] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 11:48:54] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 11:48:54] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 11:48:54] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 11:54:16] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 11:54:16] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 11:54:16] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 11:54:16] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 11:57:20] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 11:57:20] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 11:57:20] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 11:57:20] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 11:58:31] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 11:58:31] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 11:58:31] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 11:58:31] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:01:28] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:01:28] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:01:28] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:01:28] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:02:46] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:02:46] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:02:46] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:02:46] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:03:45] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:03:45] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:03:45] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:03:46] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:06:23] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:06:23] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:06:23] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:06:23] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:07:35] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:07:35] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:07:35] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:07:35] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:09:36] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:09:36] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:09:36] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:09:36] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:12:40] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:12:40] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:12:40] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:12:41] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:14:45] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:14:45] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:14:45] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:14:45] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:16:41] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:16:41] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:16:41] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:16:41] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:16:58] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:16:58] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:16:58] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:16:58] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:18:26] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:18:26] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:18:26] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:18:26] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:21:10] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:21:10] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:21:10] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:21:10] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:24:50] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:24:50] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:24:50] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:24:50] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:30:18] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:30:18] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:30:18] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:30:18] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:32:13] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:32:13] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:32:13] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:32:13] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 12:36:39] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 12:36:39] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 12:36:39] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 12:36:39] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 20:54:14] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 20:54:14] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 20:54:14] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 20:54:14] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 21:24:19] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 21:24:19] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 21:24:19] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 21:24:19] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 21:26:58] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 21:26:58] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 21:26:58] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 21:26:59] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 21:44:25] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 21:44:25] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 21:44:25] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 21:44:25] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 22:15:29] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 22:15:29] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 22:15:29] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 22:15:29] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-13 23:10:54] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-13 23:10:54] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-13 23:10:54] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-13 23:10:54] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:04:25] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:04:25] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:04:25] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:04:25] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:04:25] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:13:17] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:13:17] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:13:17] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:13:17] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:13:17] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:20:19] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:20:19] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:20:19] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:20:19] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:20:19] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:26:24] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:26:24] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:26:24] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:26:24] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:26:24] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:26:31] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:26:31] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:26:31] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:26:31] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:26:31] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:27:52] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:27:52] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:27:52] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:27:52] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:27:52] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:29:23] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:29:23] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:29:23] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:29:23] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:29:23] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:32:59] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:32:59] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:32:59] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:32:59] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:32:59] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:34:44] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:34:44] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:34:44] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:34:44] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:34:44] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:35:49] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:35:49] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:35:49] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:35:49] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:35:49] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:39:01] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:39:01] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:39:01] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:39:01] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:39:01] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:42:49] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:42:49] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:42:49] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:42:49] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:42:49] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:43:09] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:43:09] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:43:09] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:43:09] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:43:09] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:50:38] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:50:38] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:50:38] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:50:38] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:50:38] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 00:51:57] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 00:51:57] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 00:51:57] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 00:51:57] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 00:51:57] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 01:13:51] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 01:13:51] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 01:13:51] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 01:13:51] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 01:13:51] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 01:14:41] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 01:14:41] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 01:14:41] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 01:14:41] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 01:14:41] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 01:16:36] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 01:16:36] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 01:16:36] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 01:16:36] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 01:16:36] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 01:19:24] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 01:19:24] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 01:19:24] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 01:19:24] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 01:19:24] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 01:19:52] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 01:19:52] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 01:19:52] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 01:19:52] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 01:19:52] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-14 01:20:03] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-14 01:20:03] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-14 01:20:03] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-14 01:20:03] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-14 01:20:03] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-15 02:36:15] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-15 02:36:15] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-15 02:36:15] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-15 02:36:15] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-15 02:36:15] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-18 03:26:07] [INFO] [Sistema] Iniciando SIAX Agent +[2026-01-18 03:26:07] [INFO] [Sistema] Escaneando servicios systemd existentes... +[2026-01-18 03:26:07] [INFO] [Discovery] Escaneando servicios systemd existentes... +[2026-01-18 03:26:07] [INFO] [Discovery] ✅ Descubiertos 0 servicios +[2026-01-18 03:26:07] [INFO] [Config] Usando archivo de configuración: config/monitored_apps.json +[2026-01-18 03:26:07] [INFO] [Config] ✅ Configuración cargada: 2 apps desde config/monitored_apps.json +[2026-01-18 03:26:07] [INFO] [Sistema] Servidor detectado: siax-intel +[2026-01-18 03:26:07] [INFO] [Sistema] Iniciando servidor unificado en puerto 8080 +[2026-01-18 03:26:07] [INFO] [Sistema] Sistema SIAX completamente operativo en puerto 8080 +[2026-01-18 03:26:07] [INFO] [Monitor] Vigilando procesos para siax-intel [SIAX-Agent/0.1.0 (linux/x86_64; Rust-Monitor)] +[2026-01-18 03:26:07] [INFO] [Monitor] Buscando app app_tareas en API central... +[2026-01-18 03:26:07] [INFO] [Monitor] App app_tareas encontrada en cloud (ID: 3) +[2026-01-18 03:26:07] [ERROR] [Monitor] Error sincronizando app_tareas | HTTP 500 Internal Server Error: {"success":false,"message":"Error al actualizar el estado","error":"Table 'webControl.app_service_history' doesn't exist"} +[2026-01-18 03:26:07] [INFO] [Monitor] Buscando app fidelizacion en API central... +[2026-01-18 03:26:07] [INFO] [Monitor] App fidelizacion encontrada en cloud (ID: 4) +[2026-01-18 03:26:07] [ERROR] [Monitor] Error sincronizando fidelizacion | HTTP 500 Internal Server Error: {"success":false,"message":"Error al actualizar el estado","error":"Table 'webControl.app_service_history' doesn't exist"} diff --git a/preparar_binario.sh b/preparar_binario.sh new file mode 100755 index 0000000..6abea48 --- /dev/null +++ b/preparar_binario.sh @@ -0,0 +1,66 @@ +#!/bin/bash + +####################################### +# SIAX Agent - Preparar Binario para Distribución +# Compila y copia el binario a web/static/binary/ +####################################### + +set -e + +GREEN='\033[0;32m' +BLUE='\033[0;34m' +RED='\033[0;31m' +NC='\033[0m' + +echo -e "${BLUE}============================================${NC}" +echo -e "${BLUE} Preparando SIAX Agent para Distribución${NC}" +echo -e "${BLUE}============================================${NC}" +echo "" + +# Compilar en release +echo -e "${BLUE}📦 Compilando en modo release...${NC}" +cargo build --release + +if [ ! -f "target/release/siax_monitor" ]; then + echo -e "${RED}❌ Error: No se pudo compilar el binario${NC}" + exit 1 +fi + +echo -e "${GREEN}✅ Compilación exitosa${NC}" +echo "" + +# Crear directorio para binarios +echo -e "${BLUE}📁 Creando directorio web/static/binary/${NC}" +mkdir -p web/static/binary + +# Copiar binario +echo -e "${BLUE}📋 Copiando binario...${NC}" +cp target/release/siax_monitor web/static/binary/siax-agent +chmod +x web/static/binary/siax-agent + +echo -e "${GREEN}✅ Binario copiado a web/static/binary/siax-agent${NC}" +echo "" + +# Mostrar información +BINARY_SIZE=$(du -h web/static/binary/siax-agent | cut -f1) +echo -e "${GREEN}============================================${NC}" +echo -e "${GREEN} ✅ Preparación completada${NC}" +echo -e "${GREEN}============================================${NC}" +echo "" +echo "📊 Tamaño del binario: $BINARY_SIZE" +echo "📂 Ubicación: web/static/binary/siax-agent" +echo "" +echo "🚀 Ahora puedes:" +echo "" +echo " 1. Iniciar el servidor:" +echo " cargo run --release" +echo "" +echo " 2. Desde otro servidor, instalar con:" +echo " curl -sSL http://TU-SERVIDOR:8080/install.sh | sudo bash" +echo "" +echo " O especificar el servidor:" +echo " curl -sSL http://TU-SERVIDOR:8080/install.sh | sudo SIAX_SERVER=TU-SERVIDOR:8080 bash" +echo "" +echo "Ejemplo VPN:" +echo " curl -sSL http://10.8.0.1:8080/install.sh | sudo SIAX_SERVER=10.8.0.1:8080 bash" +echo "" diff --git a/src/config.rs b/src/config.rs index d5c39a4..eac9f04 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,14 +6,51 @@ use crate::logger::get_logger; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MonitoredApp { + /// Nombre de la aplicación pub name: String, + + /// Nombre del servicio systemd (ej: siax-app-TAREAS.service) + #[serde(default)] + pub service_name: String, + + /// Ruta completa al directorio de la aplicación (WorkingDirectory) + #[serde(default)] + pub path: String, + + /// Puerto donde escucha la aplicación pub port: i32, + + /// Archivo de entrada (ej: server.js, app.js) + #[serde(default)] + pub entry_point: String, + + /// Ruta completa al binario de node/python + #[serde(default)] + pub node_bin: String, + + /// Modo de ejecución (production, development, test) + #[serde(default = "default_mode")] + pub mode: String, + + /// Ruta completa al archivo .service de systemd + #[serde(default)] + pub service_file_path: String, + + /// Fecha de registro (ISO 8601) + #[serde(default, skip_serializing_if = "String::is_empty", rename = "reg")] + pub registered_at: String, + + // DEPRECATED: Mantener por compatibilidad con versiones antiguas #[serde(skip_serializing_if = "Option::is_none")] pub systemd_service: Option, #[serde(skip_serializing_if = "Option::is_none")] pub created_at: Option, } +fn default_mode() -> String { + "production".to_string() +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppConfig { pub apps: Vec, @@ -99,23 +136,16 @@ impl ConfigManager { config.apps.clone() } - pub fn add_app(&self, name: String, port: i32) -> Result<(), String> { + /// Agrega una app con información completa + pub fn add_app_full(&self, app: MonitoredApp) -> Result<(), String> { let mut config = self.config.write().unwrap(); // Verificar si ya existe - if config.apps.iter().any(|app| app.name == name) { - return Err(format!("La app '{}' ya está siendo monitoreada", name)); + if config.apps.iter().any(|a| a.name == app.name) { + return Err(format!("La app '{}' ya está siendo monitoreada", app.name)); } - let systemd_service = format!("siax-app-{}.service", name); - let created_at = chrono::Local::now().to_rfc3339(); - - config.apps.push(MonitoredApp { - name, - port, - systemd_service: Some(systemd_service), - created_at: Some(created_at), - }); + config.apps.push(app); // Guardar en disco match Self::save_config_to_file(&self.config_path, &config) { @@ -124,6 +154,29 @@ impl ConfigManager { } } + /// Método simplificado para compatibilidad (DEPRECATED) + #[deprecated(note = "Usar add_app_full() con MonitoredApp completo")] + pub fn add_app(&self, name: String, port: i32) -> Result<(), String> { + let service_name = format!("siax-app-{}.service", name); + let registered_at = chrono::Local::now().to_rfc3339(); + + let app = MonitoredApp { + name, + service_name, + path: String::new(), + port, + entry_point: String::new(), + node_bin: String::new(), + mode: "production".to_string(), + service_file_path: String::new(), + registered_at, + systemd_service: None, + created_at: None, + }; + + self.add_app_full(app) + } + pub fn remove_app(&self, name: &str) -> Result<(), String> { let mut config = self.config.write().unwrap(); diff --git a/src/discovery.rs b/src/discovery.rs index 691e0ff..7024b40 100644 --- a/src/discovery.rs +++ b/src/discovery.rs @@ -67,9 +67,12 @@ pub struct DiscoveredService { pub user: Option, pub exec_start: Option, pub port: Option, + pub node_env: String, + pub entry_point: Option, + pub node_bin: Option, } -/// Parsea un archivo .service para extraer configuración básica +/// Parsea un archivo .service para extraer configuración completa fn parse_service_file(path: &Path, app_name: &str) -> Option { let logger = get_logger(); @@ -88,6 +91,9 @@ fn parse_service_file(path: &Path, app_name: &str) -> Option user: None, exec_start: None, port: None, + node_env: String::from("production"), + entry_point: None, + node_bin: None, }; // Parsear líneas del archivo @@ -106,7 +112,24 @@ fn parse_service_file(path: &Path, app_name: &str) -> Option // ExecStart if line.starts_with("ExecStart=") { - service.exec_start = Some(line.trim_start_matches("ExecStart=").to_string()); + let exec_start = line.trim_start_matches("ExecStart=").to_string(); + + // Extraer node_bin y entry_point del ExecStart + // Ejemplo: /home/user/.nvm/versions/node/v24.12.0/bin/node server.js + let parts: Vec<&str> = exec_start.split_whitespace().collect(); + if !parts.is_empty() { + service.node_bin = Some(parts[0].to_string()); + + // Buscar el archivo .js como entry_point + for part in &parts[1..] { + if part.ends_with(".js") { + service.entry_point = Some(part.to_string()); + break; + } + } + } + + service.exec_start = Some(exec_start); } // Environment con PORT @@ -115,12 +138,21 @@ fn parse_service_file(path: &Path, app_name: &str) -> Option service.port = Some(port); } } + + // Environment con NODE_ENV + if line.starts_with("Environment=") && line.contains("NODE_ENV") { + if let Some(env) = extract_env_value(line, "NODE_ENV") { + service.node_env = env; + } + } } - logger.info("Discovery", &format!(" App: {}, User: {:?}, WorkDir: {:?}", + logger.info("Discovery", &format!(" App: {}, User: {:?}, WorkDir: {:?}, Env: {}, EntryPoint: {:?}", service.app_name, service.user, - service.working_directory + service.working_directory, + service.node_env, + service.entry_point )); Some(service) @@ -143,6 +175,27 @@ fn extract_port_from_env(line: &str) -> Option { } } +/// Extrae un valor de variable de entorno de una línea Environment +/// Ejemplo: Environment="NODE_ENV=production" -> Some("production") +fn extract_env_value(line: &str, var_name: &str) -> Option { + let pattern = format!("{}=", var_name); + if let Some(start) = line.find(&pattern) { + let after_var = &line[start + pattern.len()..]; + // Extraer hasta espacios, comillas o fin de línea + let value: String = after_var.chars() + .take_while(|c| !c.is_whitespace() && *c != '"') + .collect(); + + if !value.is_empty() { + Some(value) + } else { + None + } + } else { + None + } +} + /// Sincroniza los servicios descubiertos con monitored_apps.json pub fn sync_discovered_services(services: Vec) { let logger = get_logger(); @@ -156,7 +209,6 @@ pub fn sync_discovered_services(services: Vec) { for service in services { // Intentar detectar el puerto si no se encontró en Environment let port = service.port.unwrap_or_else(|| { - // Intentar extraer del nombre o usar puerto por defecto detect_port_from_name(&service.app_name) }); @@ -170,10 +222,29 @@ pub fn sync_discovered_services(services: Vec) { continue; } - // Agregar a monitored_apps.json - logger.info("Discovery", &format!("➕ Agregando {} (puerto: {})", service.app_name, port)); + // Crear MonitoredApp con información completa + let service_name = format!("siax-app-{}.service", service.app_name); + let registered_at = chrono::Local::now().to_rfc3339(); - match config_manager.add_app(service.app_name.clone(), port) { + let app = MonitoredApp { + name: service.app_name.clone(), + service_name, + path: service.working_directory.unwrap_or_default(), + port, + entry_point: service.entry_point.unwrap_or_default(), + node_bin: service.node_bin.unwrap_or_default(), + mode: service.node_env, + service_file_path: service.service_file.clone(), + registered_at, + systemd_service: None, + created_at: None, + }; + + // Agregar a monitored_apps.json + logger.info("Discovery", &format!("➕ Agregando {} (puerto: {}, entry: {})", + app.name, app.port, app.entry_point)); + + match config_manager.add_app_full(app) { Ok(_) => { logger.info("Discovery", &format!("✅ {} agregado exitosamente", service.app_name)); added_count += 1; diff --git a/src/orchestrator/app_manager.rs b/src/orchestrator/app_manager.rs index 237e079..e235e56 100644 --- a/src/orchestrator/app_manager.rs +++ b/src/orchestrator/app_manager.rs @@ -2,6 +2,7 @@ use super::{Result, OrchestratorError}; use crate::models::{ServiceConfig, ManagedApp, AppStatus}; use crate::systemd::{ServiceGenerator, SystemCtl}; use crate::logger::get_logger; +use crate::config::{get_config_manager, MonitoredApp}; use dashmap::DashMap; use std::sync::Arc; @@ -52,6 +53,49 @@ impl AppManager { // Guardar en memoria self.apps.insert(config.app_name.clone(), config.clone()); + // Guardar en monitored_apps.json con información completa + let config_manager = get_config_manager(); + let service_file_path = format!("/etc/systemd/system/{}", config.service_name()); + let registered_at = chrono::Local::now().to_rfc3339(); + + // Extraer el puerto del environment si existe + let port = config.environment.get("PORT") + .and_then(|p| p.parse::().ok()) + .unwrap_or(8080); + + // Determinar el entry_point desde script_path + let entry_point = std::path::Path::new(&config.script_path) + .file_name() + .and_then(|f| f.to_str()) + .unwrap_or("server.js") + .to_string(); + + // Determinar node_bin (será resuelto por el ServiceGenerator) + let node_bin = config.custom_executable.clone().unwrap_or_default(); + + // Determinar mode desde NODE_ENV + let mode = config.environment.get("NODE_ENV") + .cloned() + .unwrap_or_else(|| "production".to_string()); + + let monitored_app = MonitoredApp { + name: config.app_name.clone(), + service_name: config.service_name(), + path: config.working_directory.clone(), + port, + entry_point, + node_bin, + mode, + service_file_path, + registered_at, + systemd_service: None, + created_at: None, + }; + + if let Err(e) = config_manager.add_app_full(monitored_app) { + logger.warning("AppManager", "No se pudo guardar en monitored_apps.json", Some(&e)); + } + logger.info("AppManager", &format!("Aplicación {} registrada exitosamente", config.app_name)); Ok(()) @@ -84,6 +128,12 @@ impl AppManager { // Eliminar de memoria self.apps.remove(app_name); + // Eliminar de monitored_apps.json + let config_manager = get_config_manager(); + if let Err(e) = config_manager.remove_app(app_name) { + logger.warning("AppManager", "No se pudo eliminar de monitored_apps.json", Some(&e)); + } + logger.info("AppManager", &format!("Aplicación {} desregistrada exitosamente", app_name)); Ok(()) diff --git a/web/api-docs.html b/web/api-docs.html index 8be6ac8..e5e1a08 100644 --- a/web/api-docs.html +++ b/web/api-docs.html @@ -4,6 +4,7 @@ Documentación API - SIAX Monitor + -