- 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
316 lines
9.0 KiB
Bash
316 lines
9.0 KiB
Bash
#!/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
|