Compare commits

..

No commits in common. "main" and "deb-package" have entirely different histories.

89 changed files with 10177 additions and 1276 deletions

View File

View File

@ -1,47 +0,0 @@
# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
# * .env contains default values for the environment variables needed by the app
# * .env.local uncommitted file with local overrides
# * .env.$APP_ENV committed environment-specific defaults
# * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
# https://symfony.com/doc/current/configuration/secrets.html
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration
###> symfony/framework-bundle ###
APP_ENV=prod
APP_SECRET=d423d1302b974417d415b10bcde25767
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
# DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=8&charset=utf8mb4"
DATABASE_URL="postgresql://app:!ChangeMe!@127.0.0.1:5432/app?serverVersion=15&charset=utf8"
###< doctrine/doctrine-bundle ###
###> symfony/messenger ###
# Choose one of the transports below
# MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages
# MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
###< symfony/messenger ###
###> symfony/mailer ###
# MAILER_DSN=null://null
###< symfony/mailer ###
### Opengnsys Variables
#
OGCORE_API_URL="https://127.0.0.1:8443"
OGBOOT_IP="127.0.0.1"
OGBOOT_PORT="8082"

6
.gitignore vendored
View File

@ -19,9 +19,3 @@
.phpunit.result.cache
/phpunit.xml
###< symfony/phpunit-bridge ###
### Debian packaging
debian/ogboot
debian/*.substvars
debian/*.log
debian/.debhelper/
debian/files

View File

@ -1,20 +1,5 @@
# CHANGELOG
## [0.7.1] - 19/06/2025
### **Cambios principales**
1. Añade scripts de grub y menu.lst para el arranque del Oglive por cache
## [0.7.0] - 19/06/2025
### **Cambios principales**
1. No hay cambios, pasa el tag 0.5.12 a 0.6.0
## [0.6.0] - 25/02/2025
### **Cambios principales**
1. No hay cambios, pasa el tag 0.5.12 a 0.6.0
## [0.5.12] - 25/02/2025
### **Cambios principales**

View File

@ -1,126 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.8.10] - 2024-07-05
### Changed
- Añade oglive BIOS para el arranque de Windows al arrancarlo desde el ogbrowser
- Elimina arranque MBR del menú de arranque
## [0.8.9] - 2024-06-30
### Changed
- Borra directorio samba de etc y modifica postint para que copie el fichero de configuración de la plantilla de samba
## [0.8.8] - 2024-06-27
### Changed
- Actualiza grub.exe para que soporte sistemas de particiones ext
- Actualiza las plantillas de arranque de menu para bios para que use el nuevo grub.exe
- Elimina la plantilla de bootmark obsoleta
## [0.8.7] - 2024-06-25
### Changed
- Elimina el parámetro de kernel ogdebug del controlador y se le añade a las plantillas de arranque de oglive
## [0.8.6] - 2024-06-24
### Changed
- Modifica la plantilla de arranque por disco y partición para no tener hardcodeado la partición EFI
## [0.8.5] - 2024-06-24
### Changed
- Comprueba si existe una etiqueta para asignar root cuando corresponda en la plantilla de arranque por disco y partición
## [0.8.4] - 2024-06-20
### Changed
- Corrige oglivecli para que desmonte los puntos de montaje ante cualquier fallo en el script de instalación de oglive
## [0.8.3] - 2024-06-20
### Changed
- Añade el cambio de la 0.8.2
## [0.8.2] - 2024-06-20
### Changed
- Corrige un bug en oglivecli que impide cambiar el propietario del oglive
## [0.8.1] - 2024-06-18
### Changed
- Añade nuevos modulos al grubx64.efi
## [0.8.0] - 2024-06-18
### Changed
- Actualiza a 0.8.0 para incluir los cambios de la versión 0.7.2
## [0.7.2] - 2024-06-05
### Changed
- Añade scripts de grub y menu.lst para el arranque por disco y partición
- Añade plantilla ogliveadmin con permisos de administracion como parametro del kernel
- Añade plantilla de menú para el arranque por disco y partición y caché
## [0.7.1] - 2024-05-19
### Changed
- Añade scripts de grub y menu.lst para el arranque del Oglive por cache
## [0.7.0] - 2024-03-26
### Changed
- Updated files location
## [0.6.3] - 2025-03-19
### Changed
- Jenkinsfile to upload debian packages
## [0.6.2] - 2025-03-19
### Changed
- Jenkinsfile to upload debian packages
## [0.6.1] - 2025-02-25
### Fixed
- Arreglos menores
## [0.6.1] - 2025-02-25
### Fixed
- Arreglos menores
## [0.6.0] - 2025-02-25
### Changed
- No hay cambios en esta versión, se incrementa el tag de `0.5.12` a `0.6.0`.
## [0.5.12] - 2025-02-25
### Added
- Monta `efivars` al inicio del arranque del `oglive`.
### Fixed
- Corrige un error en un `awk` al obtener entradas NVRAM.
- Devuelve un array vacío cuando no hay `oglives` instalados.
- Devuelve una excepción cuando se intenta instalar un `Oglive` ya instalado.
## [0.5.11] - 2025-02-06
### Changed
- Permite la lectura de otros usuarios en el home `/opt/opengnsys` del usuario `opengnsys`.
## [0.5.10] - 2025-02-06
### Changed
- Cambia el home del usuario `opengnsys` a `/opt/opengnsys`.
## [0.5.9] - 2025-02-03
### Added
- Añade el puerto `8443` de `ogcore` al `PostConf.lib`.
## [0.5.8] - 2025-01-13
### Fixed
- Arregla un bug que no añadía los parámetros `ogcore` y `oglog` al crear los ficheros de arranque.
## [0.5.7] - 2025-01-13
### Added
- Añade logs para todos los endpoints siguiendo un formato JSON preestablecido.
### Changed
- Actualiza `monolog.yaml` para enviar logs al `journal` de la máquina.

View File

@ -1,104 +0,0 @@
@Library('jenkins-shared-library') _
pipeline {
agent {
label 'jenkins-slave'
}
environment {
DEBIAN_FRONTEND = 'noninteractive'
DEFAULT_DEV_NAME = 'Opengnsys Team'
DEFAULT_DEV_EMAIL = 'opengnsys@qindel.com'
}
options {
skipDefaultCheckout()
}
parameters {
string(name: 'DEV_NAME', defaultValue: '', description: 'Nombre del desarrollador')
string(name: 'DEV_EMAIL', defaultValue: '', description: 'Email del desarrollador')
}
stages {
stage('Prepare Workspace') {
steps {
script {
env.BUILD_DIR = "${WORKSPACE}/ogboot"
sh "mkdir -p ${env.BUILD_DIR}"
}
}
}
stage('Checkout') {
steps {
dir("${env.BUILD_DIR}") {
checkout scm
}
}
}
stage('Generate Changelog') {
when {
expression {
return env.TAG_NAME != null
}
}
steps {
script {
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
generateDebianChangelog(env.BUILD_DIR, devName, devEmail)
}
}
}
stage('Generate Changelog (Nightly)'){
when {
branch 'main'
}
steps {
script {
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
generateDebianChangelog(env.BUILD_DIR, devName, devEmail,'nightly')
}
}
}
stage('Build') {
steps {
script {
construirPaquete(env.BUILD_DIR, "../artifacts", "172.17.8.68", "/var/tmp/opengnsys/debian-repo/ogboot")
}
}
}
stage ('Publish to Debian Repository') {
when {
expression {
return env.TAG_NAME != null
}
}
agent { label 'debian-repo' }
steps {
script {
// Construir el patrón de versión esperado en el nombre del paquete
def versionPattern = "${env.TAG_NAME}-${env.BUILD_NUMBER}"
publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogboot', 'opengnsys-devel', versionPattern)
}
}
}
stage ('Publish to Debian Repository (Nightly)') {
when {
branch 'main'
}
agent { label 'debian-repo' }
steps {
script {
// Construir el patrón de versión esperado en el nombre del paquete
def versionPattern = "-${env.BUILD_NUMBER}~nightly"
publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogboot', 'nightly', versionPattern)
}
}
}
}
post {
always {
notifyBuildStatus('narenas@qindel.com')
}
}
}

View File

@ -1,9 +0,0 @@
<?php
use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};

View File

@ -0,0 +1,85 @@
import os
import socket
import json
import subprocess
import logging
import stat
# Configuración de logging
logging.basicConfig(level=logging.INFO, filename='/var/log/oglive_daemon.log', filemode='a', format='%(asctime)s - %(levelname)s - %(message)s')
def handle_command(command):
action = command.get('action')
args = command.get('args', [])
cleaned_args = [arg.strip('\'"') for arg in args]
logging.info(f'Handling command: {action} with args: {cleaned_args}')
try:
if action in ['config', 'install', 'download', 'show', 'check', 'uninstall', 'disk_usage','list_installed_oglives','get_info','get_default','set_default','check_services_status']:
command_to_run = ['sudo', '/opt/ogboot/bin/oglivecli', action] + cleaned_args
logging.info(f'Running command: {" ".join(command_to_run)}')
process = subprocess.Popen(command_to_run, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()
logging.info(f'Command stdout: {stdout}')
logging.error(f'Command stderr: {stderr}')
# Asumimos que `stdout` contendrá el JSON válido
try:
json_output = json.loads(stdout)
return {"success": True, "output": json_output}
except json.JSONDecodeError as e:
logging.error(f'Error parsing JSON: {e} - Raw output: {stdout}')
return {"success": False, "error": f'Error parsing JSON: {str(e)} - Raw output: {stdout}'}
else:
return {"success": False, "error": "Unknown command"}
except Exception as e:
logging.error(f'Error handling command {action}: {e}')
return {"success": False, "error": str(e)}
def main():
# Crea el directorio si no existe
if not os.path.exists('/var/run/oglive'):
os.makedirs('/var/run/oglive', exist_ok=True)
socket_path = '/var/run/oglive/oglive_daemon.sock'
# Elimina el socket si existe
if os.path.exists(socket_path):
os.remove(socket_path)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(socket_path)
# Establece los permisos del socket
os.chmod(socket_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # Permisos para todos los usuarios
server.listen()
try:
while True:
logging.info('Daemon ready to accept connections')
conn, _ = server.accept()
with conn:
logging.info('Accepted connection')
data = conn.recv(1024)
if not data:
continue
try:
command = json.loads(data.decode('utf-8'))
logging.info(f'Received command: {command}')
except json.JSONDecodeError:
logging.error('Failed to decode JSON')
conn.sendall(json.dumps({"success": False, "error": "Invalid JSON"}).encode('utf-8'))
continue
response = handle_command(command)
conn.sendall(json.dumps(response).encode('utf-8'))
finally:
server.close()
if os.path.exists(socket_path):
os.remove(socket_path)
if __name__ == '__main__':
main()

View File

@ -334,20 +334,6 @@ function install() {
[ ! -d "$TMPDIR_SQUASHFS" ] && { echo "{\"error\": \"DIR_CREATION_FAILED\", \"message\": \"Failed to create/access directory $TMPDIR_SQUASHFS.\"}"; exit 500; }
trap "umount $TMPDIR" 1 2 3 6 9 15
cleanup() {
code=$?
umount "$OGLIVEFILE" >/dev/null 2>&1
umount "$TMPDIR" >/dev/null 2>&1
umount "$TMPDIR_SQUASHFS" >/dev/null 2>&1
if [ $code -ne 0 ]; then
echo "Something went wrong (exit code $code), cleaning up..."
rm -r "$OGLIVEDIR" >/dev/null 2>&1
fi
}
trap cleanup EXIT
mount "$OGLIVEFILE" >/dev/null 2>&1 || { echo "{\"error\": \"MOUNT_FAILED\", \"message\": \"Failed to mount ISO file.\"}"; exit 500; }
cp -va "$TMPDIR/ogclient/"* "$OGLIVEDIR" >/dev/null 2>&1 || { echo "{\"error\": \"COPY_FAILED\", \"message\": \"Cannot copy files to $OGLIVEDIR.\"}"; exit 500; }
@ -405,7 +391,7 @@ function install() {
}' > "$OGLIVEDIR/oglive_info.json"
[ ! -f "$OGLIVEDIR/oglive_info.json" ] && { echo "{\"error\": \"JSON_CREATION_FAILED\", \"message\": \"Failed to create oglive_info.json.\"}"; exit 500; }
# chown -R :opengnsys "$OGLIVEDIR" >/dev/null 2>&1 || { echo "{\"error\": \"CHOWN_FAILED\", \"message\": \"Failed to change ownership for $OGLIVEDIR.\"}"; exit 500; }
sudo chown -R :opengnsys "$OGLIVEDIR" >/dev/null 2>&1 || { echo "{\"error\": \"CHOWN_FAILED\", \"message\": \"Failed to change ownership for $OGLIVEDIR.\"}"; exit 500; }
JSON_OUTPUT=$(jq -n \
--arg id "$OGLIVEID" \
--arg dist "$OGLIVEDIST" \

View File

@ -1,7 +1,8 @@
#!/bin/bash
PROG=$(basename $0)
OPENGNSYS=${OPENGNSYS:-"/opt/opengnsys/ogboot"}
OPENGNSYS=${OPENGNSYS:-"/opt/ogboot"}
OGCFGFILE=$OPENGNSYS/etc/ogboot_samba.json
SAMBAUSER="opengnsys" # Usuario por defecto.
TFTPDIR=$OPENGNSYS/tftpboot
INITRD=oginitrd.img
@ -17,7 +18,7 @@ fi
case $# in
0) # Cambios en todos los clientes ogLive instalados.
if which oglivecli &>/dev/null; then
LIST=$(./oglivecli list_installed_oglives | jq -r '.installed_ogLives[].directory' | xargs -n1 basename)
LIST=$(oglivecli list | awk '{print $2}')
else
LIST="ogclient"
fi ;;
@ -94,6 +95,42 @@ for OGLIVE in $LIST; do
sudo sed -i "s/OPTIONS=\(.*\)user=\w*\(.*\)pass=\w*\(.*\)/OPTIONS=\1user=$SAMBAUSER\2pass=$SAMBAPASS\3/" scripts/ogfunctions
# TEMPORAL: solución ticket 554, actualizar cliente en caché (ogLive r3257).
sudo sed -i "s/busybox reboot/reboot/" scripts/ogfunctions
# FIN CÓDIGO TEMPORAL.
# Ticket 565, preparar acceso Rsync cliente.
echo "$SAMBAPASS" | sudo tee scripts/passrsync > /dev/null
echo "Guardar tokens de seguridad"
cat <<EOT | sudo tee scripts/client.cfg > /dev/null
CLIENTID=$(jq -r .client.id $OGCFGFILE)
CLIENTSECRET=$(jq -r .client.secret $OGCFGFILE)
EOT
sudo chown ogboot:ogboot scripts/passrsync scripts/client.cfg
# pwd
# sudo find . -print > /tmp/filelist.txt
# if [ $? -ne 0 ]; then
# echo "Error: No se pudo encontrar los archivos."
# exit 5
# fi
# cpio -H newc -oa < /tmp/filelist.txt > /tmp/initrd.cpio
# if [ $? -ne 0 ]; then
# echo "Error: No se pudo crear el archivo CPIO."
# exit 5
# fi
# $COMPRESS_CMD < /tmp/initrd.cpio > /tmp/initrd.cpio.gz
# if [ $? -ne 0 ]; then
# echo "Error: No se pudo comprimir el archivo CPIO."
# exit 5
# fi
# echo "Copiando el contenido del archivo /tmp/initrd.cpio.gz al archivo /opt/opengnsys/tftpboot/ogLive-5.11.0-r20210413/oginitrd.img."
# echo $CLIENTINITRD
# dd if=/tmp/initrd.cpio.gz of=/opt/opengnsys/tftpboot/ogLive-5.11.0-r20210413/oginitrd.img
# echo "dd ejecutado correctamente"
# if [ $? -ne 0 ]; then
# echo "Error: No se pudo escribir el archivo comprimido en el destino."
# exit 5
# fi
# echo "borrando rm /tmp/initrd.cpio /tmp/initrd.cpio.gz"
# sudo rm /tmp/initrd.cpio /tmp/initrd.cpio.gz
find . | cpio -H newc -oa | gzip -9c > "$CLIENTINITRD"
else
echo "$PROG: Aviso: no se ha modificado la clave del cliente \"$OGLIVE\"."
@ -109,8 +146,12 @@ for OGLIVE in $LIST; do
done
if [[ $CHANGES != 0 ]]; then
# Ticket 565, preparar acceso Rsync servidor.
echo "$SAMBAUSER:$SAMBAPASS" | sudo tee /etc/rsyncd.secrets > /dev/null
echo "chown debugging"
sudo chown root:root /etc/rsyncd.secrets
sudo chmod 600 /etc/rsyncd.secrets
# Cambiar clave Samba.
echo "Cambiando clave samba en el servidor"
echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | sudo smbpasswd -a -s $SAMBAUSER
echo "setsmbpass finish"
else

9901
composer.lock generated 100755

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters:
tftpboot_dir: '%kernel.project_dir%/../tftpboot'
tftpboot_dir: '%kernel.project_dir%/tftpboot'
services:
# default configuration for services in *this* file
_defaults:

6
debian/README vendored
View File

@ -1,6 +0,0 @@
The Debian Package ogboot
----------------------------
<Comments regarding the Package.>
-- vagrant <vagrant@build> Tue, 04 Mar 2025 15:42:24 +0000

View File

@ -1,6 +0,0 @@
ogboot for Debian
----------------
<Possible notes regarding this package - if none, delete this file.>
-- vagrant <vagrant@build> Tue, 04 Mar 2025 15:42:24 +0000

10
debian/README.source vendored
View File

@ -1,10 +0,0 @@
ogboot for Debian
----------------
<This file describes information about the source package, see Debian policy
manual section 4.14. You WILL either need to modify or delete this file.>
-- vagrant <vagrant@build> Tue, 04 Mar 2025 15:42:24 +0000

14
debian/changelog vendored
View File

@ -1,14 +0,0 @@
ogboot (1.0.1+deb-pkg20250310-1) unstable; urgency=medium
* First debian installation
* refs #1615 merge deb-package
* refs #1615 remove client stuff
* refs #1610 adds systctl in loadenviron.sh
* refs #1593 add UEFILib and python scripts
* refs #1609 set PATH and PYTHONPATH up
* fix bug ogisefiactive
* refs #1593 add python libs and executables
* updates CHANGELOG 0.6.0
* refs #1592 move client/shared files
-- Tu Nombre <tuemail@example.com> Mon, 10 Mar 2025 19:33:51 +0000

80
debian/control vendored
View File

@ -1,80 +0,0 @@
Source: ogboot
Section: unknown
Priority: optional
Maintainer: vagrant <vagrant@build>
Rules-Requires-Root: no
Build-Depends:
debhelper-compat (= 13),
Standards-Version: 4.6.2
Homepage: <insert the upstream URL, if relevant>
#Vcs-Browser: https://salsa.debian.org/debian/ogboot
#Vcs-Git: https://salsa.debian.org/debian/ogboot.git
Package: ogboot
Architecture: any
Multi-Arch: foreign
Depends:
${shlibs:Depends},
${misc:Depends},
debconf (>= 1.5.0),
nfs-common,
xorriso,
genisoimage,
syslinux,
liblzma-dev,
nginx,
arp-scan,
automake,
build-essential,
btrfs-progs,
composer,
curl,
ctorrent,
debootstrap,
g++-multilib,
gawk,
gettext,
graphviz,
grub-efi-amd64-signed,
jq,
libdbi-dev,
libdbi1t64,
libev-dev,
libjansson-dev,
liblz4-tool,
libssl-dev,
moreutils,
netpipes,
php8.3,
php8.3-bcmath,
php8.3-cli,
php8.3-curl,
php8.3-fpm,
php8.3-gd,
php8.3-ldap,
php8.3-mbstring,
php8.3-mysql,
php8.3-common,
php-pear,
php8.3-xml,
php8.3-zip,
procps,
coreutils,
rsync,
samba,
samba-common-bin,
schroot,
shim-signed,
squashfs-tools,
subversion,
tftpd-hpa,
udpcast,
unzip,
wakeonlan,
wget,
xinetd,
isolinux,
file
Conflicts: apache2
Description: Opengnsys Ogboot package
Files for the ogboot API and rest of configuration.

43
debian/copyright vendored
View File

@ -1,43 +0,0 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Source: <url://example.com>
Upstream-Name: ogboot
Upstream-Contact: <preferred name and address to reach the upstream project>
Files:
*
Copyright:
<years> <put author's name and email here>
<years> <likewise for another author>
License: GPL-3.0+
Files:
debian/*
Copyright:
2025 vagrant <vagrant@build>
License: GPL-3.0+
License: GPL-3.0+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Comment:
On Debian systems, the complete text of the GNU General
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
# Please also look if there are files or directories which have a
# different copyright/license attached and list them here.
# Please avoid picking licenses with terms that are more restrictive than the
# packaged work, as it may make Debian's contributions unacceptable upstream.
#
# If you need, there are some extra license texts available in two places:
# /usr/share/debhelper/dh_make/licenses/
# /usr/share/common-licenses/

View File

@ -1 +0,0 @@
ogboot

View File

@ -1,3 +0,0 @@
README.source
README.Debian
README

14
debian/ogboot.config vendored
View File

@ -1,14 +0,0 @@
#!/bin/sh
set -e
. /usr/share/debconf/confmodule
db_input high opengnsys/ogboot_ip || true
db_input high opengnsys/ogboot_port || true
db_input high opengnsys/ogboot_ogcoreUrl || true
db_input high opengnsys/ogboot_ogliveUrl || true
# db_input high opengnsys/ogboot_sambaUser || true
# db_input high opengnsys/ogboot_sambaUserPass || true
db_go

3
debian/ogboot.dirs vendored
View File

@ -1,3 +0,0 @@
/opt/opengnsys/ogboot/client_log
/opt/opengnsys/ogboot/mnt
/opt/opengnsys/ogboot/tftpboot

View File

@ -1,8 +0,0 @@
api /opt/opengnsys/ogboot
etc /opt/opengnsys/ogboot
lib /opt/opengnsys/ogboot
bin /opt/opengnsys/ogboot
tftpboot /opt/opengnsys/ogboot/

206
debian/ogboot.postinst vendored
View File

@ -1,206 +0,0 @@
#!/bin/bash
set -e
# Cargar el módulo de configuración de debconf
. /usr/share/debconf/confmodule
# Leer las variables de configuración
OGBOOT_ROOT="/opt/opengnsys/ogboot"
OGBOOT_API_DIR="/opt/opengnsys/ogboot/api"
db_get opengnsys/ogboot_ip
OGBOOT_IP="$RET"
db_get opengnsys/ogboot_port
OGBOOT_PORT="$RET"
db_get opengnsys/ogboot_ogcoreUrl
OGCORE_API_URL="$RET"
db_get opengnsys/ogboot_ogliveUrl
OGCORE_OGLIVE_URL="$RET"
# db_get opengnsys/ogboot_sambaUser
# SAMBA_USER="$RET"
# db_get opengnsys/ogboot_sambaUserPass
# SAMBA_PASS="$RET"
# IPXE_REPO="https://github.com/ipxe/ipxe.git"
IPXE_REPO="https://ognproject.evlt.uma.es/gitea/narenas/opengnsys_ipxe.git"
# Asegurarse de que el usuario exista
USER="opengnsys"
USER_INFO=$(getent passwd "$USER")
DEFAULT_OGLIVE=$OGCORE_OGLIVE_URL
ENV_FILE=/opt/opengnsys/ogboot/api/.env
if [ -z "$USER_INFO" ]; then
echo "Error: El usuario '$USER' no existe." >&2
exit 1
fi
USER_UID=$(echo "$USER_INFO" | cut -d: -f3)
USER_GID=$(echo "$USER_INFO" | cut -d: -f4)
INSTALL_OGBOOT_TARGET="/opt/opengnsys/ogboot"
fstab_entries=(
"$INSTALL_OGBOOT_TARGET/lib/oglive.iso $INSTALL_OGBOOT_TARGET/mnt iso9660 loop,ro,users,uid=$USER_UID,gid=$USER_GID,noauto 0 0"
"/opt/opengnsys/ogboot/tftpboot/ogLive/ogclient.sqfs /tmp/ogclient_mount squashfs loop,ro,user,noauto 0 0"
)
fstab_file="/etc/fstab"
configure_sudo() {
echo "Copiando configuración de sudo"
if [ ! -f /etc/sudoers.d/opengnsys ]; then
cp /opt/opengnsys/ogboot/etc/ogboot.sudoers /etc/sudoers.d/opengnsys
chmod 440 /etc/sudoers.d/opengnsys
sed -i "s|__OGBOOT_TARGET__|$OGBOOT_ROOT|g" /etc/sudoers.d/opengnsys
else
echo "El archivo /etc/sudoers.d/opengnsys ya existe."
fi
}
add_fstab_entries(){
echo "Añadiendo entradas a /etc/fstab"
for entry in "${fstab_entries[@]}"; do
if ! grep -Fxq "$entry" "$fstab_file"; then
echo "$entry" | sudo tee -a "$fstab_file" > /dev/null
echo "Entrada añadida a /etc/fstab: $entry"
else
echo "La entrada ya existe en /etc/fstab: $entry"
fi
done
}
update_opengnsys_user() {
echo "Actualizando grupos del usuario opengnsys"
usermod -aG disk "$USER"
}
configure_tftp(){
echo "Modificando el archivo tftpboot"
# Comprobar si el archivo ya está desviado
if ! dpkg-divert --list /etc/default/tftpd-hpa | grep -q "/etc/default/tftpd-hpa"; then
echo "Creando divert para /etc/default/tftpd-hpa"
dpkg-divert --add --rename --divert /etc/default/tftpd-hpa.orig /etc/default/tftpd-hpa
fi
# Copiar archivo solo si no existe en la nueva ubicación
if [ ! -f /etc/default/tftpd-hpa ]; then
echo "Copiando configuración de tftpd-hpa"
cp /opt/opengnsys/ogboot/etc/default/tftpd-hpa /etc/default/tftpd-hpa
fi
}
install_oglive(){
echo "Download ogLive"
/opt/opengnsys/ogboot/bin/oglivecli download "$DEFAULT_OGLIVE"
}
configure_ipxe(){
echo "Configure ipxe templates"
cp $OGBOOT_ROOT/etc/dhcp_boot.ipxe.tmpl $OGBOOT_ROOT/tftpboot/ipxe_scripts/dhcp_boot.ipxe
cp $OGBOOT_ROOT/etc/default.ipxe.tmpl $OGBOOT_ROOT/tftpboot/ipxe_scripts/default.ipxe
sed -i "s|__SERVERIP__|$OGBOOT_IP|g" $OGBOOT_ROOT/tftpboot/ipxe_scripts/dhcp_boot.ipxe
sed -i "s|__SERVERIP__|$OGBOOT_IP|g" $OGBOOT_ROOT/tftpboot/ipxe_scripts/default.ipxe
echo "Instalando ipxe"
rm -rf /tmp/ipxe_repo
git clone $IPXE_REPO /tmp/ipxe_repo
if [ ! -f $OGBOOT_ROOT/tftpboot/undionly.kpxe ]; then
cd /tmp/ipxe_repo/src
make -j4 -s bin/undionly.kpxe EMBED=$OGBOOT_ROOT/tftpboot/ipxe_scripts/dhcp_boot.ipxe
make -j4 -s bin-x86_64-efi/ipxe.efi EMBED=$OGBOOT_ROOT/tftpboot/ipxe_scripts/dhcp_boot.ipxe
cp bin/undionly.kpxe $OGBOOT_ROOT/tftpboot/
cp bin-x86_64-efi/ipxe.efi $OGBOOT_ROOT/tftpboot/
fi
}
configure_api(){
if ! grep -q "OGCORE_API_URL" $ENV_FILE; then
echo "OGCORE_API_URL=$OGCORE_API_URL" >> $ENV_FILE
fi
if ! grep -q "OGBOOT_IP" $ENV_FILE; then
echo "OGBOOT_IP=$OGBOOT_IP" >> $ENV_FILE
fi
if ! grep -q "OGBOOT_PORT" $ENV_FILE; then
echo "OGBOOT_PORT=$OGBOOT_PORT" >> $ENV_FILE
fi
}
configure_nginx_and_fpm() {
echo "Configure nginx"
PHP_VERSION=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
if [ ! -f /etc/nginx/sites-available/ogboot.conf ]; then
cp /opt/opengnsys/ogboot/etc/nginxServer.conf.tmpl /etc/nginx/sites-available/ogboot.conf
sed -i "s|__ROOT__|$OGBOOT_API_DIR|g" /etc/nginx/sites-available/ogboot.conf
sed -i "s|__PHPVERSION__|$PHP_VERSION|g" /etc/nginx/sites-available/ogboot.conf
sed -i "s|__SERVERIP__|$OGBOOT_IP|g" /etc/nginx/sites-available/ogboot.conf
sed -i "s|__PORT__|$OGBOOT_PORT|g" /etc/nginx/sites-available/ogboot.conf
sed -i "s|__TFTPPATH__|$OGBOOT_ROOT/tftpboot|g" /etc/nginx/sites-available/ogboot.conf
ln -s /etc/nginx/sites-available/ogboot.conf /etc/nginx/sites-enabled/ogboot.conf
else
echo "El archivo /etc/nginx/sites-available/opengnsys ya existe."
fi
echo "Modificando el fpm"
if [ ! -f /etc/php/$PHP_VERSION/fpm/pool.d/ogboot.conf ]; then
cp /opt/opengnsys/ogboot/etc/ogboot-fpm.conf /etc/php/$PHP_VERSION/fpm/pool.d/ogboot.conf
fi
}
configure_samba(){
echo "Configurando Samba"
cp /opt/opengnsys/ogboot/etc/smb-ogboot.conf.tmpl /etc/samba/smb-ogboot.conf
sed -i "s|__OGBOOTDIR__|$OGBOOT_ROOT|g" /etc/samba/smb-ogboot.conf
INCLUDE_LINE="include = /etc/samba/smb-ogboot.conf"
if ! grep -q "$INCLUDE_LINE" /etc/samba/smb.conf; then
echo "$INCLUDE_LINE" | sudo tee -a /etc/samba/smb.conf > /dev/null
fi
}
configure_permissions(){
echo "Cambiando la propiedad de los archivos al usuario $USER"
chown opengnsys:www-data /opt/opengnsys/
chown -R opengnsys:www-data /opt/opengnsys/ogboot
}
restart_services(){
systemctl daemon-reload
systemctl restart nginx
systemctl restart tftpd-hpa
systemctl restart php8.3-fpm
systemctl restart samba
}
# Detectar si es una instalación nueva o una actualización
if [ "$1" = "configure" ] && [ -z "$2" ]; then
# Copy sudo configuration
echo "Primera instalación"
configure_sudo
add_fstab_entries
update_opengnsys_user
configure_tftp
install_oglive
configure_ipxe
configure_api
configure_nginx_and_fpm
configure_samba
elif [ "$1" = "configure" ] && [ -n "$2" ]; then
echo "Actualización desde la versión $2"
configure_sudo
configure_tftp
configure_api
configure_nginx_and_fpm
configure_samba
fi
configure_permissions
restart_services
exit 0

24
debian/ogboot.postrm vendored
View File

@ -1,24 +0,0 @@
#!/bin/bash
set -e
CONFIG_FILE="/etc/default/tftpd-hpa"
DIVERTED_FILE="/etc/default/tftpd-hpa.orig"
if [ "$1" = "remove" ]; then
echo "Restaurando archivo de configuración original..."
# Restaurar el archivo original si existe
if [ -f "$DIVERTED_FILE" ]; then
mv "$DIVERTED_FILE" "$CONFIG_FILE"
fi
# Eliminar la desviación
dpkg-divert --remove --rename "$CONFIG_FILE"
# Eliminar la linea de inclusión de samba en smb.conf si existe
INCLUDE_LINE="include = /etc/samba/opengnsys/smb_ogboot.conf"
if grep -q "$INCLUDE_LINE" /etc/samba/smb.conf; then
sed -i "/$INCLUDE_LINE/d" /etc/samba/smb.conf
fi
fi

View File

@ -1,6 +0,0 @@
# Automatically added by dh_installdebconf/13.14.1ubuntu5
if [ "$1" = purge ] && [ -e /usr/share/debconf/confmodule ]; then
. /usr/share/debconf/confmodule
db_purge
fi
# End automatically added section

15
debian/ogboot.preinst vendored
View File

@ -1,15 +0,0 @@
#!/bin/bash
set -e
# Asegurarse de que el usuario exista
USER="opengnsys"
HOME_DIR="/opt/opengnsys"
if id "$USER" &>/dev/null; then
echo "El usuario $USER ya existe."
else
echo "Creando el usuario $USER con home en $HOME_DIR."
useradd -m -d "$HOME_DIR" -s /bin/bash "$USER"
fi
exit 0

25
debian/ogboot.prerm vendored
View File

@ -1,25 +0,0 @@
#!/bin/bash
set -e
case "$1" in
remove|upgrade|deconfigure)
echo "Deteniendo servicios antes de la eliminación o actualización..."
systemctl stop nginx || true
systemctl stop tftpd-hpa || true
systemctl stop php8.3-fpm || true
systemctl stop samba || true
echo "Eliminando configuraciones específicas..."
if [ "$1" = "remove" ]; then
rm -f /etc/nginx/sites-enabled/ogboot.conf
rm -f /etc/nginx/sites-available/ogboot.conf
rm -f /etc/sudoers.d/opengnsys
rm -f /etc/php/8.3/fpm/pool.d/ogboot.conf
dpkg-divert --remove --rename --divert /etc/default/tftpd-hpa.orig /etc/default/tftpd-hpa || true
dpkg-divert --remove --rename --divert /opt/opengnsys/ogboot/.env.local.php.orig /opt/opengnsys/ogboot/.env.local.php || true
fi
;;
esac
exit 0

View File

@ -1,35 +0,0 @@
Template: opengnsys/ogboot_ip
Type: string
Default: 192.168.1.100
Description: Introduce la IP donde se ejecutará OGBOOT
Esta IP será utilizada para la configuración del servicio.
Template: opengnsys/ogboot_port
Type: string
Default: 8082
Description: Puerto para OGBOOT
Por favor introduce el puerto donde escuchará ogBoot
Template: opengnsys/ogboot_ogcoreUrl
Type: string
Default: https://127.0.0.1:8443
Description: URL del API de ogCore
Por favor introduzca la URL donde se ejecuta ogCore
Template: opengnsys/ogboot_ogliveUrl
Type: string
Default: https://ognproject.evlt.uma.es/oglive/ogLive-noble-6.8.0-31-generic-amd64-r20250116.538e3fa_20250120.iso
Description: URL del OgLive a instalar
Por favor introduzca la URL desde donde descargar el ogLive para su uso.
Template: opengnsys/ogboot_sambaUser
Type: string
Default: opengnsys
Description: Usuario de samba para compartir tftpboot y client_log
No cambiar a no ser que se sepa lo que se esta haciendo
Template: opengnsys/ogboot_sambaUserPass
Type: password
Default: og
Description: Password del Usuario de samba para compartir tftpboot y client_log
No cambiar a no ser que se sepa lo que se esta haciendo

13
debian/rules vendored
View File

@ -1,13 +0,0 @@
#!/usr/bin/make -f
%:
dh $@
# Ejecutar composer install durante la fase de construcción
override_dh_auto_build:
cd api/; \
rm -rf var/cache/*; \
mkdir -p public; \
COMPOSER_ALLOW_SUPERUSER=1 APP_ENV=prod composer install --no-interaction --no-progress --optimize-autoloader; \
COMPOSER_ALLOW_SUPERUSER=1 APP_ENV=prod composer update doctrine/dbal;

View File

@ -1 +0,0 @@
3.0 (native)

View File

@ -1,6 +0,0 @@
# /etc/default/tftpd-hpa
TFTP_USERNAME="opengnsys"
TFTP_DIRECTORY="/opt/opengnsys/ogboot/tftpboot"
TFTP_ADDRESS="0.0.0.0:69"
TFTP_OPTIONS="--secure -v"

View File

@ -0,0 +1,44 @@
{
"Dhcp4": {
"interfaces-config": {
"interfaces": "INTERFACES"
},
"subnet4": [
{
"subnet": "192.168.2.0/24",
"option-data": [
{
"name": "routers",
"code": 3,
"data": "192.168.2.1"
}
],
"pools": []
}
],
"option-data": [
{
"name": "domain-name-servers",
"data": "1.1.1.1,8.8.8.8"
},
{
"name": "routers",
"data": "192.168.8.1,192.168.9.1"
}
],
"client-classes": [
{
"name": "UEFI-64",
"test": "not substring(option[60].hex,0,20) == 'PXEClient:Arch:00000'",
"boot-file-name": "ipxe.efi",
"next-server": "__SERVERIP__"
},
{
"name": "Legacy",
"test": "substring(option[60].hex,0,20) == 'PXEClient:Arch:00000'",
"boot-file-name": "undionly.kpxe",
"next-server": "__SERVERIP__"
}
]
}
}

View File

@ -1,12 +0,0 @@
[ogboot]
user = opengnsys
group = www-data
listen = /var/run/php/php8.3-fpm-ogboot.sock
listen.owner = opengnsys
listen.group = www-data
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

View File

@ -1,3 +0,0 @@
opengnsys ALL=(ALL) NOPASSWD: /opt/bin/oglivecli
opengnsys ALL=(root) NOPASSWD: /usr/bin/chmod, /usr/bin/chown, /usr/bin/md5sum, /usr/bin/smbpasswd, /usr/bin/cat, /usr/bin/tee, /usr/bin/sed, /usr/bin/gzip, /usr/bin/lz4, /usr/bin/cpio, /usr/bin/find, /bin/tee, /usr/bin/dd, /usr/bin/mkfs.ext4, /usr/bin/rsync
opengnsys ALL=(root) NOPASSWD: __OGBOOT_TARGET__/lib/*.iso /mnt

View File

@ -0,0 +1,11 @@
[Unit]
Description=oglive Daemon Service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/ogboot/bin/oglive_daemon.py
Restart=always
User=root
[Install]
WantedBy=multi-user.target

View File

@ -242,8 +242,6 @@ def og_boot_create_dirs():
os.makedirs("/opt/opengnsys", mode=0o775, exist_ok=True)
subprocess.run(["chmod", "775", "/opt/opengnsys"])
os.makedirs(INSTALL_OGBOOT_TARGET, mode=0o775, exist_ok=True)
api_dir = os.path.join(INSTALL_OGBOOT_TARGET, "api")
os.makedirs(api_dir, mode=0o775, exist_ok=True)
# Cambiar el propietario de los directorios
subprocess.run(["chown", "-R", "opengnsys:opengnsys", INSTALL_OGBOOT_TARGET])
@ -258,14 +256,11 @@ def og_boot_symfony_install():
logger.info("Creating Symfony application skeleton...")
try:
api_dir = os.path.join(INSTALL_OGBOOT_TARGET, "api")
os.makedirs(api_dir, exist_ok=True) # Asegurar que el directorio api existe
# Cambio de .env y composer.json bajo /api
api_source = os.path.join(REPO_DIR, "api")
env_src = os.path.join(api_source, ".env")
composer_src = os.path.join(api_source, "composer.json")
env_dest = os.path.join(api_dir, ".env")
composer_dest = os.path.join(api_dir, "composer.json")
# Copiar los archivos .env y composer.json primero
env_src = os.path.join(f"{REPO_DIR}", ".env")
composer_src = os.path.join(f"{REPO_DIR}", "composer.json")
env_dest = os.path.join(f"{INSTALL_OGBOOT_TARGET}", ".env")
composer_dest = os.path.join(f"{INSTALL_OGBOOT_TARGET}", "composer.json")
shutil.copy(env_src, env_dest)
shutil.copy(composer_src, composer_dest)
@ -301,32 +296,25 @@ def og_boot_symfony_install():
def og_boot_copy_files():
api_dir = os.path.join(INSTALL_OGBOOT_TARGET, "api")
api_source = os.path.join(REPO_DIR, "api")
# api/bin que contendría los scripts composer y console de symfony
bin_api_source = os.path.join(api_source, "bin")
bin_api_dest = os.path.join(api_dir, "bin")
# api/bin que contendría los scripts oglivecli y setsmbpass
bin_source = os.path.join(REPO_DIR, "bin")
bin_dest = os.path.join(INSTALL_OGBOOT_TARGET, "bin")
src_source = os.path.join(REPO_DIR, "src")
src_dest = os.path.join(INSTALL_OGBOOT_TARGET, "src")
config_source = os.path.join(REPO_DIR, "config")
config_dest = os.path.join(INSTALL_OGBOOT_TARGET, "config")
src_source = os.path.join(api_source, "src")
src_dest = os.path.join(api_dir, "src")
config_source = os.path.join(api_source, "config")
config_dest = os.path.join(api_dir, "config")
# lib va fuera de /api
lib_source = os.path.join(REPO_DIR, "lib")
lib_dest = os.path.join(INSTALL_OGBOOT_TARGET, "lib")
#os.makedirs("/tmp/opt", exist_ok=True)
#subprocess.run(["chown", "-R", "ogboot:ogboot", "/tmp/opt"])
if os.path.exists(bin_dest):
shutil.rmtree(bin_dest)
shutil.copytree(bin_source, bin_dest)
if os.path.exists(bin_api_dest):
shutil.rmtree(bin_api_dest)
shutil.copytree(bin_api_source, bin_api_dest)
if os.path.exists(src_dest):
shutil.rmtree(src_dest)
shutil.copytree(src_source, src_dest)
@ -339,27 +327,25 @@ def og_boot_copy_files():
shutil.rmtree(lib_dest)
shutil.copytree(lib_source, lib_dest)
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "etc"), mode=0o775, exist_ok=True)
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "client"), mode=0o775, exist_ok=True)
public_dir = os.path.join(api_dir, "public")
os.makedirs(public_dir, mode=0o775, exist_ok=True)
os.makedirs(os.path.join(INSTALL_OGBOOT_TARGET, "public"), mode=0o775, exist_ok=True)
subprocess.run(["chmod", "-R", "775", INSTALL_OGBOOT_TARGET])
subprocess.run(["chown", "-R", "opengnsys:opengnsys", INSTALL_OGBOOT_TARGET])
def og_boot_composer_install():
api_dir = os.path.join(INSTALL_OGBOOT_TARGET, "api")
result = subprocess.run(
["sudo", "-u", "opengnsys", "composer", "install", "--no-interaction", "--working-dir", api_dir]
)
# Ejecutar Composer como el usuario 'opengnsys' para instalar el proyecto Symfony
result = subprocess.run(["sudo", "-u", "opengnsys", "composer", "install", "--no-interaction", "--working-dir", INSTALL_OGBOOT_TARGET])
if result.returncode != 0:
logger.error("Error creating Symfony project using Composer")
return
# Ejecutar Composer como el usuario 'opengnsys' para actualizar el paquete doctrine/dbal
result = subprocess.run(["sudo", "-u", "opengnsys", INSTALL_OGBOOT_TARGET+"/api/bin/composer.phar", "update", "doctrine/dbal", "--working-dir", api_dir])
result = subprocess.run(["sudo", "-u", "opengnsys", INSTALL_OGBOOT_TARGET+"/bin/composer.phar", "update", "doctrine/dbal", "--working-dir", INSTALL_OGBOOT_TARGET])
if result.returncode != 0:
logger.error("Error updating doctrine/dbal package using Composer")
return
subprocess.call(["chown", "-R", "opengnsys:opengnsys", f"{api_dir}/public"])
subprocess.call(["chown", "-R", "opengnsys:opengnsys", f"{INSTALL_OGBOOT_TARGET}/public"])
logger.info("Application skeleton created.")
@ -630,16 +616,16 @@ def setup_nginx():
ip_address_server = OGBOOT_IP
port_address_server = OGBOOT_PORT
php_version = get_php_fpm_version()
api_dir = os.path.join(INSTALL_OGBOOT_TARGET, "api")
# Leer y modificar la plantilla de configuración de nginx
template_path = os.path.join(REPO_DIR, "etc/nginxServer.conf.tmpl")
with open(template_path, 'r') as nginx_file:
nginx_content = nginx_file.read()
nginx_content = nginx_content.replace("__SERVERIP__", ip_address_server)
nginx_content = nginx_content.replace("__PORT__", port_address_server)
nginx_content = nginx_content.replace("__PHPVERSION__", php_version)
nginx_content = nginx_content.replace("__ROOT__", api_dir)
nginx_content = nginx_content.replace("__ROOT__", INSTALL_OGBOOT_TARGET)
nginx_content = nginx_content.replace("__TFTPPATH__", f"{INSTALL_OGBOOT_TARGET}/tftpboot")
# Ruta de destino para la configuración de nginx

View File

@ -1447,7 +1447,6 @@ public function getBootFiles(): JsonResponse
* @OA\Property(property="mac", type="string", example="00:50:56:22:11:12"),
* @OA\Property(property="template_name", type="string", example="mi_plantilla.ipxe"),
* @OA\Property(property="server_ip", type="string", example="192.168.2.1"),
* @OA\Property(property="server_pxe_port", type="string", example="8082"),
* @OA\Property(property="oglivedir", type="string", example="ogLive")
* )
* ),
@ -1485,6 +1484,7 @@ public function createBootFile(Request $request): JsonResponse
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$data = json_decode($request->getContent(), true);
$templateName = $data['template_name'] ?? null;
$mac = $this->validateAndFormatMac($data['mac'] ?? null);
//Si nos pasan el puerto se lo quitamos ya que server_ip siempre tirara por Samba
@ -1492,14 +1492,6 @@ public function createBootFile(Request $request): JsonResponse
if ($serverIp && strpos($serverIp, ':') !== false) {
$serverIp = explode(':', $serverIp)[0];
}
//Declaramos serverPxePort que lo usaremos para la llamada por http
$serverPxePort = $data['server_pxe_port'] ?? null;
$serverIpPort = $serverIp;
if (!empty($serverPxePort)) {
$serverIpPort .= ':' . $serverPxePort;
}
$ogLiveDir = $data['oglivedir'] ?? 'ogLive';
// Verificación de los campos obligatorios
@ -1537,7 +1529,6 @@ public function createBootFile(Request $request): JsonResponse
$parameters = [
'LANG' => $data['lang'] ?? 'es_ES.UTF-8',
'ip' => $data['ip'] ?? '',
'server_pxe_port' => $data['server_pxe_port'] ?? '',
'router' => $data['router'] ?? '',
'netmask' => $data['netmask'] ?? '',
'computer_name' => $data['computer_name'] ?? '',
@ -1590,7 +1581,7 @@ public function createBootFile(Request $request): JsonResponse
}
// Construcción de los argumentos del kernel
$kernelArgs = 'ro boot=oginit quiet splash irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogtmpfs=15 ' .
$kernelArgs = 'ro boot=oginit quiet splash irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=true ogdebug=true ogtmpfs=15 ' .
'oglivedir=${ISODIR}' . ' ' .
'LANG=' . $parameters['LANG'] . ' ' .
'ip=' . $parameters['ip'] . ':' . $serverIp . ':' . $parameters['router'] . ':' . $parameters['netmask'] . ':' . $parameters['computer_name'] . ':' . $parameters['netiface'] . ':none ' .
@ -1609,7 +1600,12 @@ public function createBootFile(Request $request): JsonResponse
(is_numeric($parameters['resolution']) && $parameters['resolution'] <= 999 ? 'vga=' . $parameters['resolution'] :
(strpos($parameters['resolution'], ':') !== false ? 'video=' . $parameters['resolution'] : ' ' . $parameters['resolution']));
// Esta será llamada a http para arrancar kernel e imagen de inicialización
// Si lo requiriese debe llevar puerto ya que se comunica con nginx
$serverIpPort = $this->ogBootIP;
if (!empty($this->ogBootPort)) {
$serverIpPort .= ':' . $this->ogBootPort;
}
// Extraer solo el nombre del directorio si contiene una ruta completa PROVISIONAL
if (strpos($ogLiveDir, '/') !== false) {
$ogLiveDir = basename($ogLiveDir);
@ -1646,65 +1642,6 @@ public function createBootFile(Request $request): JsonResponse
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return new JsonResponse(['error' => 'FAILED_TO_CREATE_PXE_FILE', 'message' => 'Error al crear el archivo PXE'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
$templateCacheDir = $this->tftpbootDir . '/menu.lst';
$pxeFileName = '01-' . $mac;
$pxeFilePath = $templateCacheDir . '/' . $pxeFileName;
// Generar archivo si la plantilla es oglives cache o menu
if ($templateName === 'ogliveCache' || $templateName === 'menu') {
if ($templateName === 'ogliveCache') {
$templateCachePath = $templateCacheDir . '/templateCache';
} elseif ($templateName === 'menu') {
$templateCachePath = $templateCacheDir . '/templateMenu';
}
$templateCacheContent = file_get_contents($templateCachePath);
$grubContent = str_replace(
['__INFOHOST__', '__OGLIVE__'],
[$kernelArgs, basename($ogLiveDir)],
$templateCacheContent
);
}
// Generar archivo si la plantilla es de tipo disco/partición
elseif (in_array($templateName, ['firstDisk_firstPartition', 'firstDisk_secondPartition', 'firstDisk_thirdPartition'])) {
$templateDiskPath = $templateCacheDir . '/templateDisk';
$templateDiskContent = file_get_contents($templateDiskPath);
// Determinar DISK, PART y DISKPART en función del templateName
$map = [
'firstDisk_firstPartition' => ['disk' => '01', 'part' => '01', 'diskpart' => '(hd0,gpt1)'],
'firstDisk_secondPartition' => ['disk' => '01', 'part' => '02', 'diskpart' => '(hd0,gpt1)'],
'firstDisk_thirdPartition' => ['disk' => '01', 'part' => '03', 'diskpart' => '(hd0,gpt1)'],
];
$diskInfo = $map[$templateName];
// Sustituir variables en plantilla
$grubContent = str_replace(
['__DISK__', '__PART__', '__DISKPART__'],
[$diskInfo['disk'], $diskInfo['part'], $diskInfo['diskpart']],
$templateDiskContent
);
}
// En cualquier otro caso, no se hace nada
else {
return new JsonResponse(['success' => 'NO_TEMPLATE_ACTION', 'message' => 'No se requiere generar archivo PXE'], Response::HTTP_OK);
}
// Escribir el archivo PXE final (común a ambos casos)
if (file_put_contents($pxeFilePath, $grubContent) === false) {
$httpCode = '500';
$this->logger->error(json_encode([
'severity' => 'ERROR',
'operation' => $operation,
'component' => $component,
'http_code' => $httpCode,
'desc' => 'Failed to create PXE boot file.'
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return new JsonResponse(['error' => 'FAILED_TO_CREATE_PXE_FILE', 'message' => 'Error al crear el archivo de arranque PXE'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
$httpCode = '200';
$this->logger->info(json_encode([
'severity' => 'INFO',

View File

@ -30,8 +30,8 @@ class CurlRequestService
public function callOgLive($parameter)
{
// Ruta completa al script oglivecli
// $ogLiveCliPath = sprintf("%s/bin/oglivecli", dirname(dirname(dirname(__DIR__))));
$ogLiveCliPath = sprintf("%s/../../../../bin/oglivecli", __DIR__);
$ogLiveCliPath = sprintf("%s/bin/oglivecli", dirname(dirname(dirname(__DIR__))));
// Dividir el parámetro en acción y argumentos
$args = array_map('trim', explode(' ', $parameter));
$action = array_shift($args);

View File

@ -1,19 +0,0 @@
cat grub.cfg
##NO-TOCAR-ESTA-LINEA ogLive
set timeout=0
set timeout_style=hidden
echo ">>> GRUB lanzador detectando MAC..."
sleep 1
echo ">>> MAC detectada: ${net_default_mac}"
sleep 1
echo ">>> Intentando cargar menú específico: /menu.lst/01-${net_default_mac}"
sleep 1
configfile /menu.lst/01-${net_default_mac}
echo ">>> No se pudo cargar /menu.lst/01-${net_default_mac}"
sleep 5
reboot

Binary file not shown.

View File

Binary file not shown.

View File

@ -0,0 +1,36 @@
#!ipxe
# Configuración inicial
set ISODIR ogLive
:bios_boot_first_second
echo "Booting firstboot and secondboot flow using GRUB4DOS..."
# Pasar control a GRUB4DOS para manejar firstboot y secondboot
chain tftp://__SERVERIP__/tftpboot/grub.exe --config-file="
# Configurar ISODIR
timeout 0
set ISODIR=${ISODIR};
# Firstboot
find --set-root --ignore-floppies --ignore-cd /ogboot.me checkrange 0x07 parttype > nul;
cmp /ogboot.me /ogboot.firstboot || goto secondboot;
write /ogboot.firstboot iniciado;
pause Firstboot passed. File updated. Press any key to continue...;
chainloader +1;
boot;
# Secondboot
:secondboot
find --set-root --ignore-floppies --ignore-cd /ogboot.me checkrange 0x07 parttype > nul;
cmp /ogboot.me /ogboot.secondboot || goto fallback;
write /ogboot.secondboot iniciado;
pause Secondboot passed. File updated. Press any key to continue...;
chainloader +1;
boot;
# Fallback
:fallback
pause Firstboot and Secondboot failed. Press any key to continue...;
quit;
" || echo "Failed to execute GRUB fallback sequence."

View File

@ -10,6 +10,6 @@ exit
:uefi_boot
echo "Running in UEFI mode - Booting first disk, first partition"
chain http://__SERVERIP__/tftpboot/grubx64.efi
sanboot --no-describe --drive 0 --filename \EFI\Part-01-01\Boot\ogloader.efi || echo "Failed to boot in UEFI mode"
exit

View File

@ -10,7 +10,6 @@ exit
:uefi_boot
echo "Running in UEFI mode - Booting first disk, second partition"
chain http://__SERVERIP__/tftpboot/grubx64.efi
sanboot --no-describe --drive 0 --filename \EFI\Part-01-02\Boot\ogloader.efi || echo "Failed to boot in UEFI mode"
exit

View File

@ -10,7 +10,6 @@ exit
:uefi_boot
echo "Running in UEFI mode - Booting first disk, third partition"
chain http://__SERVERIP__/tftpboot/grubx64.efi
sanboot --no-describe --drive 0 --filename \EFI\Part-01-03\Boot\ogloader.efi || echo "Failed to boot in UEFI mode"
exit

View File

@ -1,68 +0,0 @@
#!ipxe
# Detectar si se está ejecutando en modo UEFI o BIOS
iseq ${platform} efi && goto uefi_boot || goto bios_boot
:bios_boot
set timeout 3000
set esc:hex 1b
set bold ${esc:string}[1m
set boldoff ${esc:string}[22m
set fg_cya ${esc:string}[36m
set fg_whi ${esc:string}[37m
set ISODIR __OGLIVE__
set default 0
set kernelargs __INFOHOST__
:main_menu
clear menu
menu ${bold}${fg_cya}OpenGnsys iPXE Disk Boot Menu${boldoff}
item part1 FirstDisk-FirstPartition
item part2 FirstHardDisk-SecondPartition
item part3 FirstDisk-ThirdPartition
item ogcache OpenGnsys CACHE
item ognet OpenGnsys NET
item ognetdef OpenGnsys NET Default
item shell iPXE Shell
choose --timeout ${timeout} --default ogcache target && goto ${target}
:part1
echo Booting FirstDisk-FirstPartition...
chain http://__SERVERIP__/tftpboot/grub.exe --config-file="timeout 1; title FirstDisk-FirstPartition; root (hd0,0); chainloader (hd0,0)+1; boot" || echo Failed to boot part1
exit
:part2
echo Booting FirstHardDisk-SecondPartition...
chain http://__SERVERIP__/tftpboot/grub.exe --config-file="timeout 1; title FirstHardDisk-SecondPartition; root (hd0,1); chainloader (hd0,1)+1; boot" || echo Failed to boot part2
exit
:part3
echo Booting FirstDisk-ThirdPartition...
chain http://__SERVERIP__/tftpboot/grub.exe --config-file="timeout 1; title FirstDisk-ThirdPartition; root (hd0,2); chainloader (hd0,2)+1; boot" || echo Failed to boot part3
exit
:ogcache
echo Booting OpenGnsys-CACHE...
chain http://__SERVERIP__/tftpboot/grub.exe --config-file="timeout 1; title OpenGnsys-CACHE; find --set-root /boot/__OGLIVE__/ogvmlinuz; kernel /boot/__OGLIVE__/ogvmlinuz ogactiveadmin=true ogdebug=true __INFOHOST__; initrd /boot/__OGLIVE__/oginitrd.img; boot"
:ognet
echo Booting OpenGnsys-NET...
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ogactiveadmin=false ogdebug=false ${kernelargs} || goto fallback
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot
:ognetdef
echo Booting OpenGnsys-NET Default...
set ISODIR ogLive
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ogactiveadmin=false ogdebug=false ${kernelargs}
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot
:shell
echo Launching iPXE shell...
shell
:uefi_boot
echo "Running in UEFI mode - Booting Menu"
chain http://__SERVERIP__/tftpboot/grubx64.efi
exit

View File

@ -7,13 +7,13 @@ set default 0
set kernelargs __INFOHOST__
# Menú de entrada para seleccionar OgLive
:try_iso
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ogdebug=false ${kernelargs} || goto fallback
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ${kernelargs} || goto fallback
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot
:fallback
echo "OgLive default"
set ISODIR ogLive
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ogdebug=false ${kernelargs}
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ${kernelargs}
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot

View File

@ -1,19 +0,0 @@
#!ipxe
set timeout 0
set timeout-style hidden
set ISODIR __OGLIVE__
set default 0
set kernelargs __INFOHOST__
# Menú de entrada para seleccionar OgLive
:try_iso
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ogactiveadmin=true ogdebug=true ${kernelargs} || goto fallback
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot
:fallback
echo "OgLive default"
set ISODIR ogLive
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ogactiveadmin=true ogdebug=true ${kernelargs}
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot

View File

@ -1,53 +0,0 @@
#!ipxe
#Template: ogliveBios
# Detectar si se está ejecutando en modo UEFI o BIOS
iseq ${platform} efi && goto uefi_boot || goto bios_boot
:uefi_boot
set timeout 0
set timeout-style hidden
set ISODIR __OGLIVE__
set default 0
set kernelargs ogactiveadmin=true ogdebug=true __INFOHOST__
# Menú de entrada para seleccionar OgLive
:try_iso
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ${kernelargs} || goto fallback
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot
:fallback
echo "OgLive default"
set ISODIR ogLive
kernel http://__SERVERIP__/tftpboot/${ISODIR}/ogvmlinuz ${kernelargs}
initrd http://__SERVERIP__/tftpboot/${ISODIR}/oginitrd.img
boot
:bios_boot
set PIPE |
set SERVERIP __SERVERIP__
set ISODIR __OGLIVE__
set kernelargs ogactiveadmin=true ogdebug=true __INFOHOST__
set CFG_PREFIX default saved; timeout 1; hiddenmenu; fallback 1 2 3 4; set ISODIR=${ISODIR};
set CFG_FIRSTBOOT title firsboot; find --set-root --ignore-floppies --ignore-cd /ogboot.me checkrange 0x07 parttype > nul; cmp /ogboot.me /ogboot.firstboot ${PIPE}${PIPE} ls FALLBACK; write /ogboot.firstboot iniciado; chainloader +1; boot;
set CFG_SECONDBOOT title secondboot; find --set-root --ignore-floppies --ignore-cd /ogboot.me checkrange 0x07 parttype > nul; cmp /ogboot.me /ogboot.secondboot; write /ogboot.secondboot iniciado; chainloader +1; boot;
set CFG_OGCACHE title OpenGnsys-CACHE; find --set-root --ignore-floppies --ignore-cd /boot/%ISODIR%/ogvmlinuz; kernel /boot/%ISODIR%/ogvmlinuz ogactiveadmin=false ogdebug=false ogupdateinitrd=true ${kernelargs}; initrd /boot/%ISODIR%/oginitrd.img; boot;
#set CFG_OGNET title OpenGnsys-NET; kernel (pd)/%ISODIR%/ogvmlinuz ${kernelargs}; initrd (pd)/%ISODIR%/oginitrd.img; boot;
#set CFG_OGNET_DEFAULT title OpenGnsys-NET default; kernel (pd)/ogLive/ogvmlinuz ${kernelargs}; initrd (pd)/ogLive/oginitrd.img; boot;
set default 0
# Menú de entrada para seleccionar OgLive
:try_iso
chain http://${SERVERIP}/tftpboot/grub.exe --config-file="${CFG_PREFIX} ${CFG_FIRSTBOOT} ${CFG_SECONDBOOT} ${CFG_OGCACHE}"
boot
:fallback
echo "OgLive default"
set ISODIR ogLive
kernel http://${SERVERIP}/tftpboot/${ISODIR}/ogvmlinuz ogactiveadmin=true ogdebug=true ${kernelargs}
initrd http://${SERVERIP}/tftpboot/${ISODIR}/oginitrd.img
boot

View File

@ -1,16 +1,17 @@
#!ipxe
# Detectar si se está ejecutando en modo UEFI o BIOS
iseq ${platform} efi && goto uefi_boot || goto bios_boot
# Configuración inicial
set ISODIR __OGLIVE__
set default 0
set kernelargs __INFOHOST__
:bios_boot_cache
echo "Booting ogLive from cache..."
:bios_boot
echo "Running in BIOS mode"
# Si el cliente es BIOS, arranca el grub.pxe
chain http://__SERVERIP__/tftpboot/grub.exe --config-file="timeout 1; title OpenGnsys-CACHE; find --set-root /boot/__OGLIVE__/ogvmlinuz; kernel /boot/__OGLIVE__/ogvmlinuz ogactiveadmin=true ogdebug=true __INFOHOST__; initrd /boot/__OGLIVE__/oginitrd.img; boot"
exit
:uefi_boot
echo "Running in UEFI mode"
# Si el cliente es UEFI, arranca el grubx64.efi
chain http://__SERVERIP__/tftpboot/grubx64.efi
exit
chain tftp://__SERVERIP__/tftpboot/grub.exe --config-file="
timeout 0
set ISODIR=${ISODIR};
find --set-root --ignore-floppies --ignore-cd /boot/${ISODIR}/ogvmlinuz;
kernel /boot/${ISODIR}/ogvmlinuz ${kernelargs};
initrd /boot/${ISODIR}/oginitrd.img;
boot;
" || echo "Failed to boot ogLive from cache."

View File

@ -1,25 +0,0 @@
##NO-TOCAR-ESTA-LINEA ogLive
set timeout=0
set timeout_style=hidden
echo ">>> Iniciando GRUB embebido"
set ISODIR=__OGLIVE__
echo ">>> ISODIR definido como: $ISODIR"
echo ">>> Buscando ogvmlinuz en particiones locales..."
search --file --set=root /boot/$ISODIR/ogvmlinuz
if [ -n "$root" ]; then
echo ">>> OgLive encontrado en CACHE en $root"
echo ">>> Cargando kernel..."
linux /boot/$ISODIR/ogvmlinuz __INFOHOST__
echo ">>> Cargando initrd..."
initrd /boot/$ISODIR/oginitrd.img
echo ">>> Ejecutando boot"
boot
else
echo ">>> ogvmlinuz no encontrado en CACHE."
echo ">>> Reintentando en red o abortando..."
reboot
fi

View File

@ -1,6 +0,0 @@
if ! search --file --set root /Part-__DISK__-__PART__; then
search --file --set root /EFI/Part-__DISK__-__PART__/Boot/ogloader.efi
fi
search --file --set rootEFI /EFI/Part-__DISK__-__PART__/Boot/ogloader.efi
chainloader ($rootEFI)/EFI/Part-__DISK__-__PART__/Boot/ogloader.efi
boot

View File

@ -1,94 +0,0 @@
set timeout=30
set detectado='no'
# Compruebo si existen distintos cargadores.
echo "Searching Grub"
set ISODIR=__OGLIVE__
search --file --set rootGrub /EFI/grub/Boot/grubx64.efi
if [ "$rootGrub" != "" ]; then
set detectado='si'
menuentry "Grub" {
root="$rootGrub"
chainloader /EFI/grub/Boot/grubx64.efi
}
fi
echo "Searching rEFInd"
search --file --set rootRefind /EFI/refind/shimx64.efi.signed
if [ "$rootRefind" != "" ]; then
menuentry "rEFInd" {
root="$rootRefind"
chainloader /EFI/refind/shimx64.efi.signed
}
fi
if ! search --file --set rootP2 /Part-01-02; then
search --file --set rootP2 /EFI/Part-01-02/Boot/ogloader.efi
fi
search --file --set rootEFI /EFI/Part-01-02/Boot/ogloader.efi
if [ "$rootP2" != "" ]; then
set detectado='si'
menuentry "Part-01-02" {
root="$rootP2"
chainloader ($rootEFI)/EFI/Part-01-02/Boot/ogloader.efi
}
fi
if ! search --file --set rootP3 /Part-01-03; then
search --file --set rootP3 /EFI/Part-01-03/Boot/ogloader.efi
fi
search --file --set rootEFI /EFI/Part-01-03/Boot/ogloader.efi
if [ "$rootEFI" != "" ]; then
set detectado='si'
menuentry "Part-01-03" {
root="$rootP3"
chainloader ($rootEFI)/EFI/Part-01-03/Boot/ogloader.efi
}
fi
echo "Searching Windows"
search --file --set rootMS /EFI/Microsoft/Boot/bootmgfw.efi
if [ "$rootMS" != "" ]; then
set detectado='si'
menuentry "Windows" {
root="$rootMS"
chainloader /EFI/Microsoft/Boot/bootmgfw.efi
}
fi
echo "Searching Ubuntu"
search --file --set rootUb /EFI/ubuntu/grubx64.efi
if [ "$rootUb" != "" ]; then
set detectado='si'
menuentry "Ubuntu"{
root="$rootUb"
chainloader /EFI/ubuntu/grubx64.efi
}
fi
echo "Buscando ogvmlinuz en particiones locales..."
search --file --set=rootOgCache /boot/$ISODIR/ogvmlinuz
if [ "$rootOgCache" != "" ]; then
set detectado='si'
menuentry "Oglive Cache"{
root="$rootOgCache"
linux /boot/$ISODIR/ogvmlinuz __INFOHOST__
initrd /boot/$ISODIR/oginitrd.img
}
fi
# Si no hay ningún sistema operativo muestro mensaje.
if [ $detectado == 'no' ]; then
menuentry "OpenGnsys no ha detectado ningún sistema operativo" {
# para evitar mensajes de error.
set root="(hd0,gpt1)"
}
fi