Files
ATLAS/deploy/proxmox/vm-setup.sh
ATLAS Admin e59aa2a742 feat: Complete ATLAS system installation and API fixes
## Backend Changes
- Add new API endpoints: combustible, pois, mantenimiento, video, configuracion
- Fix vehiculos endpoint to return paginated response with items array
- Add /vehiculos/all endpoint for non-paginated list
- Add /geocercas/all endpoint
- Add /alertas/configuracion GET/PUT endpoints
- Add /viajes/activos and /viajes/iniciar endpoints
- Add /reportes/stats, /reportes/templates, /reportes/preview endpoints
- Add /conductores/all and /conductores/disponibles endpoints
- Update router.py to include all new modules

## Frontend Changes
- Fix authentication token handling (snake_case vs camelCase)
- Update vehiculosApi.listAll to use /vehiculos/all
- Fix FuelGauge component usage in Combustible page
- Fix chart component exports (named + default exports)
- Update API client for proper token refresh

## Infrastructure
- Rename services from ADAN to ATLAS
- Configure Cloudflare tunnel for atlas.consultoria-as.com
- Update systemd service files
- Configure PostgreSQL with TimescaleDB
- Configure Redis, Mosquitto, Traccar, MediaMTX

## Documentation
- Update installation guides
- Update API reference
- Rename all ADAN references to ATLAS

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 03:04:23 +00:00

582 lines
15 KiB
Bash

