Volver a la wiki

Agente · dev-terminal

Agente · dev-terminal

Propósito

Desarrollo y mantenimiento del Terminal Hub, el Local Agent y el sistema Multi-Pane de CreaRack-Pro. Cubre la app terminal/, los 10 módulos JS del terminal y el ejecutable Windows CreaRackAgent.exe.


Módulos JS (terminal/)

static/js/terminal/
├── TabManager.js           # Gestión de pestañas SSH
├── MultiPaneManager.js     # Layouts CSS Grid (1x1, 2x1, 1x2, 2x2, 3x1)
├── TerminalToolbar.js      # Toolbar SSH (tema, tamaño, color, clipboard)
├── TerminalSettings.js     # Preferencias de usuario
├── ClusterMode.js          # Broadcast multi-sesión simultánea
├── AgentLifecycle.js       # Activación y estado del Local Agent
├── ManualConnection.js     # Conexiones manuales sin device
├── DeviceManager.js        # Filtros y grupos (patrón HTMX)
└── index.js                # Re-exports

App Django: terminal/

terminal/
├── api.py                  # Endpoints Django Ninja
├── views.py                # Vista terminal_view
├── consumers.py            # WebSocket consumers (SSH bridge)
├── routing.py              # WebSocket routing
└── agent/                  # Local Agent (Windows exe)
    ├── local_agent.py      # FastAPI app principal
    ├── models.py           # Pydantic request/response models
    ├── ssh_bridge.py       # SSHBridge: conexiones SSH persistentes
    ├── scrapli_manager.py  # LocalScrapliManager: multi-vendor
    ├── cluster_engine.py   # ClusterEngine: ejecución paralela
    ├── network_utils.py    # Ping, scan, discovery, ARP
    ├── auth_manager.py     # DPAPI + JWT authentication
    ├── offline_cache.py    # SQLite cache offline
    ├── sentinel_scheduler.py # Loops async ping/SNMP/HTTP
    ├── sync_manager.py     # REST push métricas a SaaS
    ├── saas_connector.py   # WebSocket persistente al SaaS
    ├── timeseries_store.py # SQLite WAL store métricas Sentinel
    ├── monitoring_service.py # Workers de monitoreo
    ├── installer.py        # Always-reinstall strategy
    ├── windows_integration.py # Registro Windows, auto-start
    ├── logging_handler.py  # MemoryLogHandler + WS broadcast
    ├── version.py          # AGENT_VERSION — fuente de verdad
    └── assets/
        ├── terminal.html   # UI xterm.js + Asteroids
        ├── debug.html      # Tools Hub (3 tabs, 7 herramientas)
        └── oui_vendors.json # MAC vendors DB (~230 entries)

Local Agent — arquitectura general

El agente es un ejecutable Windows standalone (~25MB) que actúa como puente entre el navegador y los dispositivos de red con IPs privadas.

[Navegador/SaaS] ←──WebSocket──► [CreaRackAgent.exe :5050] ←──SSH──► [Dispositivos 192.168.x.x]

Instalación: %APPDATA%\CreaRackAgent\ Puerto: 5050 (solo localhost — no accesible desde la red) Auto-start: Scheduled task de Windows Distribución: GitHub Releases (NO en el repo git)

https://github.com/CreaRackSL/CreaRack-Pro/releases/latest/download/CreaRackAgent.exe

Multi-Agent Fleet (Primary/Secondary)

RolFunción
PrimaryEjecuta Sentinel (SNMP, ping, HTTP monitoring 24/7) · Solo uno por tenant
SecondarySolo SSH/herramientas · No ejecuta Sentinel

Fleet API endpoints (SaaS):

GET  /api/agent/fleet                      # Lista agentes del tenant
POST /api/agent/fleet/{id}/promote         # Promover a Primary
POST /api/agent/fleet/{id}/demote          # Degradar a Secondary
GET  /api/agent/fleet/config               # Role Assignment Mode (auto/manual)
POST /api/agent/fleet/config               # Cambiar modo
POST /api/agent/fleet/{id}/reauth          # Regenerar JWT frescos

Agent endpoints (localhost:5050):

GET  /agent/role                           # Rol actual y estado Sentinel
GET  /info                                 # Versión, uptime, sessions, role
GET  /health                               # {"status": "healthy"}

Terminal SSH

WebSocket protocol

// Conectar
ws.send(JSON.stringify({
    action: "connect",
    host: "192.168.1.1", port: 22,
    username: "admin", password: "secret"
}));

// Enviar datos
ws.send(JSON.stringify({ action: "data", data: "show version\r\n" }));

// Respuestas del servidor
// { type: "output", data: "..." }
// { type: "status", message: "..." }
// { type: "error", message: "..." }

Persistencia de sesiones SSH

Las sesiones SSH sobreviven a la navegación entre páginas:

EscenarioComportamiento
Navegar fuera y volverReattach automático — replay output_buffer (2000 chunks) + “SESSION RESTORED”
SSH expirado (timeout remoto)Detecta ssh_conn=None, limpia bridge stale, crea sesión nueva
Cerrar pestañaSesión SSH sigue viva en Agent hasta que el servidor la cierre

Flujo de reattach:

  1. iframe carga terminal.html y abre WS /ws/terminal/{sid}
  2. Agent detecta sid en ACTIVE_BRIDGES, verifica ssh_conn + ssh_process
  3. SSH vivo → envía output_buffer → “Tunnel Established!”
  4. SSH muerto → limpia bridge stale → nueva sesión
  5. Frontend consulta GET /terminal/sessions antes de enviar CONNECT_SSH

