diff --git a/src/OgBootBundle/Controller/OgBootController.php b/src/OgBootBundle/Controller/OgBootController.php index a635eb4..bb91d72 100644 --- a/src/OgBootBundle/Controller/OgBootController.php +++ b/src/OgBootBundle/Controller/OgBootController.php @@ -737,7 +737,6 @@ public function uninstallOglive(string $checksum): Response - /** * @Route("/ogboot/v1/pxes", name="get_boot_files", methods={"GET"}) * @OA\Get( @@ -749,7 +748,12 @@ public function uninstallOglive(string $checksum): Response * @OA\JsonContent( * type="object", * @OA\Property( - * property="boot_files", + * property="success", + * type="string", + * example="Boot files retrieved successfully" + * ), + * @OA\Property( + * property="message", * type="array", * @OA\Items( * type="string", @@ -766,24 +770,42 @@ public function uninstallOglive(string $checksum): Response */ public function getBootFiles(): JsonResponse { - $directory = '/opt/ogboot/tftpboot/ipxe_scripts'; + // Verificar si el directorio existe + if (!is_dir($directory)) { + return new JsonResponse( + ['error' => 'SERVER_ERROR', 'message' => 'Failed to retrieve boot files: directory not found.'], + Response::HTTP_INTERNAL_SERVER_ERROR + ); + } + // Obtener la lista de archivos $files = scandir($directory); - + // Filtrar los archivos que comiencen con '01-' y excluir directorios $bootFiles = array_filter($files, function ($file) use ($directory) { return !is_dir($directory . '/' . $file) && strpos($file, '01-') === 0; }); + // Si no se encuentran archivos + if (empty($bootFiles)) { + return new JsonResponse( + ['error' => 'NOT_FOUND', 'message' => 'No boot files found.'], + Response::HTTP_NOT_FOUND + ); + } + + // Formatear la respuesta de éxito $response = [ - 'boot_files' => array_values($bootFiles) + 'success' => 'Boot files retrieved successfully', + 'message' => array_values($bootFiles) ]; return new JsonResponse($response, Response::HTTP_OK); } + /** * @Route("/ogboot/v1/pxes/{mac}", name="ogboot_get_boot_file_with_params", methods={"GET"}) * @OA\Get( @@ -801,55 +823,74 @@ public function getBootFiles(): JsonResponse * description="Successful operation", * @OA\JsonContent( * type="object", - * @OA\Property(property="template_name", type="string", description="Template name", example="pxe"), - * @OA\Property(property="mac", type="string", description="MAC address", example="00:50:56:22:11:12"), - * @OA\Property(property="lang", type="string", description="Language", example="es_ES.UTF-8"), - * @OA\Property(property="ip", type="string", description="IP address", example="192.168.2.11"), - * @OA\Property(property="server_ip", type="string", description="Server IP address", example="192.168.2.1"), - * @OA\Property(property="router", type="string", description="Router", example="192.168.2.1"), - * @OA\Property(property="netmask", type="string", description="Netmask", example="255.255.255.0"), - * @OA\Property(property="computer_name", type="string", description="Computer name", example="pc11"), - * @OA\Property(property="netiface", type="string", description="Network interface", example="eth0"), - * @OA\Property(property="group", type="string", description="Group", example="Aula_virtual"), - * @OA\Property(property="ogrepo", type="string", description="Repository IP", example="192.168.2.1"), - * @OA\Property(property="oglive", type="string", description="Live server IP", example="192.168.2.1"), - * @OA\Property(property="oglog", type="string", description="Log server IP", example="192.168.2.1"), - * @OA\Property(property="ogshare", type="string", description="Share server IP", example="192.168.2.1"), - * @OA\Property(property="oglivedir", type="string", description="Live directory", example="ogLive"), - * @OA\Property(property="ogprof", type="string", description="Is professor", example="false"), - * @OA\Property(property="hardprofile", type="string", description="Hardware profile", example=""), - * @OA\Property(property="ogntp", type="string", description="NTP server", example=""), - * @OA\Property(property="ogdns", type="string", description="DNS server", example=""), - * @OA\Property(property="ogproxy", type="string", description="Proxy server", example=""), - * @OA\Property(property="ogunit", type="string", description="Unit directory", example=""), - * @OA\Property(property="resolution", type="string", description="Screen resolution", example="788") + * @OA\Property(property="success", type="string", example="Boot file retrieved successfully"), + * @OA\Property( + * property="message", + * type="object", + * @OA\Property(property="template_name", type="string", description="Template name (required)", example="pxe"), + * @OA\Property(property="mac", type="string", description="MAC address (required)", example="00:50:56:22:11:12"), + * @OA\Property(property="lang", type="string", description="Language (optional)", example="es_ES.UTF-8"), + * @OA\Property(property="ip", type="string", description="IP address (optional)", example="192.168.2.11"), + * @OA\Property(property="server_ip", type="string", description="Server IP address (optional)", example="192.168.2.1"), + * @OA\Property(property="router", type="string", description="Router (optional)", example="192.168.2.1"), + * @OA\Property(property="netmask", type="string", description="Netmask (optional)", example="255.255.255.0"), + * @OA\Property(property="computer_name", type="string", description="Computer name (optional)", example="pc11"), + * @OA\Property(property="netiface", type="string", description="Network interface (optional)", example="eth0"), + * @OA\Property(property="group", type="string", description="Group (optional)", example="Aula_virtual"), + * @OA\Property(property="ogrepo", type="string", description="Repository IP (optional)", example="192.168.2.1"), + * @OA\Property(property="oglive", type="string", description="Live server IP (optional)", example="192.168.2.1"), + * @OA\Property(property="oglog", type="string", description="Log server IP (optional)", example="192.168.2.1"), + * @OA\Property(property="ogshare", type="string", description="Share server IP (optional)", example="192.168.2.1"), + * @OA\Property(property="oglivedir", type="string", description="Live directory (optional)", example="ogLive"), + * @OA\Property(property="ogprof", type="string", description="Is professor (optional)", example="false"), + * @OA\Property(property="hardprofile", type="string", description="Hardware profile (optional)", example=""), + * @OA\Property(property="ogntp", type="string", description="NTP server (optional)", example=""), + * @OA\Property(property="ogdns", type="string", description="DNS server (optional)", example=""), + * @OA\Property(property="ogproxy", type="string", description="Proxy server (optional)", example=""), + * @OA\Property(property="ogunit", type="string", description="Unit directory (optional)", example=""), + * @OA\Property(property="resolution", type="string", description="Screen resolution (optional)", example="788") + * ) + * ) + * ), + * @OA\Response( + * response=404, + * description="No boot file found for the specified MAC address", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="error", type="string", example="NOT_FOUND"), + * @OA\Property(property="message", type="string", example="No boot file found for the specified MAC address.") * ) * ), * @OA\Response( * response=500, - * description="Failed to retrieve boot file" + * description="Internal server error" * ) * ) */ + + public function getBootFile(string $mac): Response { // Ruta donde están alojados los archivos de arranque $directory = '/opt/ogboot/tftpboot/ipxe_scripts'; - // Genera el nombre del archivo basado en la dirección MAC + // Generar el nombre del archivo basado en la dirección MAC $mac = $this->validateAndFormatMac($mac ?? null); $fileName = "01-" . $mac; - $filePath = "$directory/$fileName"; - + $this->logger->info('FilePath: ' . $filePath); + // Verificar si el archivo existe if (!file_exists($filePath)) { - return new JsonResponse(['error' => 'No se encontró ningún archivo de arranque con la dirección MAC especificada'], Response::HTTP_NOT_FOUND); + return new JsonResponse( + ['error' => 'NOT_FOUND', 'message' => 'No boot file found for the specified MAC address.'], + Response::HTTP_NOT_FOUND + ); } $content = file_get_contents($filePath); - $templateName = 'desconocido'; // Valor por defecto si no se encuentra la plantilla + $templateName = 'unknown'; // Valor por defecto si no se encuentra la plantilla $contentLines = explode("\n", $content); - + // Buscar la plantilla utilizada foreach ($contentLines as $line) { if (strpos($line, '#Template:') !== false) { @@ -860,20 +901,27 @@ public function getBootFile(string $mac): Response // Extraer los parámetros del contenido del archivo iPXE preg_match('/set kernelargs (.*)/', $content, $matches); - - // Si no encontramos 'kernelargs', podría ser un archivo de arranque por disco + + // Si no se encuentran 'kernelargs', podría ser un archivo de arranque por disco if (!isset($matches[1])) { - return new JsonResponse([ - 'template_name' => $templateName, - 'mac' => $mac, - 'message' => 'Archivo de arranque sin parámetros, posiblemente una plantilla de arranque por disco' - ], Response::HTTP_OK); + return new JsonResponse( + [ + 'success' => 'Boot file retrieved successfully', + 'message' => [ + 'template_name' => $templateName, + 'mac' => $mac, + 'message' => 'Boot file without parameters, possibly a disk boot template.' + ] + ], + Response::HTTP_OK + ); } + // Parsear los argumentos del kernel $kernelargs = $matches[1]; parse_str(str_replace(' ', '&', $kernelargs), $params); - // Crear la estructura del resultado, incluso si los parámetros son opcionales + // Crear la estructura del resultado $result = [ 'template_name' => $templateName, 'mac' => $mac, @@ -899,7 +947,11 @@ public function getBootFile(string $mac): Response 'resolution' => $params['vga'] ?? '', ]; - return new JsonResponse($result, Response::HTTP_OK); + // Formatear la respuesta de éxito + return new JsonResponse( + ['success' => 'Boot file retrieved successfully', 'message' => $result], + Response::HTTP_OK + ); } @@ -1081,87 +1133,98 @@ public function createBootFile(Request $request): JsonResponse ], Response::HTTP_OK); } +function validateAndFormatMac($mac) +{ + // Convertir a minúsculas para un formato uniforme + $mac = strtolower($mac); - function validateAndFormatMac($mac) - { - // Primero, convertir a mayúsculas para facilitar la comparación - $mac = strtoupper($mac); - - // Comprobar si la MAC tiene el formato correcto con dos puntos (ej. FC:AA:14:21:55:B9) - if (preg_match('/^([0-9A-F]{2}:){5}[0-9A-F]{2}$/', $mac)) { - return $mac; // MAC ya está en el formato correcto - } - - // Comprobar si la MAC tiene el formato sin los dos puntos (ej. FCAA142155B9) - if (preg_match('/^[0-9A-F]{12}$/', $mac)) { - // Insertar los dos puntos en la MAC y devolverla en el formato correcto - return strtoupper(implode(':', str_split($mac, 2))); - } - - // Si no cumple con ninguno de los formatos, devolver un error - return false; // MAC no válida + // Comprobar si la MAC tiene el formato correcto con dos puntos (ej. fc:aa:14:21:55:b9) + if (preg_match('/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/', $mac)) { + return $mac; // MAC ya está en el formato correcto } + // Comprobar si la MAC tiene el formato sin los dos puntos (ej. fcaa142155b9) + if (preg_match('/^[0-9a-f]{12}$/', $mac)) { + // Insertar los dos puntos en la MAC y devolverla en el formato correcto + return strtolower(implode(':', str_split($mac, 2))); + } + + // Si no cumple con ninguno de los formatos, devolver un error + return false; // MAC no válida +} + + /** * @Route("/ogboot/v1/pxes/{mac}", name="ogboot_delete_boot_file", methods={"DELETE"}) * @OA\Delete( * path="/ogboot/v1/pxes/{mac}", - * summary="Eliminar archivo de arranque", - * description="Elimina un archivo de arranque específico utilizando su dirección MAC.", + * summary="Delete PXE boot file", + * description="Delete a specific PXE boot file using its MAC address.", * @OA\Parameter( * name="mac", * in="path", - * description="La dirección MAC del cliente cuyo archivo de arranque se desea eliminar", + * description="MAC address of the client whose boot file is to be deleted", * required=true, * @OA\Schema(type="string", example="00:11:22:33:44:55") * ), * @OA\Response( * response=200, - * description="El archivo de arranque se eliminó correctamente", + * description="Boot file deleted successfully", * @OA\JsonContent( * type="object", - * @OA\Property(property="message", type="string", example="El archivo de arranque se eliminó correctamente") + * @OA\Property(property="success", type="string", example="Boot file deleted successfully"), + * @OA\Property(property="message", type="string", example="The boot file for MAC 00:11:22:33:44:55 has been deleted.") * ) * ), * @OA\Response( * response=404, - * description="No se encontró ningún archivo de arranque con la dirección MAC especificada", + * description="No boot file found for the specified MAC address", * @OA\JsonContent( * type="object", - * @OA\Property(property="error", type="string", example="No se encontró ningún archivo de arranque con la dirección MAC especificada") + * @OA\Property(property="error", type="string", example="No boot file found for the specified MAC address.") * ) * ), * @OA\Response( * response=500, - * description="Error al eliminar el archivo de arranque", + * description="Failed to delete the boot file", * @OA\JsonContent( * type="object", - * @OA\Property(property="error", type="string", example="Error al eliminar el archivo de arranque") + * @OA\Property(property="error", type="string", example="Failed to delete the boot file due to server error.") * ) * ) * ) */ - public function deleteBootFile(string $mac): Response - { - $directory = '/opt/ogboot/tftpboot/ipxe_scripts'; +public function deleteBootFile(string $mac): Response +{ + $directory = '/opt/ogboot/tftpboot/ipxe_scripts'; - $mac = $this->validateAndFormatMac($mac ?? null); + // Validar y formatear la dirección MAC + $mac = $this->validateAndFormatMac($mac ?? null); + $fileName = "01-" . $mac; + $filePath = "$directory/$fileName"; - $fileName = "01-" . $mac; - - $filePath = "$directory/$fileName"; - - if (!file_exists($filePath)) { - - return new JsonResponse(['error' => 'No se encontró ningún archivo de arranque con la dirección MAC especificada'], Response::HTTP_NOT_FOUND); - } - - if (!unlink($filePath)) { - - return new JsonResponse(['error' => 'Error al eliminar el archivo de arranque'], Response::HTTP_INTERNAL_SERVER_ERROR); - } - return new JsonResponse(['message' => 'El archivo de arranque se eliminó correctamente'], Response::HTTP_OK); + // Verificar si el archivo de arranque existe + if (!file_exists($filePath)) { + return new JsonResponse( + ['error' => 'NOT_FOUND', 'message' => 'No boot file found for the specified MAC address.'], + Response::HTTP_NOT_FOUND + ); } + + // Intentar eliminar el archivo de arranque + if (!unlink($filePath)) { + return new JsonResponse( + ['error' => 'SERVER_ERROR', 'message' => 'Failed to delete the boot file due to server error.'], + Response::HTTP_INTERNAL_SERVER_ERROR + ); + } + + // Respuesta exitosa con formato estándar + return new JsonResponse( + ['success' => 'Boot file deleted successfully', 'message' => "The boot file for MAC $mac has been deleted."], + Response::HTTP_OK + ); +} /** * @Route("/ogboot/v1/pxe-templates", methods={"GET"})