#!/bin/bash
# ============================================
# Sistema de ATLAS - Crear VM en Proxmox
# ============================================
# Este script crea una VM en Proxmox VE lista para
# instalar el sistema de atlas
#
# Ejecutar en el HOST de Proxmox (no en una VM)
#
# Uso: ./vm-setup.sh [--vmid ID] [--name NOMBRE] [--memory MB] [--cores N]
#
# Requisitos:
# - Proxmox VE 7.x o 8.x
# - Almacenamiento local o compartido disponible
# - Acceso a internet para descargar ISO
# ============================================
set -e
set -o pipefail
# ---------------------------------------------
# Colores
# ---------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# ---------------------------------------------
# Configuracion por defecto
# ---------------------------------------------
# VM
VMID="${VMID:-200}"
VM_NAME="${VM_NAME:-atlas}"
VM_MEMORY="${VM_MEMORY:-4096}" # MB
VM_CORES="${VM_CORES:-4}"
VM_DISK_SIZE="${VM_DISK_SIZE:-50}" # GB
VM_SOCKETS="${VM_SOCKETS:-1}"
# Red
VM_BRIDGE="${VM_BRIDGE:-vmbr0}"
VM_VLAN="${VM_VLAN:-}" # Dejar vacio si no usa VLAN
VM_IP="${VM_IP:-dhcp}" # O IP estatica: 192.168.1.100/24
VM_GATEWAY="${VM_GATEWAY:-}" # Solo si IP estatica
VM_DNS="${VM_DNS:-8.8.8.8}"
# Almacenamiento
STORAGE="${STORAGE:-local-lvm}"
ISO_STORAGE="${ISO_STORAGE:-local}"
# Ubuntu
UBUNTU_VERSION="22.04.4"
UBUNTU_ISO="ubuntu-${UBUNTU_VERSION}-live-server-amd64.iso"
UBUNTU_URL="https://releases.ubuntu.com/22.04/${UBUNTU_ISO}"
# Cloud-init (para configuracion automatica)
USE_CLOUD_INIT="${USE_CLOUD_INIT:-true}"
CI_USER="${CI_USER:-atlas}"
CI_PASSWORD="${CI_PASSWORD:-}" # Se genera si esta vacio
CI_SSH_KEY="${CI_SSH_KEY:-}" # Ruta a archivo de clave publica
# ---------------------------------------------
# Funciones
# ---------------------------------------------
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[OK]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Generar password aleatorio
generate_password() {
openssl rand -base64 16 | tr -dc 'a-zA-Z0-9' | head -c 16
}
# Verificar si comando existe
command_exists() {
command -v "$1" &> /dev/null
}
# ---------------------------------------------
# Parsear argumentos
# ---------------------------------------------
parse_args() {
while [[ $# -gt 0 ]]; do
case $1 in
--vmid)
VMID="$2"
shift 2
;;
--name)
VM_NAME="$2"
shift 2
;;
--memory)
VM_MEMORY="$2"
shift 2
;;
--cores)
VM_CORES="$2"
shift 2
;;
--disk)
VM_DISK_SIZE="$2"
shift 2
;;
--storage)
STORAGE="$2"
shift 2
;;
--bridge)
VM_BRIDGE="$2"
shift 2
;;
--ip)
VM_IP="$2"
shift 2
;;
--gateway)
VM_GATEWAY="$2"
shift 2
;;
--ssh-key)
CI_SSH_KEY="$2"
shift 2
;;
--no-cloud-init)
USE_CLOUD_INIT=false
shift
;;
--help|-h)
show_help
exit 0
;;
*)
log_error "Opcion desconocida: $1"
exit 1
;;
esac
done
}
show_help() {
echo "Sistema de ATLAS - Crear VM en Proxmox"
echo ""
echo "Uso: $0 [opciones]"
echo ""
echo "Opciones:"
echo " --vmid ID ID de la VM (default: 200)"
echo " --name NOMBRE Nombre de la VM (default: atlas)"
echo " --memory MB Memoria RAM en MB (default: 4096)"
echo " --cores N Numero de cores (default: 4)"
echo " --disk GB Tamanio de disco en GB (default: 50)"
echo " --storage NAME Almacenamiento Proxmox (default: local-lvm)"
echo " --bridge NAME Bridge de red (default: vmbr0)"
echo " --ip IP/CIDR IP estatica o 'dhcp' (default: dhcp)"
echo " --gateway IP Gateway (requerido si IP estatica)"
echo " --ssh-key FILE Archivo de clave SSH publica"
echo " --no-cloud-init No usar cloud-init"
echo ""
echo "Ejemplos:"
echo " $0 --vmid 200 --name atlas --memory 8192 --cores 4"
echo " $0 --ip 192.168.1.100/24 --gateway 192.168.1.1"
}
# ---------------------------------------------
# Verificar requisitos
# ---------------------------------------------
check_requirements() {
log_info "Verificando requisitos..."
# Verificar que estamos en Proxmox
if ! command_exists pvesh; then
log_error "Este script debe ejecutarse en un host Proxmox"
exit 1
fi
# Verificar version de Proxmox
PVE_VERSION=$(pveversion --verbose | grep "pve-manager" | awk '{print $2}')
log_info "Proxmox VE version: $PVE_VERSION"
# Verificar que VMID no existe
if qm status $VMID &> /dev/null; then
log_error "Ya existe una VM con ID $VMID"
log_error "Usa --vmid para especificar otro ID"
exit 1
fi
# Verificar almacenamiento
if ! pvesm status | grep -q "^${STORAGE}"; then
log_error "Almacenamiento '$STORAGE' no encontrado"
log_error "Almacenamientos disponibles:"
pvesm status
exit 1
fi
# Verificar bridge de red
if ! ip link show "$VM_BRIDGE" &> /dev/null; then
log_warn "Bridge '$VM_BRIDGE' no encontrado"
log_warn "Bridges disponibles:"
ip link show type bridge
fi
log_success "Requisitos verificados"
}
# ---------------------------------------------
# Descargar ISO de Ubuntu
# ---------------------------------------------
download_ubuntu_iso() {
log_info "Verificando ISO de Ubuntu..."
ISO_PATH="/var/lib/vz/template/iso/${UBUNTU_ISO}"
if [[ -f "$ISO_PATH" ]]; then
log_success "ISO ya existe: $ISO_PATH"
return
fi
log_info "Descargando Ubuntu ${UBUNTU_VERSION}..."
log_info "URL: $UBUNTU_URL"
# Crear directorio si no existe
mkdir -p /var/lib/vz/template/iso
# Descargar con wget
wget -q --show-progress -O "$ISO_PATH" "$UBUNTU_URL"
if [[ ! -f "$ISO_PATH" ]]; then
log_error "Error al descargar ISO"
exit 1
fi
log_success "ISO descargada: $ISO_PATH"
}
# ---------------------------------------------
# Descargar imagen Cloud-Init (alternativa)
# ---------------------------------------------
download_cloud_image() {
log_info "Descargando imagen Ubuntu Cloud..."
CLOUD_IMAGE="ubuntu-22.04-server-cloudimg-amd64.img"
CLOUD_URL="https://cloud-images.ubuntu.com/jammy/current/${CLOUD_IMAGE}"
CLOUD_PATH="/var/lib/vz/template/iso/${CLOUD_IMAGE}"
if [[ -f "$CLOUD_PATH" ]]; then
log_success "Imagen cloud ya existe"
return
fi
wget -q --show-progress -O "$CLOUD_PATH" "$CLOUD_URL"
log_success "Imagen descargada: $CLOUD_PATH"
}
# ---------------------------------------------
# Crear VM
# ---------------------------------------------
create_vm() {
log_info "Creando VM..."
# Configuracion de red
NET_CONFIG="virtio,bridge=${VM_BRIDGE}"
if [[ -n "$VM_VLAN" ]]; then
NET_CONFIG="${NET_CONFIG},tag=${VM_VLAN}"
fi
# Crear VM base
qm create $VMID \
--name "$VM_NAME" \
--description "Sistema de ATLAS GPS" \
--ostype l26 \
--machine q35 \
--bios ovmf \
--cpu host \
--sockets $VM_SOCKETS \
--cores $VM_CORES \
--memory $VM_MEMORY \
--balloon 0 \
--net0 "$NET_CONFIG" \
--scsihw virtio-scsi-pci \
--agent enabled=1
log_success "VM creada con ID: $VMID"
}
# ---------------------------------------------
# Agregar disco
# ---------------------------------------------
add_disk() {
log_info "Creando disco de ${VM_DISK_SIZE}GB..."
# Agregar disco SCSI
qm set $VMID \
--scsi0 "${STORAGE}:${VM_DISK_SIZE},discard=on,ssd=1" \
--boot order=scsi0
# Agregar EFI disk
qm set $VMID \
--efidisk0 "${STORAGE}:1,efitype=4m,pre-enrolled-keys=1"
log_success "Disco agregado"
}
# ---------------------------------------------
# Agregar ISO o Cloud-Init
# ---------------------------------------------
add_boot_media() {
if [[ "$USE_CLOUD_INIT" == "true" ]]; then
setup_cloud_init
else
attach_iso
fi
}
attach_iso() {
log_info "Adjuntando ISO de instalacion..."
ISO_PATH="${ISO_STORAGE}:iso/${UBUNTU_ISO}"
qm set $VMID \
--ide2 "$ISO_PATH,media=cdrom" \
--boot order="ide2;scsi0"
log_success "ISO adjuntada"
log_warn "Deberas completar la instalacion manualmente"
}
setup_cloud_init() {
log_info "Configurando Cloud-Init..."
# Generar password si no se especifico
if [[ -z "$CI_PASSWORD" ]]; then
CI_PASSWORD=$(generate_password)
log_info "Password generado: $CI_PASSWORD"
fi
# Agregar drive de cloud-init
qm set $VMID --ide2 "${STORAGE}:cloudinit"
# Configurar cloud-init
qm set $VMID \
--ciuser "$CI_USER" \
--cipassword "$CI_PASSWORD"
# Configurar red
if [[ "$VM_IP" == "dhcp" ]]; then
qm set $VMID --ipconfig0 ip=dhcp
else
qm set $VMID --ipconfig0 "ip=${VM_IP},gw=${VM_GATEWAY}"
fi
# DNS
qm set $VMID --nameserver "$VM_DNS"
# SSH key si se especifico
if [[ -n "$CI_SSH_KEY" ]] && [[ -f "$CI_SSH_KEY" ]]; then
qm set $VMID --sshkeys "$CI_SSH_KEY"
log_info "SSH key configurada"
fi
# Importar imagen cloud
CLOUD_IMAGE="/var/lib/vz/template/iso/ubuntu-22.04-server-cloudimg-amd64.img"
if [[ -f "$CLOUD_IMAGE" ]]; then
log_info "Importando imagen cloud al disco..."
qm importdisk $VMID "$CLOUD_IMAGE" $STORAGE
qm set $VMID --scsi0 "${STORAGE}:vm-${VMID}-disk-1"
qm resize $VMID scsi0 ${VM_DISK_SIZE}G
else
log_warn "Imagen cloud no encontrada, usando ISO tradicional"
attach_iso
return
fi
log_success "Cloud-Init configurado"
}
# ---------------------------------------------
# Configurar opciones adicionales
# ---------------------------------------------
configure_vm_options() {
log_info "Configurando opciones adicionales..."
# Habilitar QEMU guest agent
qm set $VMID --agent enabled=1
# Configurar arranque automatico
qm set $VMID --onboot 1
# Configurar proteccion (evitar eliminacion accidental)
# qm set $VMID --protection 1
# Tags para organizacion
qm set $VMID --tags "atlas,gps,produccion"
log_success "Opciones configuradas"
}
# ---------------------------------------------
# Crear script de post-instalacion
# ---------------------------------------------
create_post_install_script() {
log_info "Creando script de post-instalacion..."
POST_INSTALL_DIR="/var/lib/vz/snippets"
mkdir -p "$POST_INSTALL_DIR"
cat > "${POST_INSTALL_DIR}/atlas-postinstall.sh" <<'SCRIPT'
#!/bin/bash
# Script de post-instalacion para Sistema de ATLAS
# Ejecutar despues de instalar Ubuntu
set -e
echo "=== Actualizando sistema ==="
apt-get update && apt-get upgrade -y
echo "=== Instalando QEMU Guest Agent ==="
apt-get install -y qemu-guest-agent
systemctl enable qemu-guest-agent
systemctl start qemu-guest-agent
echo "=== Instalando dependencias basicas ==="
apt-get install -y \
curl \
wget \
git \
htop \
net-tools \
ufw
echo "=== Configurando firewall basico ==="
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 5055/tcp # Traccar GPS
ufw --force enable
echo "=== Listo! ==="
echo "Ahora ejecuta el script de instalacion:"
echo " cd /opt && git clone REPO_URL atlas"
echo " cd atlas/deploy/scripts"
echo " sudo ./install.sh"
SCRIPT
chmod +x "${POST_INSTALL_DIR}/atlas-postinstall.sh"
log_success "Script creado en: ${POST_INSTALL_DIR}/atlas-postinstall.sh"
}
# ---------------------------------------------
# Generar archivo de credenciales
# ---------------------------------------------
save_credentials() {
CREDS_FILE="/root/vm-${VMID}-credentials.txt"
cat > "$CREDS_FILE" <<EOF
# ============================================
# Credenciales VM Sistema de ATLAS
# ============================================
# Generadas: $(date)
VM_ID: $VMID
VM_NAME: $VM_NAME
VM_IP: $VM_IP
# Acceso SSH
Usuario: $CI_USER
Password: $CI_PASSWORD
# Despues de iniciar la VM:
# 1. Conectarse: ssh ${CI_USER}@IP_DE_LA_VM
# 2. Ejecutar script de instalacion
# Comandos utiles:
# - Iniciar VM: qm start $VMID
# - Consola: qm terminal $VMID
# - Detener: qm shutdown $VMID
# - Estado: qm status $VMID
EOF
chmod 600 "$CREDS_FILE"
log_success "Credenciales guardadas en: $CREDS_FILE"
}
# ---------------------------------------------
# Mostrar resumen
# ---------------------------------------------
show_summary() {
echo ""
echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN} VM CREADA EXITOSAMENTE${NC}"
echo -e "${GREEN}============================================${NC}"
echo ""
echo -e "${BLUE}Configuracion:${NC}"
echo " ID: $VMID"
echo " Nombre: $VM_NAME"
echo " Memoria: ${VM_MEMORY}MB"
echo " Cores: $VM_CORES"
echo " Disco: ${VM_DISK_SIZE}GB"
echo " Red: $VM_BRIDGE"
echo ""
if [[ "$USE_CLOUD_INIT" == "true" ]]; then
echo -e "${BLUE}Cloud-Init:${NC}"
echo " Usuario: $CI_USER"
echo " Password: $CI_PASSWORD"
echo " IP: $VM_IP"
echo ""
fi
echo -e "${BLUE}Siguientes pasos:${NC}"
echo " 1. Iniciar la VM:"
echo " qm start $VMID"
echo ""
if [[ "$USE_CLOUD_INIT" == "true" ]]; then
echo " 2. Esperar a que inicie y conectarse:"
echo " ssh ${CI_USER}@<IP_DE_LA_VM>"
echo ""
else
echo " 2. Abrir consola y completar instalacion de Ubuntu:"
echo " qm terminal $VMID"
echo ""
fi
echo " 3. Ejecutar script de instalacion del sistema:"
echo " git clone <REPO_URL> /opt/atlas"
echo " cd /opt/atlas/deploy/scripts"
echo " sudo ./install.sh"
echo ""
echo -e "${GREEN}============================================${NC}"
}
# ---------------------------------------------
# Main
# ---------------------------------------------
main() {
parse_args "$@"
echo ""
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE} CREAR VM PARA SISTEMA DE ATLAS${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""
check_requirements
if [[ "$USE_CLOUD_INIT" == "true" ]]; then
download_cloud_image
else
download_ubuntu_iso
fi
create_vm
add_disk
add_boot_media
configure_vm_options
create_post_install_script
save_credentials
show_summary
}
# Ejecutar
main "$@"