Temas disponibles

TemaFondoDescripción
Campbell#0C0C0CDefault Windows Terminal
Gruvbox Dark#282828Retro cálido
Green Screen#001100Terminal verde fosforescente
Tango Dark#000000Paleta GNOME clásica

Atajos de teclado

AtajoAcción
Ctrl+CCopiar selección (si hay) o enviar SIGINT
Ctrl+VPegar desde clipboard
Ctrl+Shift+C/VCopiar/pegar siempre

El iframe requiere allow="clipboard-read; clipboard-write" para Clipboard API en Chrome 2024+.

Syntax highlighting (colores ANSI)

Toggle “Color” en toolbar. Dos capas:

Keywords:

ColorPalabras
Rojoerror, fail, failed, critical, down, refused
Verdeup, ok, success, connected, online, active
Amarillowarning, alert, timeout, deprecated
CianIPs IPv4
DoradoMACs (AA:BB:CC:DD:EE:FF)

Banner (malva/magenta): versiones, copyright, URLs, fabricantes (Cisco, Juniper, Arista, Xirrus, Cambium…), avisos NOTICE/IMPORTANT.

Keywords usan \b (word boundaries) — “support” no colorea “up” accidentalmente.

Superpersistencia de ajustes

localStorage key crearack_terminal_settings:


Multi-Pane Layouts

5 layouts CSS Grid gestionados por MultiPaneManager.js:

LayoutDescripción
1x1Una sola terminal
2x1Dos terminales en fila
1x2Dos terminales en columna
2x2Cuatro terminales
3x1Tres terminales en fila

Cluster Mode

Ejecución de comandos/scripts en múltiples dispositivos simultáneamente.

Vendors soportados (Scrapli):

VendorPlatform ID
Cisco IOS/IOS-XEcisco_ios, cisco_iosxe
Cisco NX-OScisco_nxos
Arista EOSarista_eos
Juniper JunOSjuniper_junos
Genérico SSHgeneric

Cluster endpoints (Agent :5050):

POST /cluster/execute    # Comando en múltiples dispositivos
POST /cluster/script     # Script en múltiples dispositivos
POST /cluster/health     # Verificar conectividad múltiple
POST /cluster/backup     # Backup de múltiples dispositivos
POST /execute/single     # Comando en un solo dispositivo

Sentinel Mode (monitoreo 24/7)

Solo el Primary ejecuta Sentinel. Loops async independientes:

LoopArchivoIntervaloMétricas
Pingsentinel/ping.pyConfigurablelatencia, packet loss
SNMP Bandwidthsentinel/snmp_bandwidth.py60sIn/Out Mbps, errors, discards
SNMP Extrassentinel/snmp_extras.pyConfigurablemétricas adicionales
HTTP Checksentinel/http_check.pyConfigurablestatus code, response time

SNMP Bandwidth — 8 OIDs por target:

HC→Legacy fallback: si ifHCInOctets delta = 0 pero ifInOctets delta > 0, usa legacy (necesario para Xirrus APs). Spike protection: rates >10 Gbps descartados y baseline reseteado.

SQLite buffering (metrics.db):


Protocolo WebSocket SaaS ↔ Agent

SaaS → Agent:

TipoPayload
START_MONITORING{targets: [...]}
STOP_MONITORING—
UPDATE_TARGETS{targets: [...]}
PING_NOW{target_id: X}
GET_STATUS—

Agent → SaaS:

TipoPayload
AGENT_HELLO{agent_id, version, capabilities}
METRICS{batch: [{target_id, metric_type, value, timestamp}]}
HEARTBEAT{timestamp, sentinel_active} — cada 30s
ALERT{target_id, alert_type, message}
STATUS{state, targets_count, uptime}

Autenticación JWT (Zero-Intervention)

Tres capas de protección para tokens:

CapaMecanismoCuándo actúa
Layer 1Proactive refresh (75% lifetime)Token al 75% de vida (~54h)
Layer 2SaaS WS push (<2h remaining)Token <2h restantes
Layer 3Auto-reauth via DPAPI credentialsAmbos tokens expirados

Tools Hub (localhost:5050)

3 tabs: Status | Tools | Debug

7 herramientas de red (Tools tab):

#HerramientaEndpoint
1Port CheckGET /check?host=X&port=Y
2ICMP PingGET /network/ping-icmp?host=X
3DNS LookupGET /network/hostname?ip=X
4SSH BannerGET /network/banner?host=X&port=Y
5ARP TableGET /network/arp-table
6Network DiscoveryPOST /network/discover
7Port ScanPOST /network/scan

Debug Console:


Sleep/Wake Recovery (Windows)

Tras suspender/hibernar Windows, el Agent se recupera en <15 segundos:


Compilación

cd C:\dev\CreaRack-Pro
build_agent.bat
# Resultado: static/downloads/CreaRackAgent.exe (~25MB)

Imports condicionales (frozen vs dev):

if getattr(sys, "frozen", False):
    from models import DeviceTarget        # frozen (.exe)
else:
    from .models import DeviceTarget       # desarrollo

Detección de IP privada (frontend)

function isPrivateIPAddress(ip) {
    const parts = ip.split('.').map(Number);
    if (parts[0] === 10) return true;                                    // 10.0.0.0/8
    if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true; // 172.16.0.0/12
    if (parts[0] === 192 && parts[1] === 168) return true;               // 192.168.0.0/16
    if (parts[0] === 127) return true;                                   // localhost
    return false;
}

Convenciones y restricciones

Véase también

Subir