From b397c7aaa96f300aaecf8ae30620549a2b91d37b Mon Sep 17 00:00:00 2001 From: lgromero Date: Thu, 26 Sep 2024 12:34:32 +0200 Subject: [PATCH] refs #404 A lot of changes, in oglivecli removes some sudos, in installation adds new line in fstab to mount oglive iso, adds ogboot to disk group to use loop devices, now we are downloading ipxe repo from github and executing make, adds a new php-fpm ogboot pool with ogboot permissions and not use www pool, changes nginx template to use the ogboot pool. For last depure core, deletes some comments and useless prints --- bin/oglivecli | 6 +- bin/setsmbpass | 8 +- config/routes.yaml | 2 +- etc/nginxServer.conf.tmpl | 4 +- installer/ogboot_installer.py | 173 +++++++++++++++++++++++----------- 5 files changed, 128 insertions(+), 65 deletions(-) diff --git a/bin/oglivecli b/bin/oglivecli index 3d4f280..efe44ac 100755 --- a/bin/oglivecli +++ b/bin/oglivecli @@ -152,12 +152,10 @@ function download() { TARGETFILE="$DOWNLOADDIR/$OGLIVEFILE" trap "rm -f $TARGETFILE" 1 2 3 6 9 15 curl -k --retry 5 --retry-delay 5 "$download_url" -o "$TARGETFILE" || raiseError download "No se pudo descargar \"$OGLIVEFILE\"." - - # Validar que el archivo descargado sea un ISO válido y que sea un ogLive. if [ -f "$TARGETFILE" ]; then local file_type=$(file -b "$TARGETFILE") if [[ "$file_type" =~ "ISO 9660" ]] && [[ "$file_type" =~ "ogClient" ]]; then - install "$OGLIVEFILE" + install "$OGLIVEFILE" else raiseError download "El archivo descargado no es un ogLive ISO válido." fi @@ -386,7 +384,7 @@ function install() { rmdir $TMPDIR_SQUASHFS || sudo rm -rf $TMPDIR_SQUASHFS fi echo "finished mount squashfs" - sudo rm -f "$OGLIVEFILE" + # sudo rm -f "$OGLIVEFILE" CHECKSUM_FILE="$OGLIVEDIR/ogclient.sqfs.sum" if [ -f "$CHECKSUM_FILE" ]; then OGLIVEID=$(cat "$CHECKSUM_FILE") diff --git a/bin/setsmbpass b/bin/setsmbpass index a4e8fe2..a1bb2ee 100755 --- a/bin/setsmbpass +++ b/bin/setsmbpass @@ -1,8 +1,8 @@ #!/bin/bash PROG=$(basename $0) -OPENGNSYS=${OPENGNSYS:-"/opt/opengnsys"} -OGCFGFILE=$OPENGNSYS/etc/opengnsys.json +OPENGNSYS=${OPENGNSYS:-"/opt/ogboot"} +OGCFGFILE=$OPENGNSYS/etc/ogboot_samba.json SAMBAUSER="opengnsys" # Usuario por defecto. TFTPDIR=$OPENGNSYS/tftpboot INITRD=oginitrd.img @@ -130,9 +130,9 @@ EOT echo "$PROG: Aviso: no se ha modificado la clave del cliente \"$OGLIVE\"." fi echo "intentando borrar $TMPDIR" - sudo rm -fr $TMPDIR + rm -fr $TMPDIR echo "Calcular suma de comprobación" - sudo md5sum "$CLIENTINITRD" | cut -f1 -d" " | sudo tee "$CLIENTINITRD.sum" > /dev/null + md5sum "$CLIENTINITRD" | cut -f1 -d" " | sudo tee "$CLIENTINITRD.sum" > /dev/null let CHANGES++ else echo "$PROG: Cliente \"$OGLIVE\" no accesible." diff --git a/config/routes.yaml b/config/routes.yaml index 274a742..fe3378b 100644 --- a/config/routes.yaml +++ b/config/routes.yaml @@ -2,6 +2,6 @@ # path: / # controller: App\Controller\DefaultController::index app.swagger_ui: - path: /api/doc + path: /ogboot/api/doc methods: GET defaults: { _controller: nelmio_api_doc.controller.swagger_ui } diff --git a/etc/nginxServer.conf.tmpl b/etc/nginxServer.conf.tmpl index 0d36042..1f1c458 100644 --- a/etc/nginxServer.conf.tmpl +++ b/etc/nginxServer.conf.tmpl @@ -18,7 +18,7 @@ server { # Bloque para manejar las solicitudes a index.php location ~ ^/index.php(/|$) { include fastcgi_params; - fastcgi_pass unix:/run/php/php__PHPVERSION__-fpm.sock; # Asegúrate de que esto sea correcto + fastcgi_pass unix:/run/php/php__PHPVERSION__-fpm-ogboot.sock; # Asegúrate de que esto sea correcto fastcgi_split_path_info ^(.+\.php)(/.*)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; @@ -35,7 +35,7 @@ server { error_log /var/log/nginx/ogboot_error.log; access_log /var/log/nginx/ogboot_access.log; - location /api/doc { + location /ogboot/api/doc { try_files $uri /index.php?$query_string; } diff --git a/installer/ogboot_installer.py b/installer/ogboot_installer.py index 80a8ac7..ecc37ba 100755 --- a/installer/ogboot_installer.py +++ b/installer/ogboot_installer.py @@ -27,7 +27,7 @@ OPENGNSYS_CLIENT_PASSWD = config["ogBootSambaPass"] OSDISTRIB = "" OSVERSION = "" -IPXE_DIR = "/tmp/ipxe" +IPXE_DIR = "/tmp/ogboot_ipxe" WORKDIR ="/tmp/ogboot_installer" DEFAULTDEV = "" @@ -298,11 +298,9 @@ def og_boot_copy_files(): lib_source = os.path.join(WORKDIR, "ogboot/lib") lib_dest = os.path.join(INSTALL_OGBOOT_TARGET, "lib") - # Crear el directorio /tmp/opt - os.makedirs("/tmp/opt") + os.makedirs("/tmp/opt", exist_ok=True) - # Cambiar el propietario del directorio - subprocess.run(["chown", "ogboot:ogboot", "/tmp/opt"]) + subprocess.run(["chown", "-R", "ogboot:ogboot", "/tmp/opt"]) if os.path.exists(bin_dest): shutil.rmtree(bin_dest) @@ -376,6 +374,38 @@ def backupFile(file): shutil.copy2(file, backup_file) logger.info(f"Backup of {file} successful") +# Obtener la UID y GID del usuario ogboot +def get_ogboot_uid_gid(): + try: + user_info = pwd.getpwnam('ogboot') + uid = user_info.pw_uid + gid = user_info.pw_gid + return uid, gid + except KeyError: + raise Exception("El usuario 'ogboot' no existe.") + +# Añadir líneas al fstab +def add_fstab_entries(uid, gid): + try: + fstab_entries = [ + f'/opt/ogboot/lib/oglive.iso /tmp/opt/ogboot/lib/ogLive iso9660 loop,ro,users,uid={uid},gid={gid} 0 0\n', + f'/var/lib/tftpboot/ogLive/ogclient.sqfs /tmp/ogclient_mount squashfs loop,ro,user 0 0\n' + ] + + with open('/etc/fstab', 'a') as fstab: + fstab.writelines(fstab_entries) + logger.info("Entradas añadidas a /etc/fstab correctamente.") + + except IOError: + raise Exception("Error al escribir en /etc/fstab.") + +# Añadir el usuario ogboot al grupo disk +def add_user_to_disk_group(): + try: + subprocess.run(['usermod', '-aG', 'disk', 'ogboot'], check=True) + logger.info("Usuario 'ogboot' añadido al grupo 'disk' correctamente.") + except subprocess.CalledProcessError: + raise Exception("Error al añadir el usuario 'ogboot' al grupo 'disk'.") def tftpConfigure(): global INETDSERV @@ -398,13 +428,13 @@ TFTP_OPTIONS="--secure" logger.info("\t2-Creating and setting permissions for the TFTP directory...") os.makedirs("/var/lib/tftpboot", exist_ok=True) - subprocess.run("sudo chown -R tftp:tftp /var/lib/tftpboot", shell=True, text=True, capture_output=True) - subprocess.run("sudo chmod -R 775 /var/lib/tftpboot", shell=True, text=True, capture_output=True) + subprocess.run("chown -R tftp:tftp /var/lib/tftpboot", shell=True, text=True, capture_output=True) + subprocess.run("chmod -R 775 /var/lib/tftpboot", shell=True, text=True, capture_output=True) logger.info("\t3-Setting permissions for /var/lib/tftpboot directory...") - subprocess.run("sudo systemctl restart tftpd-hpa", shell=True, text=True, capture_output=True) + subprocess.run("systemctl restart tftpd-hpa", shell=True, text=True, capture_output=True) logger.info("Checking tftpd-hpa service status...") - subprocess.run("sudo systemctl status tftpd-hpa", shell=True, text=True, capture_output=True) + subprocess.run("systemctl status tftpd-hpa", shell=True, text=True, capture_output=True) if os.path.exists(TFTPCFGDIR): subprocess.run(["chown", "-R", "tftp:ogboot", TFTPCFGDIR]) @@ -422,7 +452,7 @@ TFTP_OPTIONS="--secure" iso_url = "https://ognproject.evlt.uma.es/trac/downloads/ogLive-focal-5.13.0-27-beta-amd64-r20210706.5b4bf5f.iso" try: result = subprocess.run( - ["sudo", "-u", "ogboot", "/opt/ogboot/bin/oglivecli", "download", iso_url], + ["/opt/ogboot/bin/oglivecli", "download", iso_url], check=True, capture_output=True, text=True @@ -442,7 +472,7 @@ TFTP_OPTIONS="--secure" symlink_target_ogLive = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ogLive" symlink_target_ogclient = f"{INSTALL_OGBOOT_TARGET}/tftpboot/ogclient" if os.path.exists(symlink_target_ogLive): - subprocess.run(["sudo", "chown", "-R", f"tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot"], check=True) + subprocess.run(["chown", "-R", f"tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot"], check=True) os.lchown(symlink_target_ogLive, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid) os.lchown(symlink_target_ogclient, pwd.getpwnam("tftp").pw_uid, pwd.getpwnam("ogboot").pw_gid) logger.info(f"Changing properties for {symlink_target_ogLive} and {symlink_target_ogclient}") @@ -458,7 +488,7 @@ def servicesCompilation(): global WORKDIR hayErrores = 0 process = subprocess.run(["make"], cwd=f"{WORKDIR}/ogboot/sources/clients/ogAdmClient") - shutil.move(f"{WORKDIR}/ogboot/sources/clients/ogAdmClient/ogAdmClient", f"{WORKDIR}/ogboot/client/shared/bin") + shutil.copy2(f"{WORKDIR}/ogboot/sources/clients/ogAdmClient/ogAdmClient", f"{WORKDIR}/ogboot/client/shared/bin") if process.returncode != 0: logger.info(f"{servicesCompilation.__name__}(): error while compiling OpenGnsys Admin Client") hayErrores = 1 @@ -541,52 +571,56 @@ def openGnsysConfigure(): logger.info(f"OpenGnsys config files created.") def mount_NFS(): - global IPXE_DIR, INSTALL_OPENGNSYS_TARGET - if subprocess.call(["sudo", "mount", "-t", "nfs", "ognartefactos.evlt.uma.es:/", "/mnt"]) == 0: - logger.info("Properly mounted NFS system.") + global IPXE_DIR, INSTALL_OGBOOT_TARGET + repo_url = "https://github.com/ipxe/ipxe.git" + clone_dir = "/tmp/ogboot_ipxe" + + # Clonar el repositorio desde Gitea + if os.path.exists(clone_dir): + logger.info(f"Eliminando el directorio {clone_dir} existente") + subprocess.call(["rm", "-rf", clone_dir]) + + logger.info(f"Clonando el repositorio {repo_url}") + if subprocess.call(["git", "-c", "http.sslVerify=false", "clone", repo_url, clone_dir]) == 0: + logger.info("Repositorio clonado correctamente.") else: - logger.error("Could not mount the NFS system.") + logger.error(f"ERROR\tNo se pudo clonar el repositorio {repo_url}.") exit(1) - logger.info("copying tftpboot files") - subprocess.call(["sudo", "cp", "-r", "/mnt/srv/artefactos/ogboot/tftpboot/", "/tmp"]) - if not os.path.exists(IPXE_DIR + "/tftpboot"): - os.makedirs(IPXE_DIR + "/tftpboot") - logger.info("copying ipxe files") - subprocess.call(["sudo", "cp", "-r", "/mnt/srv/artefactos/ogboot/ipxe/", "/tmp"]) - if not os.path.exists(IPXE_DIR + "/src"): - os.makedirs(IPXE_DIR + "/src") - logger.info(f"make to {IPXE_DIR}/src") + + + # Ejecutar el comando make en el directorio src + logger.info(f"Ejecutando make en {IPXE_DIR}/src") os.chdir(f"{IPXE_DIR}/src") - if subprocess.call(["sudo", "make", "-s", "-j", "4"]) == 0: - logger.info(f"Directory {IPXE_DIR}/src correctly mounted.") + if subprocess.call(["make", "-s", "-j", "4"]) == 0: + logger.info(f"Directorio {IPXE_DIR}/src correctamente compilado.") else: - logger.error(f"ERROR\tCould not mount the directory {IPXE_DIR}/src.") + logger.error(f"ERROR\tNo se pudo compilar el directorio {IPXE_DIR}/src.") exit(1) if not os.path.exists("/opt/opengnsys"): os.symlink("/opt/ogboot/", "/opt/opengnsys") logger.info("Symbolic link created successfully.") - if subprocess.call(["sudo", "make", "-s", "bin/undionly.kpxe", f"EMBED={INSTALL_OPENGNSYS_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"]) == 0: + if subprocess.call(["make", "-s", "bin/undionly.kpxe", f"EMBED={INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"]) == 0: logger.info("Boot file mounted correctly.") else: logger.error("Failed to mount boot file.") exit(1) logger.info("Copiando undionly.kpxe con usuario ogboot:") - subprocess.call(["sudo", "cp", "bin/undionly.kpxe", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot"]) - subprocess.call(["sudo", "chown", "ogboot:ogboot", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot"]) + subprocess.call(["cp", "bin/undionly.kpxe", f"{INSTALL_OGBOOT_TARGET}/tftpboot"]) + subprocess.call(["chown", "ogboot:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot"]) logger.info("Generando make de ipxe.efi:") - if subprocess.call(["sudo", "make", "-s", "bin-x86_64-efi/ipxe.efi", f"EMBED={INSTALL_OPENGNSYS_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"]) == 0: + if subprocess.call(["make", "-s", "bin-x86_64-efi/ipxe.efi", f"EMBED={INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/dhcp_boot.ipxe"]) == 0: logger.info("Properly constructed EFI file.") else: logger.error("Could not build EFI file.") exit(1) - subprocess.call(["sudo", "cp", "bin-x86_64-efi/ipxe.efi", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot"]) - subprocess.call(["sudo", "chown", "-R", "tftp:ogboot", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot/"]) - subprocess.run(["sudo", "chmod", "-R", "775", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot/"]) - os.makedirs(f"{INSTALL_OPENGNSYS_TARGET}/tftpboot/ipxe_scripts/templates", exist_ok=True) - subprocess.call(["sudo", "chown", "-R", "tftp:ogboot", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot/ipxe_scripts/templates"]) - subprocess.call(["sudo", "chmod", "-R", "775", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot/ipxe_scripts/templates"]) - subprocess.call(["sudo", "cp", f"{WORKDIR}/ogboot/tftpboot/ipxe_scripts/templates/pxe_default", f"{INSTALL_OPENGNSYS_TARGET}/tftpboot/ipxe_scripts/templates"]) + subprocess.call(["sudo", "cp", "bin-x86_64-efi/ipxe.efi", f"{INSTALL_OGBOOT_TARGET}/tftpboot"]) + subprocess.call(["sudo", "chown", "-R", "tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot/"]) + subprocess.run(["sudo", "chmod", "-R", "775", f"{INSTALL_OGBOOT_TARGET}/tftpboot/"]) + os.makedirs(f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates", exist_ok=True) + subprocess.call(["sudo", "chown", "-R", "tftp:ogboot", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"]) + subprocess.call(["sudo", "chmod", "-R", "775", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"]) + subprocess.call(["sudo", "cp", f"{WORKDIR}/ogboot/tftpboot/ipxe_scripts/templates/pxe_default", f"{INSTALL_OGBOOT_TARGET}/tftpboot/ipxe_scripts/templates"]) def get_ip_address(interface): @@ -766,37 +800,54 @@ def get_php_fpm_version(): exit(1) def modify_php_fpm_config(): - php_version = get_php_fpm_version() + php_version = "8.2" # Establecemos la versión de PHP a 8.2 php_fpm_conf_path = f"/etc/php/{php_version}/fpm/pool.d/www.conf" + new_fpm_conf_path = f"/etc/php/{php_version}/fpm/pool.d/ogboot.conf" + socket_path = f"/run/php/php{php_version}-fpm-ogboot.sock" try: - # Leer el archivo de configuración - with open(php_fpm_conf_path, 'r') as file: + # Copiar www.conf a ogboot.conf + subprocess.run(["sudo", "cp", php_fpm_conf_path, new_fpm_conf_path], check=True) + logger.info(f"Archivo {php_fpm_conf_path} copiado a {new_fpm_conf_path}") + + # Leer el archivo copiado ogboot.conf + with open(new_fpm_conf_path, 'r') as file: config_lines = file.readlines() - + # Modificar las líneas necesarias - with open(php_fpm_conf_path, 'w') as file: + with open(new_fpm_conf_path, 'w') as file: for line in config_lines: - if line.startswith('user ='): + if line.startswith('[www]'): + file.write('[ogboot]\n') # Cambiar el nombre del pool + elif line.startswith('user ='): file.write('user = ogboot\n') elif line.startswith('group ='): file.write('group = ogboot\n') + elif line.startswith('listen ='): + file.write(f'listen = {socket_path}\n') # Cambiar el nombre del socket elif line.startswith('listen.owner ='): file.write('listen.owner = ogboot\n') elif line.startswith('listen.group ='): file.write('listen.group = ogboot\n') else: file.write(line) - - logger.info("PHP-FPM configuration file modified successfully.") - - # Reiniciar el servicio PHP-FPM - subprocess.run(["sudo", "systemctl", "restart", f"php{php_version}-fpm"]) - logger.info("PHP-FPM service restarted successfully.") - except Exception as e: - logger.error(f"An error occurred: {e}") - exit(1) + logger.info(f"Archivo {new_fpm_conf_path} modificado correctamente.") + + # Reiniciar el servicio PHP-FPM + subprocess.run(["sudo", "systemctl", "restart", f"php{php_version}-fpm"], check=True) + logger.info("Servicio PHP-FPM reiniciado correctamente.") + + # Verificar que el socket se ha creado + if os.path.exists(socket_path): + logger.info(f"Socket {socket_path} creado correctamente.") + else: + logger.error(f"El socket {socket_path} no se ha creado.") + exit(1) + + except Exception as e: + logger.error(f"Ocurrió un error: {e}") + exit(1) ############################################################################### ###:::::::::::::::::::::::::::::::: MAIN :::::::::::::::::::::::::::::::::::### @@ -908,6 +959,20 @@ except Exception as e: logger.error(f"Error installing Composer: {e}") exit(1) +try: + logger.info("Obteniendo UID y GID del usuario 'ogboot'.") + uid, gid = get_ogboot_uid_gid() + + logger.info("Añadiendo entradas al archivo /etc/fstab.") + add_fstab_entries(uid, gid) + + logger.info("Añadiendo el usuario 'ogboot' al grupo 'disk'.") + add_user_to_disk_group() + +except Exception as e: + logger.error(f"Error durante la configuración: {e}") + exit(1) + try: logger.info("Configuring tftpd-hpa service.") tftpConfigure()