diff --git a/bin/oglivecli b/bin/oglivecli index f9589f8..21bc293 100755 --- a/bin/oglivecli +++ b/bin/oglivecli @@ -269,20 +269,20 @@ add_message() { function install() { local OGLIVEFILE OGLIVEDIST OGLIVEREV OGLIVEKRNL OGLIVEDIR OGINITRD OGSQFS OGCLIENT=ogclient local COMPRESS SAMBAPASS TMPDIR RSYNCSERV RSYNCCLNT JSON_OUTPUT - [ $# -ne 1 ] && { echo "{\"status\": \"error\", \"error\": \"usage\"}"; exit 1; } + [ $# -ne 1 ] && { echo "{\"error\": \"USAGE_ERROR\", \"message\": \"Usage: install {iso_file}\"}"; exit 400; } - OGLIVEFILE=$(realpath $DOWNLOADDIR/$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; } + OGLIVEFILE=$(realpath "$DOWNLOADDIR/$1") + [ $(echo "$OGLIVEFILE" | wc -w) -gt 1 ] && { echo "{\"error\": \"USAGE_ERROR\", \"message\": \"Invalid ISO file: $1\"}"; exit 400; } + [ ! -f "$OGLIVEFILE" ] && { echo "{\"error\": \"NOT_FOUND\", \"message\": \"ISO file $1 not found.\"}"; exit 404; } + [ ! -r "$OGLIVEFILE" ] && { echo "{\"error\": \"ACCESS_DENIED\", \"message\": \"Cannot read ISO file $1.\"}"; exit 403; } + [ ! -w "$(dirname "$INFOFILE")" ] && { echo "{\"error\": \"ACCESS_DENIED\", \"message\": \"Cannot write to configuration directory.\"}"; exit 403; } + [ ! -w "$TFTPDIR" ] && { echo "{\"error\": \"ACCESS_DENIED\", \"message\": \"Cannot write to installation directory.\"}"; exit 403; } + [ -z "$(file -b "$OGLIVEFILE" | grep "ISO.*ogClient")" ] && { echo "{\"error\": \"INVALID_FILE\", \"message\": \"File is not a valid ogLive ISO image.\"}"; exit 400; } - OGLIVEDIST="$(echo $OGLIVEFILE|cut -f2 -d-)" + OGLIVEDIST="$(echo "$OGLIVEFILE" | cut -f2 -d-)" OGLIVEREV="${OGLIVEFILE##*-}"; OGLIVEREV="${OGLIVEREV%%.*}" - OGLIVEKRNL="$(echo $OGLIVEFILE|cut -f3- -d-)"; OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEREV.*}" - OGLIVEARCH="$(echo $OGLIVEFILE|awk -F- '{print $(NF-1)}')" + OGLIVEKRNL="$(echo "$OGLIVEFILE" | cut -f3- -d-)"; OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEREV.*}" + OGLIVEARCH="$(echo "$OGLIVEFILE" | awk -F- '{print $(NF-1)}')" case "$OGLIVEARCH" in i386|amd64) OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEARCH}" ;; @@ -291,117 +291,71 @@ function install() { esac OGLIVEDIR="$TFTPDIR/$DEFOGLIVE-${OGLIVEKRNL%%-*}-$OGLIVEARCH-$OGLIVEREV" OGLIVEDIR="${OGLIVEDIR/amd64-/}" - #OGLIVEDIR="$TFTPDIR/$DEFOGLIVE-$OGLIVEDIST-$OGLIVEKRNL-$OGLIVEARCH-$OGLIVEREV" - OGINITRD=$OGLIVEDIR/oginitrd.img - # Imprimir los valores de las variables - echo "OGLIVEFILE: $OGLIVEFILE" - echo "OGLIVEDIST: $OGLIVEDIST" - echo "OGLIVEKRNL: $OGLIVEKRNL" - echo "OGLIVEARCH: $OGLIVEARCH" - echo "OGLIVEREV: $OGLIVEREV" - echo "OGLIVEDIR: $OGLIVEDIR" - echo "OGINITRD: $OGINITRD" - - # Pausar la ejecución para que el usuario revise los valores - read -p "Presione cualquier tecla para continuar con la instalación..." - [ ! -r $OGINITRD ] && OGINITRD=$TFTPDIR/$DEFOGLIVE/oginitrd.img - if [ -r $OGINITRD ]; then - echo "Tipo de compresión: $COMPRESS" + OGINITRD="$OGLIVEDIR/oginitrd.img" + + [ ! -r "$OGINITRD" ] && OGINITRD="$TFTPDIR/$DEFOGLIVE/oginitrd.img" + if [ -r "$OGINITRD" ]; then COMPRESS=$(file -b "$OGINITRD" | awk '{print tolower($1);}') - SAMBAPASS=$($COMPRESS -dc $OGINITRD | \ + SAMBAPASS=$($COMPRESS -dc "$OGINITRD" | \ cpio -i --to-stdout scripts/ogfunctions 2>/dev/null | \ sed -n '/^[ \t].*OPTIONS=/s/.*pass=\(\w*\).*/\1/p') - echo "Contraseña de Samba extraída: $SAMBAPASS" fi - rm -fr ${OGLIVEDIR}.old 2>/dev/null - mv -f $OGLIVEDIR ${OGLIVEDIR}.old 2>/dev/null - # Changes to a generic TMPDIR name - #TMPDIR=/tmp/${OGLIVEFILE%.iso} + rm -fr "${OGLIVEDIR}.old" 2>/dev/null + mv -f "$OGLIVEDIR" "${OGLIVEDIR}.old" 2>/dev/null + TMPDIR=/tmp/$DOWNLOADDIR/ogLive - # TMPDIR for SQUASHFS mount TMPDIR_SQUASHFS=/tmp/ogclient_mount - # Antes del montaje le cambiamos el nombre a la iso por un nombre generico - mv -f $OGLIVEFILE $DOWNLOADDIR/oglive.iso 2>/dev/null || { echo "{\"status\": \"error\", \"error\": \"Cannot rename $OGLIVEFILE to oglive.iso.\"}"; exit 1; } - OGLIVEFILE=$DOWNLOADDIR/oglive.iso - # TMPDIR=/tmp/oglive - mkdir -p $OGLIVEDIR $TMPDIR $TMPDIR_SQUASHFS - if [ ! -d "$OGLIVEDIR" ]; then - echo "{\"status\": \"error\", \"error\": \"Failed to create or access directory $OGLIVEDIR.\"}" - exit 1 - fi - - if [ ! -d "$TMPDIR" ]; then - echo "{\"status\": \"error\", \"error\": \"Failed to create or access directory $TMPDIR.\"}" - exit 1 - fi - - if [ ! -d "$TMPDIR_SQUASHFS" ]; then - echo "{\"status\": \"error\", \"error\": \"Failed to create or access directory $TMPDIR_SQUASHFS.\"}" - exit 1 - fi + mv -f "$OGLIVEFILE" "$DOWNLOADDIR/oglive.iso" 2>/dev/null || { echo "{\"error\": \"RENAME_FAILED\", \"message\": \"Cannot rename $OGLIVEFILE to oglive.iso.\"}"; exit 500; } + OGLIVEFILE="$DOWNLOADDIR/oglive.iso" + + mkdir -p "$OGLIVEDIR" "$TMPDIR" "$TMPDIR_SQUASHFS" + [ ! -d "$OGLIVEDIR" ] && { echo "{\"error\": \"DIR_CREATION_FAILED\", \"message\": \"Failed to create/access directory $OGLIVEDIR.\"}"; exit 500; } + [ ! -d "$TMPDIR" ] && { echo "{\"error\": \"DIR_CREATION_FAILED\", \"message\": \"Failed to create/access directory $TMPDIR.\"}"; exit 500; } + [ ! -d "$TMPDIR_SQUASHFS" ] && { echo "{\"error\": \"DIR_CREATION_FAILED\", \"message\": \"Failed to create/access directory $TMPDIR_SQUASHFS.\"}"; exit 500; } + trap "umount $TMPDIR; rm -fr $TMPDIR" 1 2 3 6 9 15 - # sudo mount -o loop,ro $OGLIVEFILE $TMPDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"mount failed.\"}"; exit 1; } - # Asumimos que esta el montaje añadido al fstab - # La linea fstab es la siguiente: /opt/ogboot/lib/oglive.iso /tmp/opt/ogboot/lib/ogLive iso9660 loop,ro,user 0 0 - mount $OGLIVEFILE >/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; } - chmod -R u+w $OGLIVEDIR || { echo "{\"status\": \"error\", \"error\": \"Failed to change permissions.\"}"; exit 1; } - umount $TMPDIR >/dev/null 2>&1 - if [ ! -f $INFOFILE ]; then - rm -f $TFTPDIR/$DEFOGLIVE $TFTPDIR/$OGCLIENT - 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; } + 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; } + chmod -R u+w "$OGLIVEDIR" || { echo "{\"error\": \"PERMISSION_CHANGE_FAILED\", \"message\": \"Failed to change permissions for $OGLIVEDIR.\"}"; exit 500; } + umount "$TMPDIR" >/dev/null 2>&1 + + if [ ! -f "$INFOFILE" ]; then + rm -f "$TFTPDIR/$DEFOGLIVE" "$TFTPDIR/$OGCLIENT" + ln -vfs "$(basename "$OGLIVEDIR")" "$TFTPDIR/$DEFOGLIVE" >/dev/null 2>&1 || { echo "{\"error\": \"LINK_FAILED\", \"message\": \"Linking to $TFTPDIR/$DEFOGLIVE failed.\"}"; exit 500; } + ln -vfs "$DEFOGLIVE" "$TFTPDIR/$OGCLIENT" >/dev/null 2>&1 || { echo "{\"error\": \"LINK_FAILED\", \"message\": \"Linking to $TFTPDIR/$OGCLIENT failed.\"}"; exit 500; } fi if [ -n "$SAMBAPASS" ]; then - #echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"setsmbpass failed with SAMBAPASS.\"}"; exit 1; } - echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" || { echo "{\"status\": \"error\", \"error\": \"setsmbpass failed with SAMBAPASS.\"}"; exit 1; } + echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename "$OGLIVEDIR")" >/dev/null 2>&1 || { echo "{\"error\": \"SET_SMBPASS_FAILED\", \"message\": \"Failed to set Samba password with SAMBAPASS.\"}"; exit 500; } else - $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" || { echo "{\"status\": \"error\", \"error\": \"setsmbpass failed no SAMBAPASS.\"}"; exit 1; } + $OPENGNSYS/bin/setsmbpass "$(basename "$OGLIVEDIR")" >/dev/null 2>&1 || { echo "{\"error\": \"SET_SMBPASS_FAILED\", \"message\": \"Failed to set Samba password without SAMBAPASS.\"}"; exit 500; } fi - 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; } - sudo chown -R :opengnsys $OGLIVEDIR >/dev/null 2>&1 || { echo "{\"status\": \"error\", \"error\": \"chown failed.\"}"; exit 1; } - OGSQFS=$OGLIVEDIR/ogclient.sqfs + find -L "$OGLIVEDIR" -type d -exec chmod 755 {} \; >/dev/null 2>&1 || { echo "{\"error\": \"CHMOD_FAILED\", \"message\": \"Failed to change permissions for directories in $OGLIVEDIR.\"}"; exit 500; } + find -L "$OGLIVEDIR" -type f -exec chmod 644 {} \; >/dev/null 2>&1 || { echo "{\"error\": \"CHMOD_FAILED\", \"message\": \"Failed to change permissions for files in $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; } + + OGSQFS="$OGLIVEDIR/ogclient.sqfs" trap "exit 0" SIGINT TMPDIR=/tmp/oglive if mountpoint -q "$TMPDIR"; then - echo "$TMPDIR ya está montado, desmontando primero..." - umount $TMPDIR >/dev/null 2>&1 - if [ $? -ne 0 ]; then - echo "Error: No se pudo desmontar $TMPDIR" - exit 1 - fi + umount "$TMPDIR" >/dev/null 2>&1 || { echo "{\"error\": \"UMOUNT_FAILED\", \"message\": \"Failed to unmount $TMPDIR.\"}"; exit 500; } fi - echo "montando $TMPDIR_SQUASHFS" - if mount $TMPDIR_SQUASHFS ; then - RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - echo "RSYNCSERV (versión en el servidor): $RSYNCSERV" - #RSYNCCLNT=$(sudo chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - RSYNCCLNT=$($TMPDIR_SQUASHFS/usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - echo "RSYNCCLNT (versión en el cliente montado): $RSYNCCLNT" - if [ -z "$RSYNCSERV" ] || [ "$RSYNCSERV" -gt "${RSYNCCLNT:-1}" ]; then - if [ -e "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" ]; then - mv -f "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" "$OPENGNSYS/client/bin/rsync" 2>/dev/null - fi - else - if [ -e "$OPENGNSYS/client/bin/rsync" ]; then - mv -f "$OPENGNSYS/client/bin/rsync" "$OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')" - fi - fi - umount $TMPDIR_SQUASHFS - rmdir $TMPDIR_SQUASHFS || sudo rm -rf $TMPDIR_SQUASHFS - fi - echo "finished mount squashfs" - # sudo rm -f "$OGLIVEFILE" - CHECKSUM_FILE="$OGLIVEDIR/ogclient.sqfs.sum" - if [ -f "$CHECKSUM_FILE" ]; then - OGLIVEID=$(cat "$CHECKSUM_FILE") + + mount "$TMPDIR_SQUASHFS" || { echo "{\"error\": \"MOUNT_FAILED\", \"message\": \"Failed to mount $TMPDIR_SQUASHFS.\"}"; exit 500; } + RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}') + RSYNCCLNT=$($TMPDIR_SQUASHFS/usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') + if [ -z "$RSYNCSERV" ] || [ "$RSYNCSERV" -gt "${RSYNCCLNT:-1}" ]; then + [ -e "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" ] && mv -f "$OPENGNSYS/client/bin/rsync-$RSYNCSERV" "$OPENGNSYS/client/bin/rsync" 2>/dev/null else - OGLIVEID="N/A" # Si no existe el archivo, asignamos un valor por defecto + [ -e "$OPENGNSYS/client/bin/rsync" ] && mv -f "$OPENGNSYS/client/bin/rsync" "$OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')" fi - # Crear el archivo JSON con los datos del ogLive instalado + umount "$TMPDIR_SQUASHFS" || sudo rm -rf "$TMPDIR_SQUASHFS" + + CHECKSUM_FILE="$OGLIVEDIR/ogclient.sqfs.sum" + [ -f "$CHECKSUM_FILE" ] && OGLIVEID=$(cat "$CHECKSUM_FILE") || OGLIVEID="N/A" + jq -n \ --arg OGLIVEDIST "$OGLIVEDIST" \ --arg OGLIVEKRNL "$OGLIVEKRNL" \ @@ -416,10 +370,8 @@ function install() { OGLIVEDIR: $OGLIVEDIR }' > "$OGLIVEDIR/oglive_info.json" - # Verificar que el archivo JSON fue creado - if [ ! -f "$OGLIVEDIR/oglive_info.json" ]; then - echo "{\"status\": \"error\", \"error\": \"oglive_info,json failed.\"}"; exit 1; - fi + [ ! -f "$OGLIVEDIR/oglive_info.json" ] && { echo "{\"error\": \"JSON_CREATION_FAILED\", \"message\": \"Failed to create oglive_info.json.\"}"; exit 500; } + JSON_OUTPUT=$(jq -n \ --arg id "$OGLIVEID" \ --arg dist "$OGLIVEDIST" \ @@ -430,10 +382,10 @@ function install() { '{status: "success", message: {id: $id, distribution: $dist, kernel: $krnl, architecture: $arch, revision: $rev, directory: $dir}}') echo "$JSON_OUTPUT" + exit 0 } - # Uninstall an ogLive client. function uninstall() { local CHECKSUM DIR DEFAULT_OGLIVE_DIR DEFAULT_CHECKSUM @@ -737,11 +689,9 @@ function check_services_status() { 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 }') diff --git a/config/services.yaml b/config/services.yaml index d8590f3..a3ed921 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -25,3 +25,6 @@ services: App\OgBootBundle\Controller\: resource: '../src/OgBootBundle/Controller' tags: ['controller.service_arguments'] + # Register the OgLiveInstallCommand explicitly to ensure it's detected + OgBootBundle\Command\OgLiveInstallCommand: + tags: ['console.command'] diff --git a/src/OgBootBundle/Controller/OgBootController.php b/src/OgBootBundle/Controller/OgBootController.php index a1e61b6..528eb57 100644 --- a/src/OgBootBundle/Controller/OgBootController.php +++ b/src/OgBootBundle/Controller/OgBootController.php @@ -13,6 +13,7 @@ use App\OgBootBundle\Message\InstallOgliveMessage; use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; +use Symfony\Component\Process\Process; use Exception; @@ -58,7 +59,6 @@ Crear plantilla - POST /ogboot/pxe-templates Regenerar plantilla - PUT /ogboot/pxe-templates */ - /** * @Route("/ogboot/v1/status", name="getStatus", methods={"GET"}) * @OA\Get( @@ -70,44 +70,109 @@ Regenerar plantilla - PUT /ogboot/pxe-templates * @OA\JsonContent( * type="object", * @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="total", type="string", example="20G"), + * @OA\Property(property="used", type="string", example="15G"), + * @OA\Property(property="available", type="string", example="5G"), + * @OA\Property(property="percentage", type="string", example="75%") * ), - * @OA\Property(property="default_oglive", type="string"), - * @OA\Property(property="installed_oglives", type="array", @OA\Items(type="string")) + * @OA\Property(property="default_oglive", type="string", example="ogLive-5.11.0-r20210413"), + * @OA\Property( + * property="installed_oglives", + * type="array", + * @OA\Items(ref="#/components/schemas/OgLive") + * ), + * @OA\Property(property="services_status", type="object", + * @OA\Property(property="service_name", type="string", example="nginx"), + * @OA\Property(property="status", type="string", example="running") + * ) + * ) + * ), + * @OA\Response( + * response=404, + * description="No ogLive clients found or no default ogLive client available", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="error", type="string", example="NOT_FOUND"), + * @OA\Property(property="message", type="string", example="No default or installed ogLives found.") + * ) + * ), + * @OA\Response( + * response=500, + * description="Server error occurred while retrieving the status", + * @OA\JsonContent( + * oneOf={ + * @OA\Schema( + * @OA\Property(property="error", type="string", example="FAILED_TO_RETRIEVE_DISK_USAGE"), + * @OA\Property(property="details", type="string", example="Unknown error") + * ), + * @OA\Schema( + * @OA\Property(property="error", type="string", example="FAILED_TO_RETRIEVE_OGLIVE_CONFIGURATION"), + * @OA\Property(property="details", type="string", example="Unknown error") + * ), + * @OA\Schema( + * @OA\Property(property="error", type="string", example="FAILED_TO_RETRIEVE_SERVICES_STATUS"), + * @OA\Property(property="details", type="string", example="Unknown error") + * ) + * } * ) * ) * ) */ + public function getStatus(): Response { - // Call oglivecli to get disk usage - $diskUsageResult = $this->curlRequestService->callOgLive("disk_usage"); + // Llamar a oglivecli para obtener el uso del disco + $diskUsageResponse = $this->curlRequestService->callOgLive("disk_usage"); + $diskUsageResult = $diskUsageResponse['output']; + $diskUsageExitCode = $diskUsageResponse['exitCode']; - 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); + if ($diskUsageExitCode !== 0) { + return new JsonResponse( + ['error' => 'FAILED_TO_RETRIEVE_DISK_USAGE', 'details' => $diskUsageResult['error'] ?? 'Unknown error'], + Response::HTTP_INTERNAL_SERVER_ERROR + ); } - // Call oglivecli to get installed oglives and default oglives - $ogLiveConfigResult = $this->curlRequestService->callOgLive("list_installed_oglives"); + // Llamar a oglivecli para obtener la configuración de los oglives instalados y el oglive por defecto + $ogLiveResponse = $this->curlRequestService->callOgLive("list_installed_oglives"); + $ogLiveConfigResult = $ogLiveResponse['output']; + $ogLiveExitCode = $ogLiveResponse['exitCode']; - 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); + if ($ogLiveExitCode !== 0) { + return new JsonResponse( + ['error' => 'FAILED_TO_RETRIEVE_OGLIVE_CONFIGURATION', 'details' => $ogLiveConfigResult['error'] ?? 'Unknown error'], + Response::HTTP_INTERNAL_SERVER_ERROR + ); } - // Call oglivecli to get installed oglives and default oglives - $servicesStatusResult = $this->curlRequestService->callOgLive("check_services_status"); + // Llamar a oglivecli para obtener el estado de los servicios + $servicesStatusResponse = $this->curlRequestService->callOgLive("check_services_status"); + $servicesStatusResult = $servicesStatusResponse['output']; + $servicesStatusExitCode = $servicesStatusResponse['exitCode']; - 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); + if ($servicesStatusExitCode !== 0) { + return new JsonResponse( + ['error' => 'FAILED_TO_RETRIEVE_SERVICES_STATUS', 'details' => $servicesStatusResult['error'] ?? 'Unknown error'], + Response::HTTP_INTERNAL_SERVER_ERROR + ); } + // Verificar si las claves 'default_oglive' e 'installed_ogLives' existen en la respuesta de oglivecli + $defaultOglive = $ogLiveConfigResult['default_oglive'] ?? null; + $installedOglives = $ogLiveConfigResult['installed_ogLives'] ?? []; + + if ($defaultOglive === null || empty($installedOglives)) { + return new JsonResponse( + ['error' => 'NOT_FOUND', 'message' => 'No default or installed ogLives found.'], + Response::HTTP_NOT_FOUND + ); + } + + // Formatear la respuesta final con todos los datos $response = [ 'disk_usage' => $diskUsageResult, - 'default_oglive' => $ogLiveConfigResult['default_oglive'], - 'installed_oglives' => $ogLiveConfigResult['installed_ogLives'], + 'default_oglive' => $defaultOglive, + 'installed_oglives' => $installedOglives, 'services_status' => $servicesStatusResult ]; @@ -437,61 +502,50 @@ public function setOgliveDefault(Request $request): Response * ) */ +public function installOglive(Request $request): JsonResponse +{ + // Obtener los datos del cuerpo de la petición + $data = json_decode($request->getContent(), true); - public function installOglive(Request $request): JsonResponse - { - // Obtener los datos del cuerpo de la petición - $data = json_decode($request->getContent(), true); - - if (!isset($data['url']) || !isset($data['id'])) { - return new JsonResponse(['error' => 'Invalid input data'], JsonResponse::HTTP_BAD_REQUEST); - } - - // Obtener la URL del ISO y el ID de la transacción - $isoUrl = $data['url']; - $transactionId = $data['id']; - - try { - // Llamar al servicio para iniciar la instalación - $installResult = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoUrl)); - - // Verificar el resultado de la instalación - $status = 'success'; - $messageText = 'ogLive client installed successfully'; - - if (is_array($installResult) && isset($installResult['success']) && $installResult['success'] === false) { - $status = 'failure'; - $messageText = $installResult['error']; - } - - // Preparar los datos para el webhook - $webhookData = [ - 'ogCoreId' => $transactionId, - 'status' => $status, - 'message' => $messageText, - 'details' => $installResult - ]; - - // Obtener la URL del webhook desde el archivo .env - $webhookUrl = $this->params->get('OGCORE_API_URL'); - // Llamar al webhook para notificar el resultado - $this->notifyWebhook($webhookUrl, $webhookData); - - // Responder que la instalación se ha completado - return new JsonResponse([ - 'success' => 'ogLive client installation completed', - 'message' => $installResult - ], JsonResponse::HTTP_OK); - - } catch (Exception $e) { - // Si ocurre algún error durante el proceso - return new JsonResponse([ - 'error' => 'Failed to complete ogLive installation', - 'details' => $e->getMessage() - ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); - } + if (!isset($data['url']) || !isset($data['id'])) { + return new JsonResponse(['error' => 'Invalid input data'], JsonResponse::HTTP_BAD_REQUEST); } + // Obtener la URL del ISO y el ID de la transacción + $isoUrl = $data['url']; + $transactionId = $data['id']; + + try { + // Ejecutar el comando Symfony en segundo plano + $consolePath = $this->params->get('kernel.project_dir') . '/bin/console'; + $this->logger->info($consolePath); + $process = new Process([ + 'php', + $consolePath, + 'oglive:install', + $isoUrl, // Sin escapeshellarg + $transactionId // Sin escapeshellarg, + ]); + $commandLine = $process->getCommandLine(); + $this->logger->info('Command to be executed: ' . $commandLine); + #$process->start(); // Ejecuta en segundo plano + $process->setTimeout(null); + $process->disableOutput(); + $process->start(); + + return new JsonResponse([ + 'success' => 'ogLive client installation started', + 'transaction_id' => $transactionId + ], JsonResponse::HTTP_ACCEPTED); + + } catch (Exception $e) { + // Si ocurre algún error durante el proceso de inicio + return new JsonResponse([ + 'error' => 'Failed to initiate ogLive installation', + 'details' => $e->getMessage() + ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR); + } +} /** * Enviar el resultado al webhook * diff --git a/src/OgBootBundle/Service/CurlRequestService.php b/src/OgBootBundle/Service/CurlRequestService.php index 039ccee..bba89d9 100644 --- a/src/OgBootBundle/Service/CurlRequestService.php +++ b/src/OgBootBundle/Service/CurlRequestService.php @@ -56,6 +56,7 @@ public function callOgLive($parameter) // Decodificar la salida JSON si es posible $decodedOutput = json_decode($outputString, true); error_log('Decoded Output: ' . print_r($decodedOutput, true)); + error_log('exitCode ' . $exitCode); return [ 'output' => $decodedOutput, // Retorna la salida decodificada (JSON) 'exitCode' => $exitCode // Retorna el código de salida del comando