Compare commits
No commits in common. "main" and "working-installer" have entirely different histories.
main
...
working-in
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 13 KiB |
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 4.1 KiB |
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 6.7 KiB |
|
@ -21,10 +21,6 @@ OGREPOSITORY_REPO="$OPENGNSYS_BASE_URL/ogrepository.git"
|
|||
export GIT_SSL_NO_VERIFY=1
|
||||
|
||||
|
||||
# Creamos el usuario opengnsys
|
||||
|
||||
useradd -m -d /opt/opengnsys -r -s /bin/bash opengnsys
|
||||
|
||||
## Functions
|
||||
|
||||
function install_docker() {
|
||||
|
@ -127,7 +123,7 @@ do
|
|||
mkdir -p $component_dir/etc
|
||||
cp $component_dir/repo/.env $component_dir/etc/
|
||||
cp $component_dir/repo/env.json $component_dir/etc/
|
||||
chown 82:82 $component_dir/etc/env.json
|
||||
mkdir -p $component_dir/etc/
|
||||
mkdir -p $component_dir/bin/
|
||||
cp $CONFIGS_DIR/provision_ogcore.sh $component_dir/bin/
|
||||
chmod 755 $component_dir/bin/provision_ogcore.sh
|
|
@ -3,8 +3,14 @@
|
|||
set -x
|
||||
|
||||
CONF_DIR=/opt/opengnsys/ogCore/etc/
|
||||
cd /opt/opengnsys/ogCore/repo/ || exit
|
||||
cd /opt/opengnsys/ogCore/repo/
|
||||
|
||||
# Preparar el fichero .yaml
|
||||
# CONF_DIR=/opt/opengnsys/ogCore/etc/
|
||||
# mkdir -p $CONF_DIR
|
||||
|
||||
# Copiar el fichero de configuración a CONF_DIR
|
||||
# cp docker-compose-deploy.yml $CONF_DIR/
|
||||
|
||||
if [ -f /opt/opengnsys/ogCore/installer/.deployed ]; then
|
||||
echo "ogCore ya instalado"
|
||||
|
@ -18,20 +24,11 @@ done
|
|||
adminuser=$(jq -r '.username' /opt/opengnsys/ogCore/installer/config.json)
|
||||
adminpass=$(jq -r '.password' /opt/opengnsys/ogCore/installer/config.json)
|
||||
|
||||
# Despliega la aplicación
|
||||
docker compose -f $CONF_DIR/docker-compose-deploy.yml exec php composer install
|
||||
# Genera las claves de JWT
|
||||
docker compose -f $CONF_DIR/docker-compose-deploy.yml exec php php bin/console lexik:jwt:generate-keypair --overwrite
|
||||
# Crea/actualiza la base de datos
|
||||
docker compose -f $CONF_DIR/docker-compose-deploy.yml exec php php bin/console doctrine:migrations:migrate --no-interaction
|
||||
# Carga los datos por defecto: usuario
|
||||
## TODO we need to feed $adminuser and $adminpass to doctrine:fixtures:load somehow
|
||||
docker compose -f $CONF_DIR/docker-compose-deploy.yml exec php php bin/console doctrine:fixtures:load --no-interaction
|
||||
# Carga los datos por defecto: roles
|
||||
docker compose -f $CONF_DIR/docker-compose-deploy.yml exec php bin/console app:load-default-user-groups
|
||||
# Carga los datos por defecto: comandos
|
||||
docker compose -f $CONF_DIR/docker-compose-deploy.yml exec php php bin/console app:load-default-commands
|
||||
# Carga los datos por defecto: menú
|
||||
docker compose -f $CONF_DIR/docker-compose-deploy.yml exec php php bin/console opengnsys:load-default-menu
|
||||
|
||||
|
||||
# Provision user admin
|
||||
|
@ -51,6 +48,5 @@ curl -k -L --location 'https://localhost:8443/users' \
|
|||
--header "Authorization: Bearer $bearer" \
|
||||
--data "{ \"username\": \"$adminuser\", \"password\": \"$adminpass\", \"roles\": [\"ROLE_SUPER_ADMIN\"] }"
|
||||
|
||||
|
||||
touch /opt/opengnsys/ogCore/installer/.deployed
|
||||
exit 0
|
|
@ -0,0 +1,42 @@
|
|||
#!/bin/bash
|
||||
#
|
||||
set -x
|
||||
|
||||
# preparar el fichero .env
|
||||
ENV_DIR=/opt/opengnsys/ogGui/etc/
|
||||
ENV_FILE=$ENV_DIR/.env
|
||||
mkdir -p $ENV_DIR
|
||||
|
||||
# Comprobar si ya se ha instalado ogCore
|
||||
if [ -f /opt/opengnsys/ogGui/installer/.deployed ]; then
|
||||
echo "ogCore ya instalado"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Sacar la IP del ogCore de la configuración
|
||||
ogcore_ip=$(jq -r '.ogcore_ip' /opt/opengnsys/ogGui/installer/config.json)
|
||||
export OGCORE_IP="$ogcore_ip"
|
||||
|
||||
# Si no se ha configurado la IP del ogCore, se intenta obtener de la interfaz de red
|
||||
if [ -z "$ogcore_ip" ]; then
|
||||
# Obtiene el nombre del interfaz asociado a la ruta por defecto
|
||||
interface=$(ip route | grep default | awk '{print $5}')
|
||||
|
||||
# Si se encuentra el interfaz, obtiene su dirección IP
|
||||
if [ -n "$interface" ]; then
|
||||
ip_address=$(ip -o -4 addr show "$interface" | awk '{print $4}' | cut -d'/' -f1)
|
||||
ogcore_ip=$ip_address
|
||||
# Si no se ha configurado la IP del ogCore, se escribe en el fichero .env
|
||||
echo "NG_APP_BASE_API_URL=https://$ogcore_ip:8443" > $ENV_FILE
|
||||
exit 0
|
||||
else
|
||||
echo "No se pudo determinar el interfaz asociado a la ruta por defecto."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
# Si se ha configurado la IP del ogCore, se escribe en el fichero .env
|
||||
echo "NG_APP_BASE_API_URL=$OGCORE_IP" > $ENV_FILE
|
||||
|
||||
touch /opt/opengnsys/ogGui/installer/.deployed
|
|
@ -10,7 +10,6 @@ OGPASS=${4:-"og"}
|
|||
INSTALL_DIR=/opt/opengnsys/ogrepository
|
||||
DOWNLOAD_DIR=${5:-"/tmp/ogrepository"}
|
||||
DEBIAN_FRONTEND=noninteractive
|
||||
OGUSER_HOME=/opt/opengnsys
|
||||
export DEBIAN_FRONTEND
|
||||
export GIT_SSL_NO_VERIFY
|
||||
|
||||
|
@ -35,33 +34,24 @@ install_updcast () {
|
|||
add_user_ogrepository() {
|
||||
if ! id "$OGUSER" &>/dev/null; then
|
||||
echo "User ogrepository does not exist, creating it"
|
||||
useradd -m -d $OGUSER_HOME -r -s /bin/bash $OGUSER
|
||||
useradd -r -s /bin/bash $OGUSER
|
||||
fi
|
||||
if [ ! -d $OGUSER_HOME/.ssh ] ; then
|
||||
mkdir -p $OGUSER_HOME/.ssh
|
||||
cp /tmp/oginstall/ssh-keys/opengnsys $OGUSER_HOME/.ssh/id_ed25519
|
||||
cp /tmp/oginstall/ssh-keys/opengnsys.pub $OGUSER_HOME/.ssh/id_ed25519.pub
|
||||
cat /tmp/oginstall/ssh-keys/opengnsys.pub >> $OGUSER_HOME/.ssh/authorized_keys
|
||||
chown -R $OGUSER:$OGUSER $OGUSER_HOME/.ssh
|
||||
chmod 0600 $OGUSER_HOME/.ssh/*
|
||||
fi
|
||||
if [ ! -f /etc/sudoers.d/$OGUSER ]; then
|
||||
echo "User $OGUSER does not have sudo permissions, adding it"
|
||||
echo "$OGUSER ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/"$OGUSER"
|
||||
fi
|
||||
|
||||
|
||||
}
|
||||
|
||||
create_directories() {
|
||||
mkdir -p $INSTALL_DIR
|
||||
mkdir -p $INSTALL_DIR/images $INSTALL_DIR/images_trash/ $INSTALL_DIR/bin/ $INSTALL_DIR/etc/ $INSTALL_DIR/log/ $INSTALL_DIR/api/ $INSTALL_DIR/images_virtual
|
||||
mkdir -p $INSTALL_DIR/images $INSTALL_DIR/images_trash/ $INSTALL_DIR/bin/ $INSTALL_DIR/etc/ $INSTALL_DIR/log/ $INSTALL_DIR/api/
|
||||
chown -R $OGUSER:$OGUSER $INSTALL_DIR
|
||||
}
|
||||
|
||||
install_dependencies() {
|
||||
apt update -y
|
||||
apt install -y git python3 python3-pip python3-flask python3-paramiko python3-psutil python3-flasgger debian-archive-keyring samba gunicorn wakeonlan lzop partclone qemu-utils
|
||||
apt install -y git python3 python3-pip python3-flask python3-paramiko python3-psutil python3-flasgger debian-archive-keyring samba gunicorn wakeonlan
|
||||
}
|
||||
|
||||
install_ext_repo() {
|
||||
|
@ -97,6 +87,7 @@ configure_samba() {
|
|||
systemctl restart smbd
|
||||
# Create default user ogrepository
|
||||
(echo $OGPASS; echo $OGPASS) | smbpasswd -s -a $OGUSER
|
||||
|
||||
}
|
||||
|
||||
## Main program
|
|
@ -1,27 +0,0 @@
|
|||
#!/bin/bash
|
||||
#
|
||||
set -x
|
||||
|
||||
# preparar el fichero .env
|
||||
ENV_DIR=/opt/opengnsys/ogGui/etc/
|
||||
ENV_FILE=$ENV_DIR/.env
|
||||
mkdir -p $ENV_DIR
|
||||
|
||||
# Comprobar si ya se ha instalado ogCore
|
||||
if [ -f /opt/opengnsys/ogGui/installer/.deployed ]; then
|
||||
echo "ogCore ya instalado"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Sacar la IP del ogCore de la configuración
|
||||
ogcore_url=$(jq -r '.ogcore_ip' /opt/opengnsys/ogGui/installer/config.json)
|
||||
mercure_ip=$(jq -r '.mercure_ip' /opt/opengnsys/ogGui/installer/config.json)
|
||||
export OGCORE_URL="$ogcore_url"
|
||||
export MERCURE_URL="$mercure_url"
|
||||
|
||||
|
||||
# Si se ha configurado la IP del ogCore, se escribe en el fichero .env
|
||||
echo "NG_APP_BASE_API_URL=$OGCORE_URL" > $ENV_FILE
|
||||
echo "NG_APP_OGCORE_MERCURE_BASE_URL=https://$mercure_ip:3000/.well-known/mercure" >> $ENV_FILE
|
||||
|
||||
touch /opt/opengnsys/ogGui/installer/.deployed
|
|
@ -1,7 +0,0 @@
|
|||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBs7Wbqztq5ixPGFL+1DlTa0T6QUBMiLq6KxZnCJ5rofQAAAJD7Xj89+14/
|
||||
PQAAAAtzc2gtZWQyNTUxOQAAACBs7Wbqztq5ixPGFL+1DlTa0T6QUBMiLq6KxZnCJ5rofQ
|
||||
AAAEC4UmYDisgl5jNR6SUwRA80k6Qc06cBHg1mW3+2NU6SfmztZurO2rmLE8YUv7UOVNrR
|
||||
PpBQEyIurorFmcInmuh9AAAABm5vbmFtZQECAwQFBgc=
|
||||
-----END OPENSSH PRIVATE KEY-----
|
|
@ -1 +0,0 @@
|
|||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGztZurO2rmLE8YUv7UOVNrRPpBQEyIurorFmcInmuh9 noname
|
|
@ -1,54 +0,0 @@
|
|||
import os
|
||||
from git import Repo
|
||||
from packaging.version import Version
|
||||
|
||||
def get_highest_remote_tag(repo_path):
|
||||
try:
|
||||
# Abre el repositorio local
|
||||
repo = Repo(repo_path)
|
||||
|
||||
# Asegúrate de que el repositorio tiene un remoto
|
||||
if not repo.remotes:
|
||||
return None # No hay remotos configurados
|
||||
|
||||
# Obtén el remoto por defecto (origin o el primero disponible)
|
||||
remote = repo.remotes.origin
|
||||
|
||||
# Recupera los tags remotos
|
||||
remote.fetch(tags=True)
|
||||
remote_tags = [ref.name.split('/')[-1] for ref in repo.references if ref.path.startswith('refs/tags/')]
|
||||
if not remote_tags:
|
||||
return None # No hay tags remotos
|
||||
|
||||
# Ordena los tags remotos por versión
|
||||
tags_sorted = sorted(remote_tags, key=lambda t: Version(t) if t.replace('.', '').isdigit() else Version('0.0.0'), reverse=True)
|
||||
return tags_sorted[0] if tags_sorted else None
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error al procesar el repositorio {repo_path}: {e}")
|
||||
return None
|
||||
|
||||
def process_selected_repositories(base_path, repo_names):
|
||||
repo_highest_tags = {}
|
||||
for repo_name in repo_names:
|
||||
repo_path = os.path.join(base_path, repo_name)
|
||||
if os.path.exists(repo_path) and os.path.isdir(os.path.join(repo_path, '.git')):
|
||||
highest_tag = get_highest_remote_tag(repo_path)
|
||||
repo_highest_tags[repo_name] = highest_tag
|
||||
else:
|
||||
repo_highest_tags[repo_name] = "No es un repositorio Git válido"
|
||||
return repo_highest_tags
|
||||
|
||||
# Ruta base donde están los repositorios locales
|
||||
base_path = "../"
|
||||
|
||||
# Lista de nombres de repositorios específicos
|
||||
repo_names = [ "ogcore" , "oggui" , "ogboot" , "ogdhcp" , "ogrepository" ]
|
||||
|
||||
result = process_selected_repositories(base_path, repo_names)
|
||||
|
||||
# Muestra los resultados
|
||||
for repo_name, tag in result.items():
|
||||
print(f'{repo_name}:{tag}')
|
||||
|
||||
|
|
@ -1,989 +0,0 @@
|
|||
import npyscreen
|
||||
import os
|
||||
from git import Repo
|
||||
import subprocess # Importar el módulo subprocess
|
||||
import requests # Importar el módulo requests
|
||||
import time # Importar time para simular el progreso
|
||||
import threading # Importar threading para leer el log en tiempo real
|
||||
import socket
|
||||
import sys # Importar sys para leer los argumentos del script
|
||||
import logging # Importar el módulo logging
|
||||
import shutil # Importar para verificar el tamaño del terminal
|
||||
|
||||
CONFIGS_DIR = "/tmp/oginstall"
|
||||
LOGS_DIR = "/var/log/oginstaller"
|
||||
|
||||
REPO_URL = "https://ognproject.evlt.uma.es/gitea/opengnsys/ogcore.git"
|
||||
|
||||
# Configurar logging y directorio configuración
|
||||
try:
|
||||
if not os.path.exists(LOGS_DIR):
|
||||
os.makedirs(LOGS_DIR, exist_ok=True)
|
||||
LOG_FILE = os.path.join(LOGS_DIR, "oginstall.log")
|
||||
if not os.path.exists(CONFIGS_DIR):
|
||||
os.makedirs(CONFIGS_DIR, exist_ok=True)
|
||||
|
||||
logging.basicConfig(
|
||||
filename=LOG_FILE,
|
||||
level=logging.DEBUG,
|
||||
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
logging.debug("Inicio del programa") # Mensaje inicial para verificar que el log se crea
|
||||
except Exception as e:
|
||||
print(f"[ERROR] No se pudo configurar el logging: {e}")
|
||||
print(f"[ERROR] Verifica los permisos del directorio: {LOGS_DIR}")
|
||||
exit(1) # Salir si no se puede configurar el logging
|
||||
|
||||
def get_network_interfaces():
|
||||
"""Obtiene los nombres de las interfaces de red disponibles en el servidor."""
|
||||
try:
|
||||
# Listar las interfaces de red desde /sys/class/net
|
||||
interfaces = os.listdir('/sys/class/net')
|
||||
# Filtrar interfaces válidas (excluyendo interfaces virtuales como 'lo')
|
||||
valid_interfaces = [iface for iface in interfaces if not iface.startswith('lo')]
|
||||
return ','.join(valid_interfaces) # Devuelve las interfaces separadas por comas
|
||||
except Exception as e:
|
||||
# En caso de error, devolver un valor por defecto
|
||||
print(f"Error al obtener las interfaces de red: {e}")
|
||||
return "eth0" # Valor por defecto
|
||||
|
||||
def get_available_versions():
|
||||
"""Obtiene la lista de versiones desde el archivo JSON remoto."""
|
||||
try:
|
||||
# Validar si se pasa un argumento
|
||||
if len(sys.argv) > 1:
|
||||
arg = sys.argv[1].strip().lower()
|
||||
logging.debug(f"Argumento recibido: {arg}") # Usar logging en lugar de print
|
||||
|
||||
# Validar explícitamente los valores permitidos
|
||||
if arg == "devel":
|
||||
url = "https://ognproject.evlt.uma.es/debian-opengnsys/versions-dev.json"
|
||||
elif arg == "nightly":
|
||||
logging.debug("No hay versiones disponibles para nightly. Usando 'latest'.")
|
||||
return ["latest"] # Devolver solo la opción 'latest'
|
||||
else:
|
||||
logging.debug(f"Argumento no reconocido: {arg}. Usando versiones de producción.")
|
||||
url = "https://ognproject.evlt.uma.es/debian-opengnsys/versions-prod.json"
|
||||
else:
|
||||
logging.debug("No se pasó ningún argumento. Usando versiones de producción.")
|
||||
url = "https://ognproject.evlt.uma.es/debian-opengnsys/versions-prod.json"
|
||||
|
||||
# Realizar la solicitud HTTP
|
||||
logging.debug(f"Realizando solicitud HTTP a: {url}")
|
||||
response = requests.get(url, timeout=10)
|
||||
response.raise_for_status() # Lanza una excepción si la respuesta no es 200 OK
|
||||
|
||||
# Registrar el contenido de la respuesta para depuración
|
||||
logging.debug(f"Contenido de la respuesta: {response.text}")
|
||||
|
||||
# Intentar analizar el JSON
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError as e:
|
||||
logging.error(f"Error al analizar el JSON: {e}")
|
||||
raise RuntimeError(f"El contenido de la respuesta no es un JSON válido: {e}")
|
||||
|
||||
# Validar que el JSON contiene la clave "versions"
|
||||
versions = data.get("versions", [])
|
||||
if not versions:
|
||||
logging.warning("La lista de versiones está vacía.")
|
||||
logging.debug(f"Versiones obtenidas: {versions}")
|
||||
return versions
|
||||
except (requests.RequestException, ValueError, RuntimeError) as e:
|
||||
logging.error(f"No se pudo obtener la lista de versiones: {e}")
|
||||
raise RuntimeError(f"Error crítico: {e}") # Lanzar una excepción crítica
|
||||
|
||||
def get_default_ip():
|
||||
"""Obtiene la IP asociada a la interfaz por defecto del servidor."""
|
||||
logging.debug("Obteniendo la IP por defecto del servidor.")
|
||||
try:
|
||||
# Obtener la interfaz asociada a la ruta por defecto
|
||||
result = subprocess.run(
|
||||
["ip", "route", "get", "1.1.1.1"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
# Extraer la interfaz de la salida
|
||||
interface = next((line.split()[-1] for line in result.stdout.splitlines() if "dev" in line), None)
|
||||
if not interface:
|
||||
logging.error("No se pudo determinar la interfaz por defecto.")
|
||||
raise ValueError("No se pudo determinar la interfaz por defecto.")
|
||||
logging.debug(f"Interfaz por defecto: {interface}")
|
||||
|
||||
# Obtener la IP de la interfaz
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("8.8.8.8", 80))
|
||||
ip_address = s.getsockname()[0]
|
||||
return ip_address
|
||||
except Exception as e:
|
||||
logging.error(f"Error al obtener la IP por defecto: {e}")
|
||||
return "192.168.2.2" # Valor por defecto
|
||||
|
||||
def get_oglive_list():
|
||||
"""Obtiene la lista de valores de oglives desde la URL."""
|
||||
try:
|
||||
# Realizar la solicitud HTTP
|
||||
response = requests.get("https://ognproject.evlt.uma.es/oglive/", timeout=10)
|
||||
response.raise_for_status() # Lanza una excepción si la respuesta no es 200 OK
|
||||
# Registrar el contenido de la respuesta para depuración
|
||||
|
||||
# Extraer los enlaces del contenido HTML
|
||||
from bs4 import BeautifulSoup
|
||||
soup = BeautifulSoup(response.text, "html.parser")
|
||||
links = [a["href"] for a in soup.find_all("a", href=True) if "ogLive" in a["href"]]
|
||||
|
||||
# Ordenar los enlaces por la parte después del guion bajo
|
||||
sorted_links = sorted(links, key=lambda x: x.split("_")[1] if "_" in x else x, reverse=True)
|
||||
return sorted_links
|
||||
except Exception as e:
|
||||
logging.error(f"Error al obtener la lista de oglives: {e}")
|
||||
return [] # Devolver una lista vacía en caso de error
|
||||
|
||||
# Variable global para la IP por defecto
|
||||
DEFAULT_IP = get_default_ip()
|
||||
|
||||
class InstallationTypeForm(npyscreen.ActionForm):
|
||||
"""Formulario para seleccionar el tipo de instalación."""
|
||||
def create(self):
|
||||
self.installation_type = self.add(
|
||||
npyscreen.TitleSelectOne,
|
||||
name="Selecciona el tipo de instalación:",
|
||||
values=["Mononodo", "Multinodo"],
|
||||
scroll_exit=False, max_height=10
|
||||
)
|
||||
|
||||
def on_ok(self):
|
||||
"""Guardar la selección y pasar al formulario correspondiente."""
|
||||
logging.debug(f"Entrando en InstallationTypeForm")
|
||||
if self.installation_type.value is None:
|
||||
npyscreen.notify_confirm("Debes seleccionar un tipo de instalación.", title="Error")
|
||||
return
|
||||
|
||||
if self.installation_type.value == [0]: # Mononodo
|
||||
logging.debug("Instalación mononodo seleccionada.")
|
||||
self.parentApp.installation_type = "mononodo"
|
||||
self.parentApp.setNextForm("MONONODO_CONFIG")
|
||||
elif self.installation_type.value == [1]: # Multinodo
|
||||
logging.debug("Instalación multinodo seleccionada.")
|
||||
self.parentApp.installation_type = "multinodo"
|
||||
self.parentApp.setNextForm("MULTINODO_CONFIG")
|
||||
|
||||
def on_cancel(self):
|
||||
"""Salir de la aplicación."""
|
||||
if npyscreen.notify_yes_no("¿Estás seguro de que deseas salir?", title="Confirmación"):
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
|
||||
class MononodoConfigForm(npyscreen.ActionForm):
|
||||
"""Formulario para configurar Mononodo."""
|
||||
def create(self):
|
||||
self.server_ip = self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor (mononodo):",
|
||||
value=get_default_ip()
|
||||
)
|
||||
|
||||
def on_ok(self):
|
||||
"""Guardar la configuración y pasar al siguiente formulario."""
|
||||
logging.debug(f"Entrando en MononodoConfigForm")
|
||||
self.parentApp.server_ip = self.server_ip.value
|
||||
self.parentApp.setNextForm("MAIN")
|
||||
|
||||
def on_cancel(self):
|
||||
"""Volver al formulario de selección de tipo de instalación."""
|
||||
self.parentApp.setNextForm("INSTALLATION_TYPE")
|
||||
|
||||
|
||||
class MultinodoConfigForm(npyscreen.ActionForm):
|
||||
"""Formulario para configurar Multinodo."""
|
||||
def create(self):
|
||||
self.repo_ip = self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor Repository:",
|
||||
value=get_default_ip()
|
||||
)
|
||||
self.dhcp_ip = self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor DHCP:",
|
||||
value=get_default_ip()
|
||||
)
|
||||
self.core_ip = self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor Core:",
|
||||
value=get_default_ip()
|
||||
)
|
||||
self.boot_ip = self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor Boot:",
|
||||
value=get_default_ip()
|
||||
)
|
||||
|
||||
def on_ok(self):
|
||||
"""Guardar la configuración y pasar al siguiente formulario."""
|
||||
self.parentApp.repo_ip = self.repo_ip.value
|
||||
self.parentApp.dhcp_ip = self.dhcp_ip.value
|
||||
self.parentApp.core_ip = self.core_ip.value
|
||||
self.parentApp.boot_ip = self.boot_ip.value
|
||||
self.parentApp.setNextForm("MAIN")
|
||||
|
||||
def on_cancel(self):
|
||||
"""Volver al formulario de selección de tipo de instalación."""
|
||||
self.parentApp.setNextForm("INSTALLATION_TYPE")
|
||||
|
||||
|
||||
class ComponentSelectionForm(npyscreen.ActionForm):
|
||||
def create(self):
|
||||
self.components = self.add(
|
||||
npyscreen.TitleMultiSelect,
|
||||
max_height=6,
|
||||
name="Selecciona los componentes",
|
||||
values=["ogCore", "ogGui", "ogDhcp", "ogBoot", "ogRepository"],
|
||||
scroll_exit=True
|
||||
)
|
||||
self.versions = get_available_versions() # Obtener las versiones desde el archivo JSON
|
||||
|
||||
# Si no hay versiones disponibles, usar "latest" como opción por defecto
|
||||
if not self.versions:
|
||||
self.versions = ["latest"]
|
||||
|
||||
self.tag = self.add(
|
||||
npyscreen.TitleSelectOne,
|
||||
max_height=10,
|
||||
name="Selecciona la versión",
|
||||
values=self.versions,
|
||||
scroll_exit=True
|
||||
)
|
||||
self.tag.value = [0] # Marcar "latest" (o la primera opción) por defecto
|
||||
|
||||
# Mostrar la IP del servidor si es mononodo
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
self.server_ip = self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor (mononodo):",
|
||||
value=self.parentApp.server_ip,
|
||||
editable=False
|
||||
)
|
||||
|
||||
# Agregar un cuadro de texto para mostrar el log
|
||||
self.log_box = self.add(
|
||||
npyscreen.BoxTitle,
|
||||
name="Log de depuración",
|
||||
max_height=10,
|
||||
scroll_exit=True
|
||||
)
|
||||
|
||||
def beforeEditing(self):
|
||||
"""Configurar los valores iniciales de los componentes según el tipo de instalación."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
# Seleccionar todos los componentes por defecto
|
||||
self.components.value = list(range(len(self.components.values)))
|
||||
else:
|
||||
# No seleccionar ningún componente por defecto
|
||||
self.components.value = []
|
||||
self.display()
|
||||
|
||||
def on_ok(self):
|
||||
# Validar selección obligatoria de componentes y versión
|
||||
if not self.components.value or len(self.components.value) == 0:
|
||||
npyscreen.notify_confirm("Debes seleccionar al menos un componente.", title="Error")
|
||||
return
|
||||
if not self.tag.value or len(self.tag.value) == 0:
|
||||
npyscreen.notify_confirm("Debes seleccionar una versión.", title="Error")
|
||||
return
|
||||
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
self.handle_mononodo()
|
||||
else:
|
||||
self.handle_multinodo()
|
||||
|
||||
def handle_mononodo(self):
|
||||
npyscreen.blank_terminal()
|
||||
selected_components = [self.components.values[i].lower() for i in self.components.value]
|
||||
selected_tag = self.versions[self.tag.value[0]]
|
||||
self.parentApp.selected_components = selected_components
|
||||
self.parentApp.selected_tag = selected_tag
|
||||
self.parentApp.current_component_index = 0
|
||||
self.parentApp.configurations = {}
|
||||
self.parentApp.switchForm(selected_components[0])
|
||||
|
||||
def handle_multinodo(self):
|
||||
selected_components = [self.components.values[i].lower() for i in self.components.value]
|
||||
selected_tag = self.versions[self.tag.value[0]]
|
||||
self.parentApp.selected_components = selected_components
|
||||
self.parentApp.selected_tag = selected_tag
|
||||
self.parentApp.current_component_index = 0
|
||||
self.parentApp.configurations = {}
|
||||
self.parentApp.switchForm(selected_components[0])
|
||||
|
||||
class ComponentForm(npyscreen.ActionForm):
|
||||
component_name = None
|
||||
|
||||
def create(self):
|
||||
# Agregar un título dinámico basado en el componente en la primera línea
|
||||
self.title = self.add(
|
||||
npyscreen.FixedText,
|
||||
value="",
|
||||
editable=False,
|
||||
color="STANDOUT",
|
||||
rely=0 # Forzar que el título esté en la primera línea
|
||||
)
|
||||
self.fields = {}
|
||||
|
||||
def beforeEditing(self):
|
||||
npyscreen.blank_terminal()
|
||||
# Actualizar el valor del título dinámico basado en el componente
|
||||
self.title.value = f"Configuración del componente: {self.component_name.upper()}"
|
||||
self.title.display()
|
||||
self._recreate_form()
|
||||
|
||||
def _recreate_form(self):
|
||||
"""Limpia y recrea los widgets del formulario, excepto el título."""
|
||||
# No eliminar el título al recrear los widgets
|
||||
self._widgets__ = [self.title]
|
||||
self._widgets_by_id__ = {id(self.title): self.title}
|
||||
self._contained_widgets = [self.title]
|
||||
self.configure_fields()
|
||||
|
||||
def configure_fields(self):
|
||||
"""Método para definir los campos de configuración para cada componente"""
|
||||
pass
|
||||
|
||||
def on_ok(self):
|
||||
npyscreen.blank_terminal()
|
||||
component_config = {}
|
||||
|
||||
for key, field_data in self.fields.items():
|
||||
component_config[key] = field_data["widget"].value
|
||||
|
||||
self.parentApp.configurations[self.component_name] = component_config
|
||||
|
||||
self.parentApp.current_component_index += 1
|
||||
if self.parentApp.current_component_index < len(self.parentApp.selected_components):
|
||||
next_component = self.parentApp.selected_components[self.parentApp.current_component_index]
|
||||
self.parentApp.switchForm(next_component)
|
||||
else:
|
||||
self.parentApp.generate_debconf()
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
def on_cancel(self):
|
||||
if npyscreen.notify_yes_no("¿Estás seguro de que deseas salir?", title="Confirmación"):
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
class OgCoreForm(ComponentForm):
|
||||
component_name = "ogcore"
|
||||
|
||||
def configure_fields(self):
|
||||
|
||||
self.add(npyscreen.FixedText, value="Usuario Administrador: ", editable=False, rely=2, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["adminUser"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value="ogadmin",
|
||||
rely=3, # Línea siguiente
|
||||
relx=18,
|
||||
highlighted=True
|
||||
)
|
||||
}
|
||||
self.fields["adminPass"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.TitlePassword,
|
||||
name="Contraseña Administrador:",
|
||||
value="12345678",
|
||||
rely=6 , # Ajustar la posición vertical
|
||||
highlighted=True ,
|
||||
scroll_exit=True
|
||||
)
|
||||
}
|
||||
|
||||
class OgGuiForm(ComponentForm):
|
||||
component_name = "oggui"
|
||||
|
||||
def configure_fields(self):
|
||||
"""Configura los campos del formulario según el tipo de instalación."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
self.server_ip = self.parentApp.server_ip
|
||||
elif self.parentApp.installation_type == "multinodo":
|
||||
self.server_ip = self.parentApp.core_ip
|
||||
|
||||
self.add(npyscreen.FixedText, value="URL del servidor Core:", editable=False, rely=2, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["ogcoreUrl"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value=f"https://{self.server_ip}:8443",
|
||||
rely=3 ,
|
||||
relx=18,
|
||||
highlighted=True# Ajustar la posición vertical
|
||||
)
|
||||
}
|
||||
self.add(npyscreen.FixedText, value="URL del servidor Mercure:", editable=False, rely=4, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["ogmercureUrl"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value=f"https://{self.server_ip}:3000/.well-known/mercure",
|
||||
rely=6,
|
||||
relx=18# Ajustar la posición vertical
|
||||
)
|
||||
}
|
||||
|
||||
def on_ok(self):
|
||||
"""Guarda la configuración y pasa al siguiente formulario."""
|
||||
# Obtener la configuración del formulario
|
||||
component_config = {
|
||||
"ogcoreUrl": self.fields["ogcoreUrl"]["widget"].value,
|
||||
"ogmercureUrl": self.fields["ogmercureUrl"]["widget"].value,
|
||||
}
|
||||
|
||||
# Guardar la configuración en el diccionario global
|
||||
self.parentApp.configurations[self.component_name] = component_config
|
||||
|
||||
# Continuar con el siguiente formulario
|
||||
self.parentApp.current_component_index += 1
|
||||
if self.parentApp.current_component_index < len(self.parentApp.selected_components):
|
||||
next_component = self.parentApp.selected_components[self.parentApp.current_component_index]
|
||||
self.parentApp.switchForm(next_component)
|
||||
else:
|
||||
self.parentApp.generate_debconf()
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
|
||||
class OgDhcpForm(ComponentForm):
|
||||
component_name = "ogdhcp"
|
||||
|
||||
def get_dhcp_ip(self):
|
||||
"""Obtiene la IP del servidor DHCP."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
return self.parentApp.server_ip
|
||||
elif self.parentApp.installation_type == "multinodo":
|
||||
return self.parentApp.dhcp_ip
|
||||
|
||||
def get_boot_ip(self):
|
||||
"""Obtiene la IP del servidor Boot."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
return self.parentApp.server_ip
|
||||
elif self.parentApp.installation_type == "multinodo":
|
||||
return self.parentApp.boot_ip
|
||||
|
||||
def configure_fields(self):
|
||||
# Obtener las interfaces de red disponibles
|
||||
available_interfaces = get_network_interfaces().split(",")
|
||||
|
||||
# Selector de interfaces con altura ajustada
|
||||
self.fields["dhcp_interfaces"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.TitleMultiSelect,
|
||||
name="Selecciona la interfaz de DHCP:",
|
||||
values=available_interfaces,
|
||||
scroll_exit=True,
|
||||
rely=2,
|
||||
max_height=5 # Reducir la altura para dejar espacio
|
||||
)
|
||||
}
|
||||
|
||||
# Campo para la IP del servidor DHCP
|
||||
self.fields["ip"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor DHCP:",
|
||||
value=self.get_dhcp_ip(),
|
||||
rely=8 # Ajustar la posición vertical
|
||||
)
|
||||
}
|
||||
|
||||
# Campo para la IP del servidor Boot
|
||||
self.fields["ogbootIP"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.TitleText,
|
||||
name="IP del servidor Boot:",
|
||||
value=self.get_boot_ip(),
|
||||
rely=10 # Ajustar la posición vertical
|
||||
)
|
||||
}
|
||||
|
||||
def on_ok(self):
|
||||
available_interfaces = self.fields["dhcp_interfaces"]["widget"].values
|
||||
selected_indices = self.fields["dhcp_interfaces"]["widget"].value
|
||||
# Validar que al menos un interfaz esté seleccionado
|
||||
if not selected_indices or len(selected_indices) == 0:
|
||||
npyscreen.notify_confirm("Debes seleccionar al menos una interfaz de red para DHCP.", title="Error")
|
||||
return
|
||||
try:
|
||||
for i in selected_indices:
|
||||
if i < 0 or i >= len(available_interfaces):
|
||||
raise IndexError("Índice fuera de rango")
|
||||
selected_interfaces = [available_interfaces[i] for i in selected_indices]
|
||||
logging.debug(f"Interfaces seleccionadas: {selected_interfaces}")
|
||||
interfaces_string = ",".join(selected_interfaces)
|
||||
logging.debug(f"Interfaces seleccionadas: {interfaces_string}")
|
||||
except (IndexError, ValueError):
|
||||
npyscreen.notify_confirm("Selección inválida. Por favor, revisa los índices ingresados.", title="Error")
|
||||
return
|
||||
|
||||
# Guardar las configuraciones
|
||||
self.parentApp.configurations[self.component_name] = {
|
||||
"interfaces": interfaces_string,
|
||||
"ip": self.fields["ip"]["widget"].value,
|
||||
"ogbootIP": self.fields["ogbootIP"]["widget"].value,
|
||||
}
|
||||
|
||||
# Continuar con el siguiente formulario
|
||||
self.parentApp.current_component_index += 1
|
||||
if self.parentApp.current_component_index < len(self.parentApp.selected_components):
|
||||
next_component = self.parentApp.selected_components[self.parentApp.current_component_index]
|
||||
self.parentApp.switchForm(next_component)
|
||||
else:
|
||||
self.parentApp.generate_debconf()
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
class OgBootForm(ComponentForm):
|
||||
component_name = "ogboot"
|
||||
download_url = "https://ognproject.evlt.uma.es/oglive/"
|
||||
def get_boot_ip(self):
|
||||
"""Obtiene la IP del servidor Boot."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
return self.parentApp.server_ip
|
||||
elif self.parentApp.installation_type == "multinodo":
|
||||
return self.parentApp.boot_ip
|
||||
|
||||
def get_core_ip(self):
|
||||
"""Obtiene la IP del servidor Core."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
return self.parentApp.server_ip
|
||||
elif self.parentApp.installation_type == "multinodo":
|
||||
return self.parentApp.core_ip
|
||||
|
||||
def configure_fields(self):
|
||||
# Obtener la lista de oglives
|
||||
oglives = get_oglive_list()
|
||||
if not oglives:
|
||||
oglives = ["https://ognproject.evlt.uma.es/oglive/ogLive-noble-6.8.0-31-generic-amd64-r20250116.538e3fa_20250120.iso"]
|
||||
npyscreen.notify_confirm("No se pudo obtener la lista de oglives. Usando un valor por defecto.", title="Error")
|
||||
|
||||
# Campo para seleccionar un oglive
|
||||
self.fields["ogliveUrl"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.TitleSelectOne,
|
||||
name="Selecciona un OgLive:",
|
||||
values=oglives,
|
||||
scroll_exit=True,
|
||||
max_height=6,
|
||||
rely=2 # Ajustar la posición vertical
|
||||
)
|
||||
}
|
||||
|
||||
# Otros campos
|
||||
#self.fields["ip"] = {"widget": self.add(npyscreen.TitleText, name="IP del servidor Boot:", value=self.get_boot_ip(), rely=14)}
|
||||
self.add(npyscreen.FixedText, value="IP del servidor Boot:", editable=False, rely=10, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["ip"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value=self.get_boot_ip(),
|
||||
rely=11, # Línea siguiente
|
||||
relx=18,
|
||||
highlighted=True
|
||||
)
|
||||
}
|
||||
# self.fields["ogcoreUrl"] = {"widget": self.add(npyscreen.TitleText, name="URL OgCore:", value=f"https://{self.get_core_ip()}:8443", rely=18)}
|
||||
self.add(npyscreen.FixedText, value="IP del servidor Core:", editable=False, rely=12, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["ogcoreUrl"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value=f"https://{self.get_core_ip()}:8443",
|
||||
rely=13, # Línea siguiente
|
||||
relx=18,
|
||||
highlighted=True
|
||||
)
|
||||
}
|
||||
# self.fields["sambaUser"] = {"widget": self.add(npyscreen.TitleText, name="Usuario Samba:", value="opengnsys", rely=20)}
|
||||
self.add(npyscreen.FixedText, value="Usuario Samba:", editable=False, rely=14, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["sambaUser"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value="opengnsys",
|
||||
rely=15, # Línea siguiente
|
||||
relx=18,
|
||||
highlighted=True
|
||||
)
|
||||
}
|
||||
#self.fields["sambaUserPass"] = {"widget": self.add(npyscreen.TitlePassword, name="Contraseña Samba:", value="og", rely=22)}
|
||||
self.fields["sambaUserPass"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.TitlePassword,
|
||||
name="Contraseña Samba:",
|
||||
value="og",
|
||||
rely=16, # Línea siguiente
|
||||
)
|
||||
}
|
||||
#self.fields["port"] = {"widget": self.add(npyscreen.TitleText, name="Puerto Boot:", value="8082",hidden=True, rely=16)}
|
||||
self.add(npyscreen.FixedText, value="Puerto Boot:", editable=False, rely=12, relx=2, color="SAFE" , highlighted=True,hidden=True)
|
||||
self.fields["port"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value="8082",
|
||||
rely=13, # Línea siguiente
|
||||
relx=18,
|
||||
hidden=True
|
||||
)
|
||||
}
|
||||
|
||||
def on_ok(self):
|
||||
# Obtener el oglive seleccionado
|
||||
selected_oglive_index = self.fields["ogliveUrl"]["widget"].value
|
||||
if not selected_oglive_index or len(selected_oglive_index) == 0:
|
||||
npyscreen.notify_confirm("Debes seleccionar una imagen OgLive.", title="Error")
|
||||
return
|
||||
selected_oglive = self.fields["ogliveUrl"]["widget"].values[selected_oglive_index[0]]
|
||||
|
||||
# Guardar las configuraciones
|
||||
self.parentApp.configurations[self.component_name] = {
|
||||
"ogliveUrl": self.download_url + selected_oglive,
|
||||
"ip": self.fields["ip"]["widget"].value,
|
||||
"port": self.fields["port"]["widget"].value,
|
||||
"ogcoreUrl": self.fields["ogcoreUrl"]["widget"].value,
|
||||
"sambaUser": self.fields["sambaUser"]["widget"].value,
|
||||
"sambaUserPass": self.fields["sambaUserPass"]["widget"].value,
|
||||
}
|
||||
|
||||
# Continuar con el siguiente formulario
|
||||
self.parentApp.current_component_index += 1
|
||||
if self.parentApp.current_component_index < len(self.parentApp.selected_components):
|
||||
next_component = self.parentApp.selected_components[self.parentApp.current_component_index]
|
||||
self.parentApp.switchForm(next_component)
|
||||
else:
|
||||
self.parentApp.generate_debconf()
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
class OgRepositoryForm(ComponentForm):
|
||||
component_name = "ogrepository"
|
||||
|
||||
def get_repo_ip(self):
|
||||
"""Obtiene la IP del servidor Repository."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
return self.parentApp.server_ip
|
||||
elif self.parentApp.installation_type == "multinodo":
|
||||
return self.parentApp.repo_ip
|
||||
|
||||
def get_core_ip(self):
|
||||
"""Obtiene la IP del servidor Core."""
|
||||
if self.parentApp.installation_type == "mononodo":
|
||||
return self.parentApp.server_ip
|
||||
elif self.parentApp.installation_type == "multinodo":
|
||||
return self.parentApp.core_ip
|
||||
|
||||
def configure_fields(self):
|
||||
# Campo para la IP del Repositorio
|
||||
self.add(npyscreen.FixedText, value="IP del Repositorio:", editable=False, rely=2, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["ogrepoIp"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value=self.get_repo_ip(),
|
||||
rely=3, # Línea siguiente
|
||||
relx=18,
|
||||
highlighted=True
|
||||
)
|
||||
}
|
||||
|
||||
# Campo para la IP de OgCore
|
||||
self.add(npyscreen.FixedText, value="IP de OgCore:", editable=False, rely=5, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["ogcoreIp"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value=self.get_core_ip(),
|
||||
rely=6, # Línea siguiente
|
||||
relx=18,
|
||||
)
|
||||
}
|
||||
|
||||
# Campo para el Usuario Samba
|
||||
self.add(npyscreen.FixedText, value="Usuario Samba:", editable=False, rely=8, relx=2, color="SAFE" , highlighted=True)
|
||||
self.fields["sambaUser"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.Textfield,
|
||||
value="opengnsys",
|
||||
rely=9, # Línea siguiente
|
||||
relx=18 ,
|
||||
)
|
||||
}
|
||||
|
||||
# Campo para la Contraseña Samba
|
||||
self.fields["sambaUserPass"] = {
|
||||
"widget": self.add(
|
||||
npyscreen.TitlePassword,
|
||||
name="Contraseña Samba:",
|
||||
value="og",
|
||||
rely=11 # Mantener el uso de TitlePassword
|
||||
)
|
||||
}
|
||||
|
||||
class InstallationProgressForm(npyscreen.Form):
|
||||
"""Formulario para mostrar el progreso de instalación y el log en tiempo real."""
|
||||
def create(self):
|
||||
# Ajustar alturas para evitar problemas de espacio
|
||||
self.progress_box = self.add(
|
||||
npyscreen.BoxTitle,
|
||||
name="Progreso de instalación",
|
||||
max_height=6,
|
||||
rely=1,
|
||||
relx=2,
|
||||
scroll_exit=True
|
||||
)
|
||||
self.log_box = self.add(
|
||||
npyscreen.BoxTitle,
|
||||
name="Log de instalación",
|
||||
max_height=8,
|
||||
rely=8,
|
||||
relx=2,
|
||||
scroll_exit=True
|
||||
)
|
||||
|
||||
def update_progress(self, message, current=0, total=0):
|
||||
"""Actualiza el progreso de instalación en la parte superior."""
|
||||
if total > 0:
|
||||
# Crear una barra de progreso personalizada
|
||||
progress_percentage = int((current / total) * 100)
|
||||
bar_length = 30 # Longitud de la barra
|
||||
filled_length = int(bar_length * current // total)
|
||||
bar = f"[{'=' * filled_length}{' ' * (bar_length - filled_length)}] {progress_percentage}%"
|
||||
self.progress_box.values.append(bar)
|
||||
self.progress_box.values.append(message)
|
||||
self.progress_box.display()
|
||||
|
||||
def update_log(self, new_line):
|
||||
"""Actualiza el log en tiempo real en la parte inferior."""
|
||||
max_lines = 10 # Número máximo de líneas a mostrar
|
||||
self.log_box.values.append(new_line.strip()) # Agregar la nueva línea
|
||||
self.log_box.values = self.log_box.values[-max_lines:] # Mantener solo las últimas `max_lines` líneas
|
||||
self.log_box.display()
|
||||
|
||||
def install_components_with_ui(form, components, selected_tag):
|
||||
"""Instala los componentes seleccionados mostrando el progreso y el log en tiempo real."""
|
||||
log_file_path = os.path.join(LOGS_DIR, "installation.log")
|
||||
installed_packages = []
|
||||
failed_packages = []
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
with open(log_file_path, "w", buffering=1) as log_file:
|
||||
total_packages = len(components)
|
||||
def tail_log():
|
||||
try:
|
||||
with open(log_file_path, "r") as log_reader:
|
||||
log_reader.seek(0, os.SEEK_END)
|
||||
while True:
|
||||
line = log_reader.readline()
|
||||
if line:
|
||||
form.update_log(line)
|
||||
except Exception as e:
|
||||
# Mostrar error en log si ocurre
|
||||
try:
|
||||
form.update_log(f"[ERROR] {e}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
log_thread = threading.Thread(target=tail_log, daemon=True)
|
||||
log_thread.start()
|
||||
|
||||
for index, package in enumerate(components, start=1):
|
||||
form.update_progress(f"Instalando paquete {index}/{total_packages}: {package}", current=index, total=total_packages)
|
||||
install_command = f"DEBIAN_FRONTEND=noninteractive apt-get install -y {package}"
|
||||
process = subprocess.Popen(
|
||||
install_command, shell=True, text=True, stdout=log_file, stderr=log_file, bufsize=1
|
||||
)
|
||||
process.wait()
|
||||
log_file.flush()
|
||||
if process.returncode != 0:
|
||||
error_message = f"Error al instalar el paquete {package}. Consulta el archivo de registro: {log_file_path}"
|
||||
form.update_progress(error_message)
|
||||
failed_packages.append(package)
|
||||
else:
|
||||
form.update_progress(f"Paquete {package} instalado correctamente.")
|
||||
installed_packages.append(package)
|
||||
if package == "ogboot":
|
||||
form.update_progress("Instalando paquete adicional: ogclient")
|
||||
install_command = "DEBIAN_FRONTEND=noninteractive apt-get install -y ogclient"
|
||||
process = subprocess.Popen(
|
||||
install_command, shell=True, text=True, stdout=log_file, stderr=log_file, bufsize=1
|
||||
)
|
||||
process.wait()
|
||||
log_file.flush()
|
||||
if process.returncode != 0:
|
||||
error_message = f"Error al instalar el paquete ogclient. Consulta el archivo de registro: {log_file_path}"
|
||||
form.update_progress(error_message)
|
||||
failed_packages.append("ogclient")
|
||||
else:
|
||||
form.update_progress("Paquete ogclient instalado correctamente.")
|
||||
installed_packages.append("ogclient")
|
||||
except Exception as e:
|
||||
try:
|
||||
form.update_progress(f"Error durante la instalación: {e}")
|
||||
except Exception:
|
||||
print(f"[ERROR] {e}")
|
||||
failed_packages.append("Error general durante la instalación")
|
||||
|
||||
end_time = time.time()
|
||||
duration = end_time - start_time
|
||||
summary = "\n--- Resumen de la instalación ---\n"
|
||||
summary += f"Tiempo total de instalación: {duration:.2f} segundos\n"
|
||||
summary += f"Paquetes instalados correctamente: {len(installed_packages)}\n"
|
||||
for pkg in installed_packages:
|
||||
summary += f" - {pkg}\n"
|
||||
if failed_packages:
|
||||
summary += f"\nPaquetes que fallaron: {len(failed_packages)}\n"
|
||||
for pkg in failed_packages:
|
||||
summary += f" - {pkg}\n"
|
||||
else:
|
||||
summary += "\nTodos los paquetes se instalaron correctamente.\n"
|
||||
summary += f"\nConsulta el archivo de registro para más detalles: {log_file_path}"
|
||||
|
||||
# Mostrar el resumen y salir del formulario
|
||||
try:
|
||||
npyscreen.notify_confirm(summary, title="Resumen de la instalación", wide=True)
|
||||
except Exception as e:
|
||||
print(summary)
|
||||
print(f"[ERROR] {e}")
|
||||
|
||||
# Forzar la salida de la aplicación después del resumen
|
||||
import sys
|
||||
sys.exit(0)
|
||||
|
||||
class MyApp(npyscreen.NPSAppManaged):
|
||||
def onStart(self):
|
||||
# Inicializar variables globales
|
||||
self.installation_type = None # Tipo de instalación seleccionado (mononodo o multinodo)
|
||||
self.server_ip = None # IP del servidor para mononodo
|
||||
self.repo_ip = None # IP del servidor Repository
|
||||
self.dhcp_ip = None # IP del servidor DHCP
|
||||
self.core_ip = None # IP del servidor Core
|
||||
self.boot_ip = None # IP del servidor Bootdpkg
|
||||
self.selected_components = [] # Componentes seleccionados
|
||||
self.selected_tag = None # Versión seleccionada
|
||||
self.configurations = {} # Configuraciones de los componentes
|
||||
|
||||
# Registrar los formularios
|
||||
self.addForm("INSTALLATION_TYPE", InstallationTypeForm)
|
||||
self.addForm("MONONODO_CONFIG", MononodoConfigForm)
|
||||
self.addForm("MULTINODO_CONFIG", MultinodoConfigForm)
|
||||
self.addForm("MAIN", ComponentSelectionForm)
|
||||
self.addForm("ogcore", OgCoreForm)
|
||||
self.addForm("oggui", OgGuiForm)
|
||||
self.addForm("ogdhcp", OgDhcpForm)
|
||||
self.addForm("ogboot", OgBootForm)
|
||||
self.addForm("ogrepository", OgRepositoryForm)
|
||||
self.addForm("INSTALLATION_PROGRESS", InstallationProgressForm)
|
||||
|
||||
# Configurar el formulario inicial
|
||||
self.setNextForm("INSTALLATION_TYPE")
|
||||
|
||||
def generate_debconf(self):
|
||||
# Comprobar si la clave pública ya existe
|
||||
logging.debug("Entrando en generate_debconf")
|
||||
key_path = "/etc/apt/trusted.gpg.d/opengnsys.gpg"
|
||||
if os.path.exists(key_path):
|
||||
# Silenciar este mensaje
|
||||
pass
|
||||
else:
|
||||
# Añadir la clave pública
|
||||
try:
|
||||
logging.debug("Añadiendo la clave pública")
|
||||
subprocess.run(
|
||||
'curl -k -L https://ognproject.evlt.uma.es/debian-opengnsys/public.key | gpg --dearmour -o /etc/apt/trusted.gpg.d/opengnsys.gpg',
|
||||
shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True
|
||||
)
|
||||
except subprocess.CalledProcessError:
|
||||
logging.error("Error al añadir la clave pública")
|
||||
|
||||
return
|
||||
|
||||
# Añadir el repositorio
|
||||
try:
|
||||
logging.debug("Añadiendo el repositorio")
|
||||
selected_tag = self.selected_tag # Obtener el tag seleccionado
|
||||
# Determinar el valor de repo_line según el argumento recibido
|
||||
if len(sys.argv) > 1 and sys.argv[1].lower() == "devel":
|
||||
repo_line = f'deb http://ognproject.evlt.uma.es/debian-opengnsys/opengnsys-devel/{selected_tag} noble main'
|
||||
elif len(sys.argv) > 1 and sys.argv[1].lower() == "nightly":
|
||||
repo_line = f'deb http://ognproject.evlt.uma.es/debian-opengnsys/nightly/main noble main'
|
||||
else:
|
||||
repo_line = f'deb http://ognproject.evlt.uma.es/debian-opengnsys/opengnsys/{selected_tag} noble main'
|
||||
with open('/etc/apt/sources.list.d/opengnsys.list', 'w') as repo_file:
|
||||
repo_file.write(repo_line + '\n')
|
||||
except Exception:
|
||||
logging.error("Error al añadir el repositorio")
|
||||
print("Error al añadir el repositorio")
|
||||
return
|
||||
|
||||
# Crear el archivo de versión instalada
|
||||
try:
|
||||
logging.debug("Creando el archivo de versión instalada")
|
||||
os.makedirs("/opt/opengnsys", exist_ok=True)
|
||||
with open("/opt/opengnsys/release", "w") as release_file:
|
||||
release_file.write(f"Versión instalada: {selected_tag}\n")
|
||||
except Exception as e:
|
||||
print(f"Error al crear el archivo de versión: {e}")
|
||||
|
||||
# Actualizar los repositorios
|
||||
try:
|
||||
logging.debug("Actualizando los repositorios")
|
||||
subprocess.run('apt-get update', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||
except subprocess.CalledProcessError:
|
||||
# Silenciar errores
|
||||
return
|
||||
|
||||
# Generar configuraciones para debconf
|
||||
output_file = os.path.join(CONFIGS_DIR, "configurations.txt")
|
||||
try:
|
||||
with open(output_file, "w") as f:
|
||||
f.write("\n--- Configuraciones para debconf-set-selections ---\n")
|
||||
for component, config in self.configurations.items():
|
||||
for key, value in config.items():
|
||||
field_type = "password" if "Pass" in key else "string"
|
||||
line = f'echo "{component} opengnsys/{component}_{key} {field_type} {value}" | debconf-set-selections\n'
|
||||
f.write(line)
|
||||
|
||||
# Ejecutar la línea directamente y redirigir la salida a /dev/null
|
||||
subprocess.run(
|
||||
line, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
||||
)
|
||||
logging.debug(f"Configuraciones guardadas en: {output_file}")
|
||||
except Exception:
|
||||
# Silenciar errores
|
||||
logging.error(f"Error al guardar configuraciones en {output_file}")
|
||||
print(f"Error al guardar configuraciones en {output_file}")
|
||||
|
||||
# Silenciar el mensaje de configuraciones guardadas
|
||||
# print(f"\nConfiguraciones guardadas en: {output_file}")
|
||||
|
||||
# Llamar al formulario de progreso
|
||||
form = self.getForm("INSTALLATION_PROGRESS")
|
||||
self.switchForm("INSTALLATION_PROGRESS")
|
||||
install_components_with_ui(form, self.selected_components, self.selected_tag)
|
||||
|
||||
def check_terminal_size(min_width=80, min_height=24):
|
||||
"""Verifica si el tamaño del terminal es suficiente."""
|
||||
terminal_size = shutil.get_terminal_size()
|
||||
if terminal_size.columns < min_width or terminal_size.lines < min_height:
|
||||
print(f"[ERROR] El tamaño del terminal es demasiado pequeño. Se requiere al menos {min_width}x{min_height}.")
|
||||
exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
# Verificar el tamaño del terminal antes de iniciar la aplicación
|
||||
check_terminal_size()
|
||||
|
||||
logging.debug("Ejecutando la aplicación principal")
|
||||
MyApp().run()
|
||||
except RuntimeError as e:
|
||||
print(f"[ERROR] {e}")
|
||||
logging.error(f"[ERROR] {e}")
|
||||
exit(1) # Salir con un código de error
|
||||
except KeyboardInterrupt:
|
||||
logging.warning("El programa fue interrumpido por el usuario (Ctrl-C)")
|
||||
except Exception as e:
|
||||
logging.error(f"[ERROR] Ocurrió un error inesperado: {e}")
|
||||
print(f"[ERROR] {e}")
|
||||
finally:
|
||||
# Asegurarse de que todos los mensajes de log se escriban en el archivo
|
||||
logging.debug("Finalizando el programa y cerrando el log")
|
||||
logging.shutdown()
|
||||
# Restaurar el terminal al estado normal
|
||||
npyscreen.wrapper_basic(lambda stdscr: None)
|
|
@ -1,311 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import subprocess
|
||||
import requests
|
||||
import sys
|
||||
import npyscreen
|
||||
import re
|
||||
import os
|
||||
|
||||
# Configuración general
|
||||
REPO_BASE_URL = "http://ognproject.evlt.uma.es/debian-opengnsys/opengnsys-devel"
|
||||
RELEASES_URL = "https://ognproject.evlt.uma.es/debian-opengnsys/versions-dev.json"
|
||||
APT_LIST_PATH = "/etc/apt/sources.list.d/opengnsys.list"
|
||||
PACKAGES = ["ogrepository", "ogcore", "oggui", "ogclient", "ogboot", "ogdhcp"]
|
||||
RELEASE_FILE = "/opt/opengnsys/release"
|
||||
|
||||
# === Sección npyscreen ===
|
||||
|
||||
class ServerURLForm(npyscreen.Form):
|
||||
def create(self):
|
||||
self.server_url = self.add(npyscreen.TitleText, name="Servidor de validación (URL completa):", value="http://localhost:5000/validar")
|
||||
|
||||
def afterEditing(self):
|
||||
self.parentApp.server_url = self.server_url.value
|
||||
self.parentApp.setNextForm("RELEASE")
|
||||
|
||||
class ReleaseSelectorForm(npyscreen.ActionForm):
|
||||
def create(self):
|
||||
self.releases = self.parentApp.releases
|
||||
self.listbox = self.add(npyscreen.TitleSelectOne,
|
||||
name="Releases disponibles",
|
||||
values=self.releases,
|
||||
scroll_exit=True,
|
||||
max_height=len(self.releases)+4)
|
||||
|
||||
def on_ok(self):
|
||||
selected_index = self.listbox.value[0] if self.listbox.value else None
|
||||
if selected_index is None:
|
||||
npyscreen.notify_confirm("Debes seleccionar una release antes de continuar.", title="Error")
|
||||
else:
|
||||
self.parentApp.selected = self.releases[selected_index]
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
def on_cancel(self):
|
||||
npyscreen.notify_confirm("Operación cancelada. Saliendo del formulario.", title="Cancelado")
|
||||
self.parentApp.setNextForm(None)
|
||||
|
||||
class ReleaseSelectorApp(npyscreen.NPSAppManaged):
|
||||
def __init__(self, releases):
|
||||
self.releases = releases
|
||||
self.selected = None
|
||||
self.server_url = None
|
||||
super().__init__()
|
||||
|
||||
def onStart(self):
|
||||
self.addForm("MAIN", ServerURLForm, name="Configuración inicial")
|
||||
self.addForm("RELEASE", ReleaseSelectorForm, name="Selecciona una release", releases=self.releases)
|
||||
|
||||
def choose_release_and_server(releases):
|
||||
app = ReleaseSelectorApp(releases)
|
||||
app.run()
|
||||
return app.selected, app.server_url
|
||||
|
||||
# === Funciones principales ===
|
||||
|
||||
def backup_file(filepath):
|
||||
"""Crea una copia de seguridad del archivo especificado."""
|
||||
backup_path = f"{filepath}.bak"
|
||||
if os.path.exists(filepath):
|
||||
try:
|
||||
os.replace(filepath, backup_path)
|
||||
print(f"[INFO] Copia de seguridad creada: {backup_path}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] No se pudo crear la copia de seguridad de {filepath}: {e}")
|
||||
return backup_path
|
||||
|
||||
def restore_file(backup_path, original_path):
|
||||
"""Restaura el archivo desde su copia de seguridad."""
|
||||
if os.path.exists(backup_path):
|
||||
try:
|
||||
os.replace(backup_path, original_path)
|
||||
print(f"[INFO] Archivo restaurado: {original_path}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] No se pudo restaurar el archivo {original_path}: {e}")
|
||||
|
||||
def get_installed_packages():
|
||||
installed = []
|
||||
for pkg in PACKAGES:
|
||||
try:
|
||||
subprocess.run(
|
||||
["dpkg-query", "-W", pkg],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
installed.append(pkg)
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
return installed
|
||||
|
||||
def get_installed_release():
|
||||
try:
|
||||
with open(RELEASE_FILE, "r") as release_file:
|
||||
line = release_file.readline().strip()
|
||||
match = re.search(r".*:\s*(.+)", line)
|
||||
if match:
|
||||
return match.group(1).strip()
|
||||
except FileNotFoundError:
|
||||
print("El archivo de release no existe.")
|
||||
except Exception as e:
|
||||
print(f"Error al leer el archivo de release: {e}")
|
||||
return None
|
||||
|
||||
def fetch_available_releases():
|
||||
try:
|
||||
response = requests.get(RELEASES_URL)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data.get("versions", [])
|
||||
except requests.RequestException as e:
|
||||
print(f"[ERROR] No se pudo obtener la lista de releases: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
def update_repo_file(selected_release):
|
||||
backup_path = backup_file(APT_LIST_PATH)
|
||||
line = f"deb {REPO_BASE_URL}/{selected_release} noble main\n"
|
||||
print(f"[INFO] Escribiendo nueva línea en {APT_LIST_PATH}:\n{line.strip()}")
|
||||
try:
|
||||
with open(APT_LIST_PATH, "w") as f:
|
||||
f.write(line)
|
||||
except PermissionError:
|
||||
print("[ERROR] No tienes permisos para escribir en el archivo del repositorio. Ejecuta el script como root.")
|
||||
restore_file(backup_path, APT_LIST_PATH)
|
||||
sys.exit(1)
|
||||
|
||||
# Ejecutar apt update para actualizar la información del repositorio
|
||||
try:
|
||||
print("[INFO] Actualizando la información del repositorio con 'apt update'...")
|
||||
subprocess.run(["sudo", "apt", "update"], check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"[ERROR] Error al ejecutar 'apt update': {e}")
|
||||
restore_file(backup_path, APT_LIST_PATH)
|
||||
sys.exit(1)
|
||||
|
||||
def check_compatibility(server_url, installed_release, selected_release):
|
||||
payload = {
|
||||
"installed_release": installed_release,
|
||||
"target_release": selected_release
|
||||
}
|
||||
try:
|
||||
response = requests.post(server_url, json=payload, timeout=5)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
return result.get("compatible", False), result.get("message", "")
|
||||
except requests.RequestException as e:
|
||||
print(f"[ERROR] No se pudo contactar con el servidor de validación: {e}")
|
||||
return False, str(e)
|
||||
|
||||
def summarize_updates(installed_packages, selected_release):
|
||||
"""Genera un resumen de los paquetes que se van a actualizar y los que no."""
|
||||
to_update = []
|
||||
up_to_date = []
|
||||
|
||||
for pkg in installed_packages:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["apt-cache", "policy", pkg],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
check=True,
|
||||
env={"LANG": "C"} # Forzar el idioma a inglés
|
||||
)
|
||||
installed = None
|
||||
candidate = None
|
||||
for line in result.stdout.splitlines():
|
||||
if "Installed:" in line: # Siempre estará en inglés
|
||||
installed = line.split(":", 1)[1].strip()
|
||||
elif "Candidate:" in line: # Siempre estará en inglés
|
||||
candidate = line.split(":", 1)[1].strip()
|
||||
|
||||
if not installed or candidate == "(none)":
|
||||
to_update.append(f"{pkg} (no instalado o sin versión candidata)")
|
||||
elif installed != candidate:
|
||||
to_update.append(f"{pkg} ({installed} → {candidate})")
|
||||
else:
|
||||
up_to_date.append(f"{pkg} ({installed})")
|
||||
|
||||
except subprocess.CalledProcessError:
|
||||
to_update.append(f"{pkg} (error obteniendo versión)")
|
||||
|
||||
summary = "\n--- Resumen de actualización ---\n"
|
||||
summary += f"Release objetivo: {selected_release}\n\n"
|
||||
summary += "Paquetes que se actualizarán:\n"
|
||||
summary += "\n".join(f" - {line}" for line in to_update) if to_update else " - Ninguno\n"
|
||||
summary += "\nPaquetes que ya están actualizados:\n"
|
||||
summary += "\n".join(f" - {line}" for line in up_to_date) if up_to_date else " - Ninguno\n"
|
||||
summary += "\n--------------------------------"
|
||||
|
||||
# Mostrar el resumen en una ventana emergente
|
||||
npyscreen.notify_confirm(summary, title="Resumen de actualización", wide=True)
|
||||
|
||||
if not to_update:
|
||||
npyscreen.notify_confirm("[INFO] Todos los paquetes están actualizados. No es necesario continuar.", title="Información")
|
||||
sys.exit(0)
|
||||
|
||||
if not npyscreen.notify_yes_no("¿Deseas continuar con la actualización?", title="Confirmación"):
|
||||
npyscreen.notify_confirm("[INFO] Actualización cancelada por el usuario.", title="Cancelado")
|
||||
restore_file(f"{APT_LIST_PATH}.bak", APT_LIST_PATH)
|
||||
restore_file(f"{RELEASE_FILE}.bak", RELEASE_FILE)
|
||||
sys.exit(0)
|
||||
|
||||
return [line.split()[0] for line in to_update]
|
||||
|
||||
def show_final_versions(packages):
|
||||
print("\n✅ Resumen final de versiones instaladas:")
|
||||
for pkg in packages:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["dpkg-query", "-W", "-f=${Version}", pkg],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True
|
||||
)
|
||||
version = result.stdout.strip()
|
||||
print(f" - {pkg}: {version}")
|
||||
except subprocess.CalledProcessError:
|
||||
print(f" - {pkg}: no instalado")
|
||||
|
||||
def update_and_install(packages_to_update, selected_release):
|
||||
backup_release = backup_file(RELEASE_FILE)
|
||||
try:
|
||||
subprocess.run(["sudo", "apt", "update"], check=True)
|
||||
subprocess.run(["sudo", "apt", "install", "-y"] + packages_to_update, check=True)
|
||||
print("[INFO] Paquetes actualizados correctamente.")
|
||||
|
||||
# Actualizar el archivo de release con la versión seleccionada
|
||||
try:
|
||||
os.makedirs(os.path.dirname(RELEASE_FILE), exist_ok=True)
|
||||
with open(RELEASE_FILE, "w") as release_file:
|
||||
release_file.write(f"Versión instalada: {selected_release}\n")
|
||||
print(f"[INFO] Archivo de release actualizado: {selected_release}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] No se pudo actualizar el archivo de release: {e}")
|
||||
|
||||
show_final_versions(packages_to_update)
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"[ERROR] Error al instalar paquetes: {e}")
|
||||
restore_file(backup_release, RELEASE_FILE)
|
||||
sys.exit(1)
|
||||
|
||||
# === Entrada principal ===
|
||||
|
||||
def main():
|
||||
print("[INFO] Iniciando actualización de paquetes de OpenGnSys...")
|
||||
installed_release = get_installed_release()
|
||||
if installed_release:
|
||||
print(f"[INFO] Versión instalada: {installed_release}")
|
||||
else:
|
||||
print("[WARN] No se encontró la versión instalada.")
|
||||
sys.exit(1)
|
||||
|
||||
installed = get_installed_packages()
|
||||
if not installed:
|
||||
print("[ERROR] No se detectaron paquetes OpenGnSys instalados.")
|
||||
sys.exit(1)
|
||||
|
||||
releases = fetch_available_releases()
|
||||
selected, server_url = choose_release_and_server(releases)
|
||||
|
||||
if not selected or not server_url:
|
||||
print("[WARN] No se seleccionó release o URL del servidor. Restaurando archivos.")
|
||||
restore_file(f"{APT_LIST_PATH}.bak", APT_LIST_PATH)
|
||||
restore_file(f"{RELEASE_FILE}.bak", RELEASE_FILE)
|
||||
sys.exit(0)
|
||||
|
||||
print(f"[INFO] Validando compatibilidad con {server_url}...")
|
||||
compatible, message = check_compatibility(server_url, installed_release, selected)
|
||||
|
||||
if not compatible:
|
||||
print(f"[ERROR] El servidor indica que la actualización no es compatible: {message}")
|
||||
restore_file(f"{APT_LIST_PATH}.bak", APT_LIST_PATH)
|
||||
restore_file(f"{RELEASE_FILE}.bak", RELEASE_FILE)
|
||||
sys.exit(1)
|
||||
else:
|
||||
print(f"[INFO] Compatibilidad validada: {message}")
|
||||
|
||||
try:
|
||||
update_repo_file(selected)
|
||||
to_update = summarize_updates(installed, selected)
|
||||
update_and_install(to_update, selected)
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Error durante la actualización: {e}")
|
||||
restore_file(f"{APT_LIST_PATH}.bak", APT_LIST_PATH)
|
||||
restore_file(f"{RELEASE_FILE}.bak", RELEASE_FILE)
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except SystemExit as e:
|
||||
# Manejar la excepción SystemExit para evitar interrupciones
|
||||
if e.code != 0:
|
||||
print(f"[INFO] El script terminó con código de salida: {e.code}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Ocurrió un error inesperado: {e}")
|
||||
finally:
|
||||
# Restaurar el terminal al estado normal
|
||||
npyscreen.wrapper_basic(lambda stdscr: None)
|
|
@ -1,75 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Setup installer environment
|
||||
|
||||
|
||||
BRANCH=${BRANCH:-main}
|
||||
GIT_SSL_NO_VERIFY=1
|
||||
GIT_REPO="https://ognproject.evlt.uma.es/gitea/api/v1/repos/opengnsys/oginstaller/archive/$BRANCH.zip"
|
||||
export GIT_SSL_NO_VERIFY
|
||||
DEVEL=$1
|
||||
|
||||
if [ "$DEVEL" == "devel" ]; then
|
||||
INSTALL_DEVEL=1
|
||||
elif [ "$DEVEL" == "nightly" ]; then
|
||||
INSTALL_NIGHTLY=1
|
||||
else
|
||||
INSTALL_STABLE=1
|
||||
fi
|
||||
|
||||
install_packages() {
|
||||
apt-get update
|
||||
apt-get install -y curl jq unzip python3 python3-git
|
||||
}
|
||||
|
||||
|
||||
create_python_venv() {
|
||||
apt-get install -y python3-venv
|
||||
python3 -m venv /tmp/oginstall/venv
|
||||
source /tmp/oginstall/venv/bin/activate
|
||||
pip install -r /tmp/oginstall/requirements.txt
|
||||
}
|
||||
|
||||
download_installer() {
|
||||
|
||||
rm -f /tmp/oginstaller.zip
|
||||
rm -rf /tmp/oginstaller-$BRANCH
|
||||
rm -rf /tmp/oginstaller
|
||||
|
||||
curl -q -k $GIT_REPO -H 'accept: application/json' -o /tmp/oginstaller.zip
|
||||
unzip /tmp/oginstaller.zip -d /tmp
|
||||
mv /tmp/oginstaller /tmp/oginstaller-$BRANCH
|
||||
}
|
||||
|
||||
extract_installer() {
|
||||
rm -rf /tmp/oginstall
|
||||
mkdir -p /tmp/oginstall
|
||||
cp -r /tmp/oginstaller-$BRANCH/non_graf_installer/python-installer/* /tmp/oginstall/
|
||||
chmod 755 /tmp/oginstall/*.py
|
||||
}
|
||||
|
||||
create_questions() {
|
||||
echo "Creating questions..."
|
||||
if [ $INSTALL_DEVEL ] ; then
|
||||
python3 /tmp/oginstall/oginstaller-v3.py devel
|
||||
elif [ $INSTALL_NIGHTLY ] ; then
|
||||
python3 /tmp/oginstall/oginstaller-v3.py nightly
|
||||
else
|
||||
python3 /tmp/oginstall/oginstaller-v3.py
|
||||
fi
|
||||
deactivate
|
||||
}
|
||||
|
||||
clean_tmp() {
|
||||
rm -rf /tmp/oginstall
|
||||
rm -rf /tmp/oginstaller-$BRANCH
|
||||
rm -f /tmp/oginstaller.zip
|
||||
}
|
||||
|
||||
|
||||
install_packages
|
||||
download_installer
|
||||
extract_installer
|
||||
create_python_venv
|
||||
create_questions
|
||||
clean_tmp
|
|
@ -1,214 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Detect installed components.
|
||||
|
||||
|
||||
INSTALLER_BRANCH=${INSTALLER_BRANCH:-main}
|
||||
OPENGNSYS_BASE=/opt/opengnsys
|
||||
OPENGNSYS_COMPONENTS=(ogCore ogGui ogDhcp ogBoot ogRepository)
|
||||
GIT_SSL_NO_VERIFY=1
|
||||
INSTALLED_COMPONENTS=()
|
||||
|
||||
GIT_REPO="https://ognproject.evlt.uma.es/gitea/api/v1/repos/opengnsys/oginstaller/archive/$INSTALLER_BRANCH.zip"
|
||||
|
||||
export GIT_SSL_NO_VERIFY
|
||||
INSTALLED_COMPONENTS=()
|
||||
|
||||
check_os(){
|
||||
if [ -f /etc/os-release ]; then
|
||||
. /etc/os-release
|
||||
# Just support Ubuntu 24.04 for now
|
||||
if [ $ID == "ubuntu" ] && [ $VERSION_ID == "24.04" ]; then
|
||||
echo "OS supported."
|
||||
else
|
||||
echo "OS not supported."
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "OS not supported."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
detect_installed_components() {
|
||||
local OGNODE=0
|
||||
for component in "${OPENGNSYS_COMPONENTS[@]}"; do
|
||||
if [ -f "${OPENGNSYS_BASE}/${component}/installer/config.json" ]; then
|
||||
echo "Component $component is installed."
|
||||
INSTALLED_COMPONENTS+=($component)
|
||||
OGNODE=1
|
||||
else
|
||||
echo "Component $component is not installed."
|
||||
fi
|
||||
done
|
||||
if [ $OGNODE -eq 0 ]; then
|
||||
echo "No OpenGnsys components installed."
|
||||
else
|
||||
echo "Installed components:" "${INSTALLED_COMPONENTS[@]}"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
# Assume taht all components are at the same release version, get the first installed compoenent and return its version
|
||||
get_og_installed_version() {
|
||||
local component=$1
|
||||
local version=$(jq -r '.release' ${OPENGNSYS_BASE}/${component}/installer/config.json)
|
||||
echo $version
|
||||
}
|
||||
|
||||
start_stop_component() {
|
||||
local component=$1
|
||||
local action=$2
|
||||
case $component in
|
||||
ogCore)
|
||||
handle_ogcore $action
|
||||
;;
|
||||
ogGui)
|
||||
handle_oggui $action
|
||||
;;
|
||||
ogDhcp)
|
||||
handle_ogdhcp $action
|
||||
;;
|
||||
ogBoot)
|
||||
handle_ogboot $action
|
||||
;;
|
||||
ogRepository)
|
||||
handle_ogrepository $action
|
||||
;;
|
||||
*)
|
||||
echo "Component $component not found."
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
|
||||
stop_installed_services() {
|
||||
echo "Stopping services..."
|
||||
for component in "${INSTALLED_COMPONENTS[@]}"; do
|
||||
echo "Stopping component $component..."
|
||||
start_stop_component $component stop
|
||||
done
|
||||
}
|
||||
|
||||
start_installed_services() {
|
||||
echo "Starting services..."
|
||||
for component in "${INSTALLED_COMPONENTS[@]}"; do
|
||||
echo "Starting component $component..."
|
||||
start_stop_component $component start
|
||||
done
|
||||
}
|
||||
|
||||
handle_ogboot() {
|
||||
case $1 in
|
||||
stop)
|
||||
echo "Stopping ogBoot..."
|
||||
systemctl stop nginx
|
||||
systemctl stop tftpd-hpa
|
||||
systemctl stop smbd
|
||||
systemctl stop nmbd
|
||||
;;
|
||||
start)
|
||||
echo "Starting ogBoot..."
|
||||
systemctl start nginx
|
||||
systemctl start tftpd-hpa
|
||||
systemctl start smbd
|
||||
systemctl start nmbd
|
||||
;;
|
||||
*)
|
||||
echo "Invalid action."
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
handle_ogdhcp() {
|
||||
case $1 in
|
||||
stop)
|
||||
echo "Stopping ogDhcp..."
|
||||
systemctl stop kea-dhcp4-server
|
||||
systemctl stop kea-ctrl-agent
|
||||
;;
|
||||
start)
|
||||
echo "Starting ogDhcp..."
|
||||
systemctl start kea-dhcp4-server
|
||||
systemctl start kea-ctrl-agent
|
||||
;;
|
||||
*)
|
||||
echo "Invalid action."
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
handle_ogrepository() {
|
||||
case $1 in
|
||||
stop)
|
||||
echo "Stopping ogRepository..."
|
||||
systemctl stop smbd
|
||||
systemctl stop nmbd
|
||||
systemctl stop ogrepo-api
|
||||
;;
|
||||
start)
|
||||
echo "Starting ogRepository..."
|
||||
systemctl start smbd
|
||||
systemctl start nmbd
|
||||
systemctl start ogrepo-api
|
||||
;;
|
||||
*)
|
||||
echo "Invalid action."
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
handle_ogcore() {
|
||||
case $1 in
|
||||
stop)
|
||||
echo "Stopping ogCore..."
|
||||
systemctl stop ogcore
|
||||
;;
|
||||
start)
|
||||
echo "Starting ogCore..."
|
||||
systemctl start ogcore
|
||||
;;
|
||||
*)
|
||||
echo "Invalid action."
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
handle_oggui() {
|
||||
case $1 in
|
||||
stop)
|
||||
echo "Stopping ogGui..."
|
||||
systemctl stop oggui-app
|
||||
;;
|
||||
start)
|
||||
echo "Starting ogGui..."
|
||||
systemctl start oggui-app
|
||||
;;
|
||||
*)
|
||||
echo "Invalid action."
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
|
||||
update_installed_components() {
|
||||
local version=$1
|
||||
echo "Updating components to version $version..."
|
||||
for component in "${INSTALLED_COMPONENTS[@]}"; do
|
||||
echo "Updating component $component..."
|
||||
update_component $component $version
|
||||
done
|
||||
}
|
||||
|
||||
|
||||
#### Main
|
||||
|
||||
check_os
|
||||
detect_installed_components
|
||||
installed_version=$(get_og_installed_version "${INSTALLED_COMPONENTS[0]}")
|
||||
select_version_to_update
|
||||
stop_installed_services
|
||||
update_installed_components $installed_version
|
||||
start_installed_services
|
||||
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
#!/bin/bash
|
||||
|
||||
|
||||
CONFIGS_DIR=/tmp/opengnsys-installer-configs
|
||||
rm -rf $CONFIGS_DIR
|
||||
mkdir -p $CONFIGS_DIR
|
||||
|
||||
# Paso 1: Seleccionar los componentes
|
||||
components=$(yad --list --title="Seleccionar componentes" \
|
||||
--text="Selecciona los componentes que deseas configurar:" \
|
||||
--checklist --multiple \
|
||||
--column="Seleccionar" --column="Componente" \
|
||||
FALSE "ogCore" \
|
||||
FALSE "ogGui" \
|
||||
FALSE "ogDhcp" \
|
||||
FALSE "ogBoot" \
|
||||
--width=400 --height=300 --center)
|
||||
|
||||
# Verificar si el usuario seleccionó algún componente
|
||||
if [[ -z "$components" ]]; then
|
||||
yad --info --text="No seleccionaste ningún componente. Saliendo..." --center
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for component in $components; do
|
||||
selected_component=$(echo "$component" | cut -d '|' -f 2)
|
||||
# Pedir la configuración específica para cada componente seleccionado
|
||||
|
||||
|
||||
# Dividir la configuración en IP y ruta del fichero
|
||||
config_file="config_${selected_component}.json"
|
||||
case $selected_component in
|
||||
"ogCore")
|
||||
config=$(yad --form --title="Configuración para $selected_component" \
|
||||
--field="Usuario administrador":TEXT \
|
||||
--field="Contraseña":H \
|
||||
--field="Tag del contenedor":TEXT \
|
||||
"ogadmin" "" "latest" \
|
||||
--width=400 --height=200 --center)
|
||||
user=$(echo "$config" | cut -d '|' -f 1)
|
||||
password=$(echo "$config" | cut -d '|' -f 2)
|
||||
container_tag=$(echo "$config" | cut -d '|' -f 3)
|
||||
echo "{\"username\": \"$user\", \"password\": \"$password\", \"container_version\": \"$container_tag\" }" > $CONFIGS_DIR/"$config_file"
|
||||
;;
|
||||
"ogGui")
|
||||
config=$(yad --form --title="Configuración para $selected_component" \
|
||||
--field="IP del servidor de ogCore" \
|
||||
--field="Tag del contenedor":TEXT \
|
||||
--width=400 --height=200 --center)
|
||||
ogcore_ip=$(echo "$config" | cut -d '|' -f 1)
|
||||
container_version=$(echo "$config" | cut -d '|' -f 2)
|
||||
echo "{\"ogcore_ip\": \"$ogcore_ip\" , \"container_version\": \"$container_version\" }" > $CONFIGS_DIR/"$config_file"
|
||||
;;
|
||||
"ogDhcp")
|
||||
config=$(yad --form --title="Configuración para $selected_component" \
|
||||
--field="Configuración IP servidor de Boot" \
|
||||
--field="Interfaces Boot" \
|
||||
--width=400 --height=200 --center)
|
||||
ogbootIP=$(echo "$config" | cut -d '|' -f 1)
|
||||
interfaces=$(echo "$config" | cut -d '|' -f 2)
|
||||
json_array_interfaces=$(echo "$interfaces" | jq -R 'split(",")')
|
||||
echo "{\"ogbootIP\": \"$ogbootIP\", \"interfaces\": \"$json_array_interfaces\"}" > $CONFIGS_DIR/"$config_file"
|
||||
;;
|
||||
"ogBoot")
|
||||
config=$(yad --form --title="Configuración para $selected_component" \
|
||||
--field="ogCore Ip Server" \
|
||||
--field="ogCore Server" \
|
||||
--field="ogCore Dir" \
|
||||
--field="ogBoot GitRepo" \
|
||||
--field="ogBoot Samba User" \
|
||||
--field="ogBoot Samba Pass" \
|
||||
--width=400 --height=200 --center)
|
||||
ogcore_ip=$(echo "$config" | cut -d '|' -f 1)
|
||||
ogcore_server=$(echo "$config" | cut -d '|' -f 2)
|
||||
ogcore_dir=$(echo "$config" | cut -d '|' -f 3)
|
||||
ogboot_gitrepo=$(echo "$config" | cut -d '|' -f 4)
|
||||
ogboot_samba_user=$(echo "$config" | cut -d '|' -f 5)
|
||||
ogboot_samba_pass=$(echo "$config" | cut -d '|' -f 6)
|
||||
echo "{\"ogcore_ip\": \"$ogcore_ip\", \"ogcore_server\": \"$ogcore_server\", \"ogcore_dir\": \"$ogcore_dir\", \"ogboot_gitrepo\": \"$ogboot_gitrepo\", \"ogboot_samba_user\": \"$ogboot_samba_user\", \"ogboot_samba_pass\": \"$ogboot_samba_pass\"}" > $CONFIGS_DIR/"$config_file"
|
||||
;;
|
||||
esac
|
||||
|
||||
# Verificar si los campos no están vacíos
|
||||
# if [[ -z "$server_ip" || -z "$config_path" ]]; then
|
||||
# yad --error --text="Debes proporcionar la IP del servidor y la ruta del fichero para $selected_component." --center
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
# Guardar la configuración en un archivo (cada componente tiene su archivo JSON)
|
||||
config_file="./${selected_component}_config.json"
|
||||
echo "{\"server_ip\": \"$server_ip\", \"config_path\": \"$config_path\"}" > "$config_file"
|
||||
|
||||
# Mostrar un mensaje de éxito
|
||||
yad --info --text="Configuración guardada en $config_file para $selected_component." --center
|
||||
|
||||
done
|
||||
|
||||
|
||||
# # Una vez se ha configurado todo, se puede proceder a la instalación de los componentes
|
||||
# # Ejecutar la instalación con calamares y enviar el log a un archivo
|
||||
|
||||
# #calamares > installer.log 2>&1 & disown
|
||||
sudo calamares > installer.log 2>&1
|
|
@ -143,7 +143,7 @@ class OgGuiForm(ComponentForm):
|
|||
|
||||
def configure_fields(self):
|
||||
self.fields["ogcore_ip"] = {"widget": self.add(npyscreen.TitleText, name="URL Api OgCore (https://127.0.0.1:8443):", value="https://127.0.0.1:8443")}
|
||||
self.fields["mercure_ip"] = {"widget": self.add(npyscreen.TitleText, name="Mercue IP (127.0.0.1):", value="127.0.0.1")}
|
||||
|
||||
class OgDhcpForm(ComponentForm):
|
||||
component_name = "ogDhcp"
|
||||
|
||||
|
@ -184,7 +184,7 @@ class OgBootForm(ComponentForm):
|
|||
self.fields["ogCore_ServerIP"] = {"widget": self.add(npyscreen.TitleText, name="ogCore IP:", value="")}
|
||||
self.fields["ogBoot_ServerIP"] = {"widget": self.add(npyscreen.TitleText, name="ogBoot Server IP:", value="")}
|
||||
self.fields["ogBoot_Dir"] = {"widget": self.add(npyscreen.TitleText, name="ogCore Dir (/opt/opengnsys/ogboot):", value="/opt/opengnsys/ogboot")}
|
||||
self.fields["ogLive_Default"] = {"widget": self.add(npyscreen.TitleText, name="ogLive por defecto:", value="https://ognproject.evlt.uma.es/oglive/ogLive-noble-6.8.0-31-generic-amd64-r20250116.538e3fa_20250120.iso")}
|
||||
self.fields["ogLive_Default"] = {"widget": self.add(npyscreen.TitleText, name="ogLive por defecto:", value="https://ognproject.evlt.uma.es/oglive/ogLive-noble-6.8.0-31-generic-amd64-r20241128.62778c9_20241129.iso")}
|
||||
self.fields["ogBootSambaUser"] = {"widget": self.add(npyscreen.TitleText, name="ogBoot Samba User (opengnsys):", value="opengnsys")}
|
||||
self.add_password_field("ogBootSambaPass", "ogBoot Samba Pass (og):", default_value="og")
|
||||
self.add_password_field("confirm_ogBootSambaPass", "Confirmar ogBoot Samba Pass (og):", is_confirmation=True, default_value="og")
|
|
@ -37,8 +37,8 @@ download_installer() {
|
|||
extract_installer() {
|
||||
rm -rf /tmp/oginstall
|
||||
mkdir -p /tmp/oginstall
|
||||
cp -r /tmp/oginstaller-$BRANCH/non_graf_installer/python-installer/* /tmp/oginstall/
|
||||
cp -r /tmp/oginstaller-$BRANCH/non_graf_installer/component-installer/* /tmp/oginstall/
|
||||
cp -r /tmp/oginstaller-$BRANCH/python-installer/* /tmp/oginstall/
|
||||
cp -r /tmp/oginstaller-$BRANCH/component-installer/* /tmp/oginstall/
|
||||
chmod 755 /tmp/oginstall/*.sh
|
||||
chmod 755 /tmp/oginstall/*.py
|
||||
}
|
|
@ -1,4 +1,2 @@
|
|||
GitPython
|
||||
npyscreen
|
||||
requests
|
||||
bs4
|