From 30218828f8ca6696fe9f913cc114ed829f649f20 Mon Sep 17 00:00:00 2001 From: lgromero Date: Tue, 25 Jun 2024 04:40:35 +0200 Subject: [PATCH] refs #437 Fix install output and adds new functions to oglivecli to build endpoint config --- bin/oglive_daemon.py | 19 +- bin/oglivecli | 428 ++++++++++----- .../Controller/OgBootController.php | 503 +++++++----------- .../Service/CurlRequestService.php | 57 +- 4 files changed, 553 insertions(+), 454 deletions(-) diff --git a/bin/oglive_daemon.py b/bin/oglive_daemon.py index 97176a0..ed0b3d5 100644 --- a/bin/oglive_daemon.py +++ b/bin/oglive_daemon.py @@ -12,20 +12,25 @@ 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']: + 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 output: {stdout}') - if process.returncode == 0: - return {"success": True, "output": stdout.strip()} - else: - return {"success": False, "error": stderr.strip()} + 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: diff --git a/bin/oglivecli b/bin/oglivecli index a46e06c..8efc445 100755 --- a/bin/oglivecli +++ b/bin/oglivecli @@ -224,7 +224,6 @@ function search() { list | awk -v d="$1" '{if ($2==d) print $1; if ($1==d) print $2}' | grep . || raiseError notfound "Index/Directory \"$1\"." } -# Show a menu to select and download an ogLive ISO image from the OpenGnsys website. function download() { local OGLIVE NISOS i HTTPCODE ISOREL @@ -265,17 +264,32 @@ function download() { } # Muestra un menú para seleccionar y descargar un archivo ogLive ISO del sitio web de OpenGnsys. function downloadMenu() { - local OGLIVE NISOS i HTTPCODE ISOREL OGLIVE=( $(curl -k --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") ) NISOS=${#OGLIVE[@]} - echo "Descargas disponibles (+ = instalado, * = compatibilidad completa):" + + local downloads=() + for i in $(seq 1 $NISOS); do - [ -e $DOWNLOADDIR/${OGLIVE[i-1]} ] && OGLIVE[i-1]="(+) ${OGLIVE[i-1]}" + local installed=false + local compatible=false + + [ -e $DOWNLOADDIR/${OGLIVE[i-1]} ] && installed=true ISOREL=${OGLIVE[i-1]##*-r}; ISOREL=${ISOREL%%.*} - [ $ISOREL -ge $MINREL ] && OGLIVE[i-1]="(*) ${OGLIVE[i-1]}" - echo "$i) ${OGLIVE[i-1]}" + [ $ISOREL -ge $MINREL ] && compatible=true + + local DATA=$(jq -n \ + --arg id "$i" \ + --arg filename "${OGLIVE[i-1]}" \ + --argjson installed "$installed" \ + --argjson compatible "$compatible" \ + '{id: $id, filename: $filename, installed: $installed, compatible: $compatible}') + + downloads+=("$DATA") done + + jq -n --argjson downloads "$(printf '%s\n' "${downloads[@]}" | jq -s .)" \ + '{downloads: $downloads}' } # Show a menu to select and download an ogLive ISO image from the OpenGnsys website. @@ -312,19 +326,30 @@ function download_old() { curl -k --retry 5 --retry-delay 5 --max-time 30 $DOWNLOADURL/$OGLIVEFILE -o $TARGETFILE || raiseError download "\"$OGLIVEFILE\"." } +update_json() { + local key=$1 + local value=$2 + result_json=$(jq --arg key "$key" --arg value "$value" '.[$key] = $value' <<< "$result_json") +} + +add_message() { + local message=$1 + result_json=$(jq --arg message "$message" '.messages += [$message]' <<< "$result_json") +} + # Install an ogLive client from a previously downloaded ISO image. function install() { local OGLIVEFILE OGLIVEDIST OGLIVEREV OGLIVEKRNL OGLIVEDIR OGINITRD OGSQFS OGCLIENT=ogclient - local COMPRESS SAMBAPASS TMPDIR RSYNCSERV RSYNCCLNT - [ $# -ne 1 ] && { echo "{\"error\": \"usage\"}"; exit 1; } - + local COMPRESS SAMBAPASS TMPDIR RSYNCSERV RSYNCCLNT JSON_OUTPUT + [ $# -ne 1 ] && { echo "{\"status\": \"error\", \"error\": \"usage\"}"; exit 1; } + OGLIVEFILE=$(realpath $DOWNLOADDIR/$1) - [ $(echo $OGLIVEFILE | wc -w) -gt 1 ] && { echo "{\"error\": \"usage\"}"; exit 1; } - [ ! -f $OGLIVEFILE ] && { echo "{\"error\": \"not found \"$1\".\"}"; exit 1; } - [ ! -r $OGLIVEFILE ] && { echo "{\"error\": \"access \"$1\".\"}"; exit 1; } - [ ! -w $(dirname $INFOFILE) ] && { echo "{\"error\": \"access configuration directory.\"}"; exit 1; } - [ ! -w $TFTPDIR ] && { echo "{\"error\": \"access installation directory.\"}"; exit 1; } - [ -z "$(file -b $OGLIVEFILE | grep "ISO.*ogClient")" ] && { echo "{\"error\": \"File is not an ogLive ISO image.\"}"; exit 1; } + [ $(echo $OGLIVEFILE | wc -w) -gt 1 ] && { echo "{\"status\": \"error\", \"error\": \"usage\"}"; exit 1; } + [ ! -f $OGLIVEFILE ] && { echo "{\"status\": \"error\", \"error\": \"not found $1.\"}"; exit 1; } + [ ! -r $OGLIVEFILE ] && { echo "{\"status\": \"error\", \"error\": \"access $1.\"}"; exit 1; } + [ ! -w $(dirname $INFOFILE) ] && { echo "{\"status\": \"error\", \"error\": \"access configuration directory.\"}"; exit 1; } + [ ! -w $TFTPDIR ] && { echo "{\"status\": \"error\", \"error\": \"access installation directory.\"}"; exit 1; } + [ -z "$(file -b $OGLIVEFILE | grep "ISO.*ogClient")" ] && { echo "{\"status\": \"error\", \"error\": \"File is not an ogLive ISO image.\"}"; exit 1; } OGLIVEDIST="$(echo $OGLIVEFILE|cut -f2 -d-)" OGLIVEREV="${OGLIVEFILE##*-}"; OGLIVEREV="${OGLIVEREV%%.*}" @@ -344,175 +369,181 @@ function install() { if [ -r $OGINITRD ]; then COMPRESS=$(file -b "$OGINITRD" | awk '{print tolower($1);}') SAMBAPASS=$($COMPRESS -dc $OGINITRD | \ - cpio -i --to-stdout scripts/ogfunctions 2>&1 | \ + cpio -i --to-stdout scripts/ogfunctions 2>/dev/null | \ sed -n '/^[ \t].*OPTIONS=/s/.*pass=\(\w*\).*/\1/p') fi rm -fr ${OGLIVEDIR}.old - mv -fv $OGLIVEDIR ${OGLIVEDIR}.old 2>/dev/null + mv -f $OGLIVEDIR ${OGLIVEDIR}.old 2>/dev/null TMPDIR=/tmp/${OGLIVEFILE%.iso} mkdir -p $OGLIVEDIR $TMPDIR trap "umount $TMPDIR; rm -fr $TMPDIR" 1 2 3 6 9 15 - mount -o loop,ro $OGLIVEFILE $TMPDIR || { echo "{\"error\": \"mount failed.\"}"; exit 1; } - cp -va $TMPDIR/ogclient/* $OGLIVEDIR || { echo "{\"error\": \"Cannot copy files to ogLive directory.\"}"; exit 1; } - umount $TMPDIR + mount -o loop,ro $OGLIVEFILE $TMPDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"mount failed.\"}"; exit 1; } + cp -va $TMPDIR/ogclient/* $OGLIVEDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"Cannot copy files to ogLive directory.\"}"; exit 1; } + umount $TMPDIR >/dev/null 2>&1 if [ ! -f $INFOFILE ]; then rm -f $TFTPDIR/$DEFOGLIVE $TFTPDIR/$OGCLIENT - ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE || { echo "{\"error\": \"Linking to $TFTPDIR/$DEFOGLIVE failed.\"}"; exit 1; } - ln -vfs $DEFOGLIVE $TFTPDIR/$OGCLIENT || { echo "{\"error\": \"Linking to $TFTPDIR/$OGCLIENT failed.\"}"; exit 1; } + ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"Linking to $TFTPDIR/$DEFOGLIVE failed.\"}"; exit 1; } + ln -vfs $DEFOGLIVE $TFTPDIR/$OGCLIENT >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"Linking to $TFTPDIR/$OGCLIENT failed.\"}"; exit 1; } fi if [ -n "$SAMBAPASS" ]; then - echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" || { echo "{\"error\": \"setsmbpass failed.\"}"; exit 1; } + echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"setsmbpass failed.\"}"; exit 1; } else - $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" || { echo "{\"error\": \"setsmbpass failed.\"}"; exit 1; } + $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"setsmbpass failed.\"}"; exit 1; } fi - find -L $OGLIVEDIR -type d -exec chmod 755 {} \; || { echo "{\"error\": \"chmod directories failed.\"}"; exit 1; } - find -L $OGLIVEDIR -type f -exec chmod 644 {} \; || { echo "{\"error\": \"chmod files failed.\"}"; exit 1; } - chown -R :opengnsys $OGLIVEDIR || { echo "{\"error\": \"chown failed.\"}"; exit 1; } + find -L $OGLIVEDIR -type d -exec chmod 755 {} \; >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"chmod directories failed.\"}"; exit 1; } + find -L $OGLIVEDIR -type f -exec chmod 644 {} \; >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"chmod files failed.\"}"; exit 1; } + chown -R :opengnsys $OGLIVEDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"chown failed.\"}"; exit 1; } - echo "Mounting SquashFS and checking Rsync version..." OGSQFS=$OGLIVEDIR/ogclient.sqfs - echo "Attempting to mount SquashFS..." - if mount -o loop,ro $OGSQFS $TMPDIR; then - echo "Mounted SquashFS successfully." - + if mount -o loop,ro $OGSQFS $TMPDIR >/dev/null 2>&1; then RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}') RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - echo "RSYNCSERV: $RSYNCSERV" - echo "RSYNCCLNT: $RSYNCCLNT" if [ -z "$RSYNCSERV" ] || [ "$RSYNCSERV" -gt "${RSYNCCLNT:-1}" ]; then - echo "Comparing server and client versions for rsync..." if [ -e "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" ]; then - echo "File exists: $OPENGNSYS/client/bin/rsync-$RSYNCSERV" - if mv -f "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" "$OPENGNSYS/client/bin/rsync"; then - echo "Moved rsync successfully" - else - echo "{\"error\": \"mv rsync failed.\"}" - # Optional exit if moving rsync fails - exit 1 - fi - else - echo "File not found: $OPENGNSYS/client/bin/rsync-$RSYNCSERV" - echo "Rsync version $RSYNCSERV not found in $OPENGNSYS/client/bin. No action needed." - # No exit here, as this is not a critical error + mv -f "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" "$OPENGNSYS/client/bin/rsync" 2>/dev/null fi else - echo "Server rsync version is not greater, checking default rsync..." if [ -e "$OPENGNSYS/client/bin/rsync" ]; then - echo "File exists: $OPENGNSYS/client/bin/rsync" - if mv -f "$OPENGNSYS/client/bin/rsync" "$OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')"; then - echo "Moved rsync client successfully" - else - echo "{\"error\": \"mv rsync client failed.\"}" - # Optional exit if moving rsync fails - exit 1 - fi - else - echo "File not found: $OPENGNSYS/client/bin/rsync" - echo "Default rsync not found in $OPENGNSYS/client/bin. No action needed." - # No exit here, as this is not a critical error + mv -f "$OPENGNSYS/client/bin/rsync" "$OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')" fi fi - - echo "Unmounting SquashFS..." - if umount $TMPDIR; then - echo "Unmounted successfully" - sleep 1 - if rmdir $TMPDIR; then - echo "Cleaned up successfully" - else - echo "Warning: rmdir $TMPDIR failed. Attempting force removal." - rm -rf $TMPDIR || echo "{\"error\": \"rm -rf $TMPDIR failed.\"}" - fi - else - echo "{\"error\": \"umount SquashFS failed.\"}" - fi - else - echo "{\"error\": \"mount SquashFS failed.\"}" + umount $TMPDIR >/dev/null 2>&1 + rmdir $TMPDIR >/dev/null 2>&1 || rm -rf $TMPDIR >/dev/null 2>&1 fi - echo "Updating JSON file..." - - # Crear JSON output - json_output=$(jq -n \ + JSON_OUTPUT=$(jq -n \ --arg dist "$OGLIVEDIST" \ --arg krnl "$OGLIVEKRNL" \ --arg arch "$OGLIVEARCH" \ --arg rev "$OGLIVEREV" \ --arg dir "$OGLIVEDIR" \ --arg iso "$(basename "$OGLIVEFILE")" \ - '{distribution: $dist, kernel: $krnl, architecture: $arch, revision: $rev, directory: $dir, iso: $iso}') + '{status: "success", messages: [], result: {distribution: $dist, kernel: $krnl, architecture: $arch, revision: $rev, directory: $dir, iso: $iso}}') - echo "$json_output" + echo "$JSON_OUTPUT" } + # Uninstall an ogLive client. function uninstall() { - local ISO DIR INDEX DEFINDEX - [ $# -ne 1 ] && raiseError usage - [ ! -r $INFOFILE ] && raiseError access "Configuration file." - [ ! -w $TFTPDIR ] && raiseError access "Installation directory." - # Get index and directory for the entry. - case "$1" in - */*) # Error (access to other directory). - raiseError access "Cannot access outside installation directory." - ;; - *.iso) # ISO file. - ISO="$1" - # Working directory (ogLive-Distribution-KernelVersion-CodeRevision). - DIR="$(echo $ISO|cut -f1,3 -d-)-${ISO##*-}"; DIR=${DIR%.*} - INDEX=$(search $DIR 2>/dev/null) - ;; - [0-9]*) # Index. - INDEX=$1; DIR=$(search $INDEX 2>/dev/null) - ;; - *) # Directory. - DIR="$1"; INDEX=$(search $DIR 2>/dev/null) - ;; - esac - DEFINDEX=$(getdefault) - [[ $INDEX = $DEFINDEX ]] && raiseError access "Cannot uninstall default ogLive." - # Remove files and delete index entry. - rm -vfr ${ISO:+$DOWNLOADDIR/$ISO} ${DIR:+$TFTPDIR/$DIR} ### Remove $TFTPDIR/$DIR.old ? - if [ -n "$INDEX" ]; then - jq "del(.oglive[$INDEX])" $INFOFILE | sponge $INFOFILE - # Decrement default index if needed (removed < default). - [[ $INDEX < $DEFINDEX ]] && jq ".default=$((DEFINDEX-1))" $INFOFILE | sponge $INFOFILE + local CHECKSUM DIR + + # Validar que se proporcionó exactamente un argumento (el checksum) + [ $# -ne 1 ] && { echo "{\"error\": \"usage: uninstall {checksum}\"}"; exit 1; } + + CHECKSUM=$1 + + # Verificar acceso a los directorios necesarios + [ ! -w $TFTPDIR ] && { echo "{\"error\": \"access installation directory.\"}"; exit 1; } + + # Buscar el directorio correspondiente al checksum + DIR=$(find $TFTPDIR -type f -name 'linuxISO.sum' -exec grep -l "$CHECKSUM" {} \; | xargs -I{} dirname {}) + + # Si no se encuentra el directorio, devolver error + if [ -z "$DIR" ]; then + echo "{\"error\": \"ogLive client with checksum $CHECKSUM not found.\"}" + exit 1 fi + + # Eliminar archivos y directorio, redirigiendo la salida a /dev/null + rm -vfr $DIR > /dev/null 2>&1 + + # Comprobar si la eliminación tuvo éxito + if [ -d "$DIR" ]; then + echo "{\"error\": \"Failed to uninstall ogLive client in $DIR.\"}" + exit 1 + fi + + # Devolver mensaje de éxito + echo "{\"message\": \"ogLive client uninstalled successfully.\", \"details\": \"Removed directory: $DIR\"}" } -# Get default ogLive index. -function getdefault() { - [ $# -ne 0 ] && raiseError usage - [ ! -r $INFOFILE ] && raiseError access "Configuration file." - # Read default parameter. - jq -r .default $INFOFILE || raiseError notfound "Undefined default index." +# Get information about the default ogLive client. +function get_default() { + local DEFAULT_LINK="$TFTPDIR/$DEFOGLIVE" + local DIR OGLIVEDIST OGLIVEKRNL OGLIVEARCH OGLIVEREV OGLIVEISO OGLIVEDIR + + # Verificar que el enlace simbólico del ogLive por defecto existe. + if [ ! -L "$DEFAULT_LINK" ]; then + echo "{\"error\": \"Default ogLive client link not found.\"}" + exit 1 + fi + + # Obtener el directorio real al que apunta el enlace simbólico. + DIR=$(readlink -f "$DEFAULT_LINK") + + # Si no se encuentra el directorio, devolver error. + if [ -z "$DIR" ]; then + echo "{\"error\": \"Default ogLive client directory not found.\"}" + exit 1 + fi + + # Obtener la información del ogLive a partir del nombre del directorio. + OGLIVEDIR=$(basename "$DIR") + OGLIVEDIST="$(echo $OGLIVEDIR | cut -d- -f2)" + OGLIVEKRNL="$(echo $OGLIVEDIR | cut -d- -f3)" + OGLIVEARCH="amd64" # Suponiendo que siempre es amd64 + OGLIVEREV="$(echo $OGLIVEDIR | cut -d- -f4)" + OGLIVEISO="" # No tenemos la información del ISO aquí, podría necesitarse un ajuste si se requiere + + # Construir el JSON con la información. + local INFO=$(cat << EOT +{ + "distribution": "$OGLIVEDIST", + "kernel": "$OGLIVEKRNL", + "architecture": "$OGLIVEARCH", + "revision": "$OGLIVEREV", + "directory": "$DIR", + "iso": "$OGLIVEISO" +} +EOT + ) + + # Devolver la información en formato JSON. + echo "$INFO" } -# Set default ogLive index. -function setdefault() { - local INDEX OGLIVEDIR - [ $# -ne 1 ] && raiseError usage - [ ! -w $INFOFILE ] && raiseError access "Configuration file." - INDEX=$1 - # Check if index entry exists. - jq ".oglive[$INDEX]" $INFOFILE || raiseError notfound "Index \"$INDEX\"." - # Get ogLive directory. - OGLIVEDIR=$(jq -r ".oglive[$INDEX].directory" $INFOFILE) || raiseError notfound "Directory for index \"$INDEX\"." - # Update default parameter. - jq ".default=$INDEX" $INFOFILE | sponge $INFOFILE - # Link to default directory. - rm -f $TFTPDIR/$DEFOGLIVE - ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE +# Set default ogLive client by checksum. +function set_default() { + local CHECKSUM=$1 + local DIR + + # Validar que se proporcionó exactamente un argumento (el checksum) + [ $# -ne 1 ] && { echo "{\"error\": \"usage: set-default {checksum}\"}"; exit 1; } + + # Verificar acceso a los directorios necesarios + [ ! -w $TFTPDIR ] && { echo "{\"error\": \"access installation directory.\"}"; exit 1; } + + # Buscar el directorio correspondiente al checksum + DIR=$(find $TFTPDIR -type f -name 'linuxISO.sum' -exec grep -l "$CHECKSUM" {} \; | xargs -I{} dirname {} | grep -v ".old") + + # Si no se encuentra el directorio, devolver error + if [ -z "$DIR" ]; then + echo "{\"error\": \"ogLive client with checksum $CHECKSUM not found.\"}" + exit 1 + fi + + # Eliminar el enlace simbólico existente y crear uno nuevo + rm -f $TFTPDIR/$DEFOGLIVE > /dev/null 2>&1 + ln -vfs $(basename $DIR) $TFTPDIR/$DEFOGLIVE > /dev/null 2>&1 + + # Comprobar si el enlace simbólico se creó correctamente + if [ "$(readlink -f $TFTPDIR/$DEFOGLIVE)" == "$(readlink -f $DIR)" ]; then + echo "{\"message\": \"ogLive client set as default successfully.\", \"details\": \"$DIR\"}" + else + echo "{\"error\": \"Failed to set default ogLive client.\"}" + exit 1 + fi } # Rebuild a lost configuration file. @@ -550,6 +581,135 @@ local ISOFILE DIR jq ".oglive[$2].iso=\"$1\"" $INFOFILE | sponge $INFOFILE && jq ".oglive[$2]" $INFOFILE } +# Get disk usage information +function disk_usage() { + DISK_INFO=$(df -h / | awk 'NR==2{print "{\"total\":\""$2"\", \"used\":\""$3"\", \"available\":\""$4"\", \"percentage\":\""$5"\"}"}') + echo $DISK_INFO +} + +# Function to list installed ogLive clients and the default ogLive client +function list_installed_oglives() { + local INST NF DEF + INST=$(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort) + local installed_ogLives=() + + for i in $INST; do + NF=$(echo $i | awk -F- '{print NF-1}') + local OGLIVEDIST="" + local OGLIVEKRNL="" + local OGLIVEARCH="" + local OGLIVEREV="" + local CHECKSUM="" + local CHECKSUM_FILE="$TFTPDIR/$i/linuxISO.sum" + + if [ -f "$CHECKSUM_FILE" ]; then + CHECKSUM=$(cat "$CHECKSUM_FILE" | cut -d ' ' -f 1) + fi + + case $NF in + 1) OGLIVEDIST="" OGLIVEKRNL=$(echo $i|cut -f2 -d-) OGLIVEARCH="i386" OGLIVEREV="" ;; + 2) eval $(echo $i | awk -F- '{printf "OGLIVEDIST=\"\" OGLIVEKRNL=%s OGLIVEARCH=amd64 OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$0}') ;; + 3) eval $(echo $i | awk -F- '{if ($3=="i386") printf "OGLIVEDIST=\"\" OGLIVEKRNL=%s OGLIVEARCH=%s OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$4,$0; else printf "OGLIVEDIST=%s OGLIVEKRNL=%s OGLIVEARCH=i386 OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$4,$0}') ;; + 4) eval $(echo $i | awk -F- '{printf "OGLIVEDIST=%s OGLIVEKRNL=%s OGLIVEARCH=%s OGLIVEREV=%s OGLIVEDIR=%s",$2,$3,$4,$5,$0}') ;; + esac + + local DATA=$(jq -n \ + --arg id "$CHECKSUM" \ + --arg dist "$OGLIVEDIST" \ + --arg krnl "$OGLIVEKRNL" \ + --arg arch "$OGLIVEARCH" \ + --arg rev "$OGLIVEREV" \ + --arg dir "$TFTPDIR/$OGLIVEDIR" \ + --arg iso "" \ + '{id: $id, distribution: $dist, kernel: $krnl, architecture: $arch, revision: $rev, directory: $dir, iso: $iso}') + + installed_ogLives+=("$DATA") + + [ -n "$(stat -c "%N" $TFTPDIR/$DEFOGLIVE | awk '$3~/'$i'/ {print}')" ] && DEF="$i" + done + + local default_oglive=$(basename $(readlink -f $TFTPDIR/$DEFOGLIVE)) + + jq -n \ + --arg default_oglive "$default_oglive" \ + --argjson installed_ogLives "$(printf '%s\n' "${installed_ogLives[@]}" | jq -s .)" \ + '{ + default_oglive: $default_oglive, + installed_ogLives: $installed_ogLives + }' +} + +# Get information about an installed ogLive client. +function get_info() { + local CHECKSUM="$1" + local DIR OGLIVEDIST OGLIVEKRNL OGLIVEARCH OGLIVEREV OGLIVEISO OGLIVEDIR + + # Verificar que se proporcionó un checksum. + [ -z "$CHECKSUM" ] && { echo "{\"error\": \"usage: get_info {checksum}\"}"; exit 1; } + + # Verificar acceso al directorio de instalación. + [ ! -w $TFTPDIR ] && { echo "{\"error\": \"access installation directory.\"}"; exit 1; } + + # Buscar el directorio correspondiente al checksum, excluyendo los que terminan en .old. + DIR=$(find $TFTPDIR -type f -name 'linuxISO.sum' -exec grep -l "$CHECKSUM" {} \; | grep -v '.old' | xargs -I{} dirname {}) + + # Si no se encuentra el directorio, devolver error. + if [ -z "$DIR" ]; then + echo "{\"error\": \"ogLive client with checksum $CHECKSUM not found.\"}" + exit 1 + fi + + # Obtener la información del ogLive a partir del nombre del directorio. + OGLIVEDIR=$(basename "$DIR") + OGLIVEDIST="$(echo $OGLIVEDIR | cut -d- -f2)" + OGLIVEKRNL="$(echo $OGLIVEDIR | cut -d- -f3)" + OGLIVEARCH="amd64" # Suponiendo que siempre es amd64 + OGLIVEREV="$(echo $OGLIVEDIR | cut -d- -f4)" + OGLIVEISO="" # No tenemos la información del ISO aquí, podría necesitarse un ajuste si se requiere + + # Construir el JSON con la información. + local INFO=$(cat << EOT +{ + "distribution": "$OGLIVEDIST", + "kernel": "$OGLIVEKRNL", + "architecture": "$OGLIVEARCH", + "revision": "$OGLIVEREV", + "directory": "$DIR", + "iso": "$OGLIVEISO" +} +EOT + ) + + # Devolver la información en formato JSON. + echo "$INFO" +} + +# Function to check the status of services +function check_services_status() { + local SERVICES=("oglive_daemon.service" "tftpd-hpa.service" "nginx.service") + declare -A STATUS_MAP + + for service in "${SERVICES[@]}"; do + if systemctl list-units --type=service --all | grep -q "$service"; then + STATUS=$(systemctl is-active "$service") + STATUS_MAP[$service]=$STATUS + else + STATUS_MAP[$service]="not installed" + fi + done + + local json_output=$(jq -n \ + --arg oglive_daemon "${STATUS_MAP['oglive_daemon.service']}" \ + --arg tftpboot "${STATUS_MAP['tftpd-hpa.service']}" \ + --arg nginx "${STATUS_MAP['nginx.service']}" \ + '{ + oglive_daemon: $oglive_daemon, + tftpboot: $tftpboot, + nginx: $nginx + }') + + echo "$json_output" +} # Main progrram. @@ -562,7 +722,7 @@ which sponge &>/dev/null || raiseError notfound "Need to install \"moreutils\"." # Commands control. shopt -s extglob case "$ACCESS" in - root) CMDS='+(help|version|convert|config|check|list|show|search|download|install|uninstall|get-default|set-default|rebuild|assign)' ;; + root) CMDS='+(help|version|convert|config|check|list|show|search|download|install|uninstall|get-default|set-default|rebuild|assign|disk_usage|list_installed_oglives|get_info|get_default|set_default|check_services_status)' ;; web) CMDS='+(list|show|search|get-default)' ;; esac case "$1" in diff --git a/src/OgBootBundle/Controller/OgBootController.php b/src/OgBootBundle/Controller/OgBootController.php index 73405e8..31780d9 100644 --- a/src/OgBootBundle/Controller/OgBootController.php +++ b/src/OgBootBundle/Controller/OgBootController.php @@ -68,66 +68,63 @@ Regenerar plantilla - PUT /ogboot/pxe-templates } /** - * @Route("/ogboot/v1/config", name="config", methods={"GET"}) + * @Route("/ogboot/v1/config", name="getConfig", methods={"GET"}) * @OA\Get( * path="/ogboot/v1/config", * summary="Get ogboot configuration", * @OA\Response( * response=200, - * description="Successful operation", + * description="Configuration retrieved successfully", * @OA\JsonContent( * type="object", - * @OA\Property( - * property="config-file", - * type="string", - * description="Configuration file path" + * @OA\Property(property="disk_usage", type="object", + * @OA\Property(property="total", type="string"), + * @OA\Property(property="used", type="string"), + * @OA\Property(property="available", type="string"), + * @OA\Property(property="percentage", type="string") * ), - * @OA\Property( - * property="download-url", - * type="string", - * description="ogLive download URL" - * ), - * @OA\Property( - * property="download-dir", - * type="string", - * description="ogLive download directory" - * ), - * @OA\Property( - * property="install-dir", - * type="string", - * description="ogLive installation directory" - * ), - * @OA\Property( - * property="default-name", - * type="string", - * description="Default ogLive name" - * ), - * @OA\Property( - * property="min-release", - * type="string", - * description="Minimum compatibility release" - * ) + * @OA\Property(property="default_oglive", type="string"), + * @OA\Property(property="installed_oglives", type="array", @OA\Items(type="string")) * ) - * ), - * @OA\Response( - * response=500, - * description="Failed to retrieve configuration" * ) * ) */ - public function config(): Response - { +public function getConfig(): Response +{ + // Call oglivecli to get disk usage + $diskUsageResult = $this->curlRequestService->callOgLive("disk_usage"); - # $result = $this->curlRequestService->common_request(OG_REST_CMD_POWEROFF, POST, [OG_REST_PARAM_CLIENTS => $ips]); - $result = $this->curlRequestService->callOgLive("config"); - - if ($result) { - return new Response($result, Response::HTTP_OK); - } else { - return new Response('Failed', Response::HTTP_INTERNAL_SERVER_ERROR); - } + if (is_array($diskUsageResult) && isset($diskUsageResult['success']) && $diskUsageResult['success'] === false) { + return new JsonResponse(['error' => 'Failed to retrieve disk usage', 'details' => $diskUsageResult['error']], Response::HTTP_INTERNAL_SERVER_ERROR); } + // Call oglivecli to get installed oglives and default oglives + $ogLiveConfigResult = $this->curlRequestService->callOgLive("list_installed_oglives"); + + if (is_array($ogLiveConfigResult) && isset($ogLiveConfigResult['success']) && $ogLiveConfigResult['success'] === false) { + return new JsonResponse(['error' => 'Failed to retrieve ogLive configuration', 'details' => $ogLiveConfigResult['error']], Response::HTTP_INTERNAL_SERVER_ERROR); + } + + // Call oglivecli to get installed oglives and default oglives + $servicesStatusResult = $this->curlRequestService->callOgLive("check_services_status"); + + if (is_array($servicesStatusResult) && isset($servicesStatusResult['success']) && $servicesStatusResult['success'] === false) { + return new JsonResponse(['error' => 'Failed to retrieve services status', 'details' => $servicesStatusResult['error']], Response::HTTP_INTERNAL_SERVER_ERROR); + } + + $response = [ + 'disk_usage' => $diskUsageResult, + 'default_oglive' => $ogLiveConfigResult['default_oglive'], + 'installed_oglives' => $ogLiveConfigResult['installed_ogLives'], + 'services_status' => $servicesStatusResult + ]; + + return new JsonResponse($response, Response::HTTP_OK); +} + + + + /** * @Route("/ogboot/v1/status", name="status", methods={"GET"}) * @OA\Get( @@ -164,6 +161,46 @@ Regenerar plantilla - PUT /ogboot/pxe-templates } } +/** + * @Route("/ogboot/v1/oglives/isos", name="getDownloadMenu", methods={"GET"}) + * @OA\Get( + * path="/ogboot/v1/oglives/isos", + * summary="Get ogLive downloads menu", + * @OA\Response( + * response=200, + * description="Isos retrieved successfully", + * @OA\JsonContent( + * type="array", + * @OA\Items(type="object", + * @OA\Property(property="id", type="integer"), + * @OA\Property(property="filename", type="string"), + * @OA\Property(property="installed", type="boolean"), + * @OA\Property(property="compatible", type="boolean") + * ) + * ) + * ), + * @OA\Response( + * response=500, + * description="Failed to retrieve isos", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="error", type="string"), + * @OA\Property(property="details", type="string") + * ) + * ) + * ) + */ +public function getDownloadMenu(): Response +{ + $downloadsOutput = $this->curlRequestService->callOgLive("download"); + + if (is_array($downloadsOutput) && isset($downloadsOutput['success']) && $downloadsOutput['success'] === false) { + return new JsonResponse(['error' => 'Failed to retrieve downloads', 'details' => $downloadsOutput['error']], Response::HTTP_INTERNAL_SERVER_ERROR); + } + + return new JsonResponse($downloadsOutput, Response::HTTP_OK); +} + /** * @Route("/ogboot/v1/oglives", name="getOglives", methods={"GET"}) * @OA\Get( @@ -308,130 +345,6 @@ public function getOglives(): Response } } - -/** - * @Route("/ogboot/v1/oglives/{id}", name="getOglive", methods={"GET"}) - * @OA\Get( - * path="/ogboot/v1/oglives/{id}", - * summary="Get information of an installed ogLive client", - * @OA\Parameter( - * name="id", - * in="path", - * description="Checksum of the installed ogLive client", - * required=true, - * @OA\Schema( - * type="string", - * example="9e49a085ba74f97a81bdf9b3d0785094" - * ) - * ), - * @OA\Response( - * response=200, - * description="Successful operation", - * @OA\JsonContent( - * type="object", - * @OA\Property( - * property="id", - * type="string", - * description="Checksum of the installed ogLive client" - * ), - * @OA\Property( - * property="distribution", - * type="string", - * description="Distribution name of the installed ogLive client" - * ), - * @OA\Property( - * property="kernel", - * type="string", - * description="Kernel version of the installed ogLive client" - * ), - * @OA\Property( - * property="architecture", - * type="string", - * description="Architecture of the installed ogLive client" - * ), - * @OA\Property( - * property="revision", - * type="string", - * description="Revision of the installed ogLive client" - * ), - * @OA\Property( - * property="directory", - * type="string", - * description="Directory name of the installed ogLive client" - * ), - * @OA\Property( - * property="iso", - * type="string", - * description="ISO file name of the installed ogLive client" - * ) - * ) - * ), - * @OA\Response( - * response=404, - * description="ogLive client not found" - * ) - * ) - */ -public function getOglive(Request $request, string $id): Response -{ - $directoryPath = '/opt/ogboot/tftpboot/'; - $pattern = '/^ogLive-([\w.-]+)-([\w.-]+)-r(\d{4,8})$/'; - - $found = false; - $result = []; - - if ($handle = opendir($directoryPath)) { - while (false !== ($entry = readdir($handle))) { - if ($entry != "." && $entry != ".." && is_dir($directoryPath . $entry)) { - if (preg_match($pattern, $entry, $matches)) { - $checksumFilePath = $directoryPath . $entry . '/linuxISO.sum'; - if (file_exists($checksumFilePath)) { - $checksum = trim(file_get_contents($checksumFilePath)); - if ($checksum === $id) { - // Extract details - $distribution = explode('-', $matches[1])[0]; - $kernel = substr($matches[1], strlen($distribution) + 1); - $architecture = 'amd64'; // Assuming architecture, refine as needed - $revision = $matches[3]; - $directory = $entry; - $iso = $this->findIsoFile($directoryPath . $entry); - - // Construct the result - $result = [ - 'id' => $id, - 'distribution' => $distribution, - 'kernel' => $kernel, - 'architecture' => $architecture, - 'revision' => $revision, - 'directory' => $directory, - 'iso' => $iso - ]; - $found = true; - break; - } - } - } - } - } - closedir($handle); - } - - if ($found) { - return new JsonResponse($result, Response::HTTP_OK); - } else { - return new JsonResponse(['error' => 'ogLive client not found'], Response::HTTP_NOT_FOUND); - } -} - -private function findIsoFile(string $directory): string -{ - $files = glob($directory . '/*.iso'); - return count($files) > 0 ? basename($files[0]) : ''; -} - - - - /** * @Route("/ogboot/v1/oglives/default", name="getOgliveDefault", methods={"GET"}) * @OA\Get( @@ -480,19 +393,90 @@ private function findIsoFile(string $directory): string * ) * ) */ +public function getOgliveDefault(Request $request): Response +{ + $result = $this->curlRequestService->callOgLive("get_default"); - public function getOgliveDefault(Request $request): Response - { - # $result = $this->curlRequestService->common_request(OG_REST_CMD_POWEROFF, POST, [OG_REST_PARAM_CLIENTS => $ips]); - $result = $this->curlRequestService->callOgLive("show default"); - - if ($result) { - return new Response($result, Response::HTTP_OK); - } else { - return new Response('Failed', Response::HTTP_INTERNAL_SERVER_ERROR); - } + if (is_array($result) && isset($result['error'])) { + return new JsonResponse(['error' => $result['error']], Response::HTTP_INTERNAL_SERVER_ERROR); } + return new JsonResponse($result, Response::HTTP_OK); +} + +/** + * @Route("/ogboot/v1/oglives/{checksum}", name="getOglive", methods={"GET"}) + * @OA\Get( + * path="/ogboot/v1/oglives/{checksum}", + * summary="Get information of an installed ogLive client", + * @OA\Parameter( + * name="checksum", + * in="path", + * description="Checksum of the installed ogLive client", + * required=true, + * @OA\Schema( + * type="string", + * example="9e49a085ba74f97a81bdf9b3d0785094" + * ) + * ), + * @OA\Response( + * response=200, + * description="Successful operation", + * @OA\JsonContent( + * type="object", + * @OA\Property( + * property="distribution", + * type="string", + * description="Distribution name of the installed ogLive client" + * ), + * @OA\Property( + * property="kernel", + * type="string", + * description="Kernel version of the installed ogLive client" + * ), + * @OA\Property( + * property="architecture", + * type="string", + * description="Architecture of the installed ogLive client" + * ), + * @OA\Property( + * property="revision", + * type="string", + * description="Revision of the installed ogLive client" + * ), + * @OA\Property( + * property="directory", + * type="string", + * description="Directory name of the installed ogLive client" + * ), + * @OA\Property( + * property="iso", + * type="string", + * description="ISO file name of the installed ogLive client" + * ) + * ) + * ), + * @OA\Response( + * response=404, + * description="ogLive client not found" + * ) + * ) + */ +public function getOglive(string $checksum): Response +{ + $result = $this->curlRequestService->callOgLive("get_info " . escapeshellarg($checksum)); + + if (is_array($result) && isset($result['error'])) { + return new JsonResponse(['error' => $result['error']], Response::HTTP_NOT_FOUND); + } + + return new JsonResponse($result, Response::HTTP_OK); +} + + + + + /** @@ -505,10 +489,10 @@ private function findIsoFile(string $directory): string * @OA\JsonContent( * type="object", * @OA\Property( - * property="name", + * property="checksum", * type="string", - * example="ogLive-5.11.0-r20210413", - * description="Name of the ogLive client to set as default" + * example="9e49a085ba74f97a81bdf9b3d0785094", + * description="Checksum of the ogLive client to set as default" * ) * ) * ), @@ -534,114 +518,31 @@ public function setOgliveDefault(Request $request): Response { $data = json_decode($request->getContent(), true); - if (!isset($data['name'])) { + if (!isset($data['checksum'])) { return new JsonResponse(['error' => 'Invalid input data'], Response::HTTP_BAD_REQUEST); } - $name = $data['name']; + $checksum = $data['checksum']; - // Obtener la lista de ogLives - $listResult = $this->curlRequestService->callOgLive("list"); + // Establecer el ogLive como predeterminado utilizando el checksum proporcionado + $result = $this->curlRequestService->callOgLive("set_default " . escapeshellarg($checksum)); - if (!$listResult) { - return new Response('Failed to retrieve ogLive list', Response::HTTP_INTERNAL_SERVER_ERROR); + if (is_array($result) && isset($result['error'])) { + return new JsonResponse(['error' => $result['error']], Response::HTTP_INTERNAL_SERVER_ERROR); } - // Buscar el ID correspondiente al nombre proporcionado - $lines = explode("\n", trim($listResult)); - $id = null; - foreach ($lines as $line) { - if (strpos($line, $name) !== false) { - $id = explode(" ", trim($line))[0]; - break; - } - } - - if ($id === null) { - return new JsonResponse(['error' => 'ogLive client not found'], Response::HTTP_NOT_FOUND); - } - - // Establecer el ogLive como predeterminado utilizando el ID encontrado - $result = $this->curlRequestService->callOgLive("set-default $id"); - - if ($result) { - return new JsonResponse(['message' => 'ogLive client set as default successfully'], Response::HTTP_OK); - } else { - return new JsonResponse(['error' => 'Failed to set default ogLive client'], Response::HTTP_INTERNAL_SERVER_ERROR); - } + return new JsonResponse(['message' => 'ogLive client set as default successfully'], Response::HTTP_OK); } - - -/** - * @Route("/ogboot/v1/isos", name="getDownloadMenu", methods={"GET"}) - * @OA\Get( - * path="/ogboot/v1/isos", - * summary="Get available ISO images for download", - * @OA\Response( - * response=200, - * description="List of available ISO images", - * @OA\JsonContent( - * type="array", - * @OA\Items( - * type="object", - * @OA\Property(property="id", type="string"), - * @OA\Property(property="filename", type="string"), - * @OA\Property(property="installed", type="boolean"), - * @OA\Property(property="compatible", type="boolean") - * ) - * ) - * ) - * ) - */ - -public function getDownloadMenu(): Response -{ - - $downloadsOutput = $this->curlRequestService->callOgLive("download"); - - - $downloads = explode("\n", trim($downloadsOutput)); - $result = []; - - foreach ($downloads as $download) { - - $pattern = '/^(\d+)\) (\(\*\))?\s?(\(\+\))?\s?(.+\.iso)$/'; - - - preg_match($pattern, $download, $matches); - - if (!empty($matches)) { - $id = $matches[1]; - $installed = !empty($matches[2]); - $compatible = !empty($matches[3]); - $filename = $matches[4]; - - $result[] = [ - 'id' => $id, - 'filename' => $filename, - 'installed' => $installed, - 'compatible' => $compatible - ]; - } - } - - $jsonDownloads = json_encode($result); - - - return new Response($jsonDownloads, Response::HTTP_OK, [ - 'Content-Type' => 'application/json' - ]); -} /** - * @Route("/ogboot/v1/oglives", name="installOglive", methods={"POST"}) + * @Route("/ogboot/v1/oglives/install", name="installOglive", methods={"POST"}) * @OA\Post( - * path="/ogboot/v1/oglives", + * path="/ogboot/v1/oglives/install", * summary="Install an ogLive client", * @OA\RequestBody( * required=true, @@ -660,21 +561,13 @@ public function getDownloadMenu(): Response * description="ogLive client installed successfully", * @OA\JsonContent( * type="object", - * @OA\Property(property="distribution", type="string"), - * @OA\Property(property="kernel", type="string"), - * @OA\Property(property="architecture", type="string"), - * @OA\Property(property="revision", type="string"), - * @OA\Property(property="directory", type="string"), - * @OA\Property(property="iso", type="string") + * @OA\Property(property="message", type="string"), + * @OA\Property(property="details", type="object") * ) * ), * @OA\Response( * response=400, - * description="Invalid input data", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string") - * ) + * description="Invalid input data" * ), * @OA\Response( * response=500, @@ -687,8 +580,6 @@ public function getDownloadMenu(): Response * ) * ) */ - - public function installOglive(Request $request): Response { $data = json_decode($request->getContent(), true); @@ -698,17 +589,17 @@ public function installOglive(Request $request): Response } $isoname = $data['isoname']; - $result = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoname)); + $result = $this->curlRequestService->callOgLive("install " . escapeshellarg($isoname)); if (is_array($result) && isset($result['success']) && $result['success'] === false) { return new JsonResponse(['error' => 'Failed to install ogLive client', 'details' => $result['error']], Response::HTTP_INTERNAL_SERVER_ERROR); } - return new JsonResponse(['message' => 'ogLive client installed successfully', 'details' => $result['output']], Response::HTTP_OK); + return new JsonResponse(['message' => 'ogLive client installed successfully', 'details' => $result], Response::HTTP_OK); } - - + + /** * @Route("/ogboot/v1/oglives/{checksum}", name="uninstallOglive", methods={"DELETE"}) * @OA\Delete( @@ -726,7 +617,8 @@ public function installOglive(Request $request): Response * description="ogLive client uninstalled successfully", * @OA\JsonContent( * type="object", - * @OA\Property(property="message", type="string") + * @OA\Property(property="message", type="string"), + * @OA\Property(property="details", type="string") * ) * ), * @OA\Response( @@ -745,23 +637,34 @@ public function installOglive(Request $request): Response */ public function uninstallOglive(string $checksum): Response { + // Llamada al servicio para desinstalar el cliente ogLive + error_log("Calling curlRequestService with checksum: $checksum"); $result = $this->curlRequestService->callOgLive("uninstall " . escapeshellarg($checksum)); - if ($result) { - // Decodifica la respuesta JSON del demonio - $response = json_decode($result, true); + // Verificar la respuesta del servicio + error_log("Service call result: " . print_r($result, true)); - if (isset($response['error'])) { - return new JsonResponse(['error' => $response['error']], Response::HTTP_INTERNAL_SERVER_ERROR); - } - - return new JsonResponse(['message' => 'ogLive client uninstalled successfully', 'details' => $response['details']], Response::HTTP_OK); + if (is_array($result) && isset($result['error'])) { + // Error encontrado en la respuesta + error_log("Error found in response: " . $result['error']); + return new JsonResponse(['error' => $result['error']], Response::HTTP_INTERNAL_SERVER_ERROR); + } elseif (is_array($result) && isset($result['message'])) { + // Respuesta exitosa + error_log("Success response: " . print_r($result, true)); + return new JsonResponse([ + 'message' => $result['message'], + 'details' => $result['details'] ?? '' + ], Response::HTTP_OK); } else { + // Manejar el caso en que no se recibió una respuesta válida del servicio + error_log("Failed to uninstall ogLive client, empty result from service"); return new JsonResponse(['error' => 'Failed to uninstall ogLive client'], Response::HTTP_INTERNAL_SERVER_ERROR); } } + + /** * @Route("/ogboot/v1/pxes", name="get_boot_files", methods={"GET"}) * @OA\Get( diff --git a/src/OgBootBundle/Service/CurlRequestService.php b/src/OgBootBundle/Service/CurlRequestService.php index 960183e..a4c4373 100644 --- a/src/OgBootBundle/Service/CurlRequestService.php +++ b/src/OgBootBundle/Service/CurlRequestService.php @@ -3,6 +3,7 @@ namespace App\OgBootBundle\Service; use Exception; +use Psr\Log\LoggerInterface; class CurlRequestService { @@ -66,34 +67,39 @@ public function installOglive($isoname) public function callOgLive($parameter) { - $socketPath = '/tmp/oglive_daemon.sock'; + $socketPath = '/var/run/oglive/oglive_daemon.sock'; + + // Registrar el parámetro recibido + file_put_contents('/tmp/serviceOglive.log', 'callOgLive called with parameter: ' . $parameter . PHP_EOL, FILE_APPEND); + $socket = socket_create(AF_UNIX, SOCK_STREAM, 0); if ($socket === false) { - syslog(LOG_ERR, 'Error al crear el socket: ' . socket_strerror(socket_last_error())); + $error = 'Error al crear el socket: ' . socket_strerror(socket_last_error()); + file_put_contents('/tmp/serviceOglive.log', 'Socket creation error: ' . $error . PHP_EOL, FILE_APPEND); return [ 'success' => false, - 'error' => 'Error al crear el socket' + 'error' => $error ]; } $result = socket_connect($socket, $socketPath); if ($result === false) { - syslog(LOG_ERR, 'Error al conectar con el socket: ' . socket_strerror(socket_last_error($socket))); + $error = 'Error al conectar con el socket: ' . socket_strerror(socket_last_error($socket)); + file_put_contents('/tmp/serviceOglive.log', 'Socket connection error: ' . $error . PHP_EOL, FILE_APPEND); socket_close($socket); return [ 'success' => false, - 'error' => 'Error al conectar con el socket' + 'error' => $error ]; } - $args = explode(' ', $parameter); + $args = array_map('trim', explode(' ', $parameter)); $action = array_shift($args); $command = [ 'action' => $action, 'args' => $args ]; - syslog(LOG_INFO, 'Sending command to daemon: ' . json_encode($command)); socket_write($socket, json_encode($command), strlen(json_encode($command))); $response = ''; @@ -103,15 +109,40 @@ public function callOgLive($parameter) socket_close($socket); - $decodedResponse = json_decode($response, true); + // Registrar la respuesta en bruto + file_put_contents('/tmp/serviceOglive.log', 'Raw response: ' . $response . PHP_EOL, FILE_APPEND); - if (isset($decodedResponse['success']) && $decodedResponse['success']) { - return $decodedResponse['output']; - } else { - syslog(LOG_ERR, 'Error al ejecutar el comando: ' . $decodedResponse['error']); + if (empty($response)) { + $error = 'Respuesta vacía del demonio'; + file_put_contents('/tmp/serviceOglive.log', 'Empty response error: ' . $error . PHP_EOL, FILE_APPEND); return [ 'success' => false, - 'error' => $decodedResponse['error'] ?? 'Unknown error' + 'error' => $error + ]; + } + + $decodedResponse = json_decode($response, true); + + // Registrar cualquier error de decodificación JSON + if (json_last_error() !== JSON_ERROR_NONE) { + $error = 'Error al decodificar JSON: ' . json_last_error_msg(); + file_put_contents('/tmp/serviceOglive.log', 'JSON decode error: ' . $error . PHP_EOL, FILE_APPEND); + return [ + 'success' => false, + 'error' => $error + ]; + } + + if (isset($decodedResponse['success']) && $decodedResponse['success']) { + // Registrar la respuesta decodificada + file_put_contents('/tmp/serviceOglive.log', 'Decoded successful response: ' . json_encode($decodedResponse['output']) . PHP_EOL, FILE_APPEND); + return $decodedResponse['output']; + } else { + $error = $decodedResponse['error'] ?? 'Unknown error'; + file_put_contents('/tmp/serviceOglive.log', 'Error in response: ' . $error . PHP_EOL, FILE_APPEND); + return [ + 'success' => false, + 'error' => $error ]; } }