refs #649 adds webhook sender to notify when is installed oglive to the ogcore

ogboot_debian_installer
Luis Gerardo Romero Garcia 2024-09-06 07:43:33 +00:00
parent ad7a91ce05
commit a11051c05f
1 changed files with 106 additions and 28 deletions

View File

@ -9,6 +9,10 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\OgBootBundle\Message\InstallOgliveMessage;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Exception;
@ -20,11 +24,14 @@ class OgBootController
*/
private $curlRequestService;
public function __construct(CurlRequestService $curlRequestService, LoggerInterface $logger)
private $httpClient;
private $params;
public function __construct(CurlRequestService $curlRequestService, LoggerInterface $logger, HttpClientInterface $httpClient, ParameterBagInterface $params)
{
$this->curlRequestService = $curlRequestService;
$this->logger = $logger;
$this->httpClient = $httpClient;
$this->params = $params; // Accedemos a las variables de entorno a través de ParameterBagInterface
}
/*Tabla de Contenido
@ -384,11 +391,6 @@ public function setOgliveDefault(Request $request): Response
return new JsonResponse(['message' => 'ogLive client set as default successfully'], Response::HTTP_OK);
}
/**
* @Route("/ogboot/v1/oglives/install", name="installOglive", methods={"POST"})
* @OA\Post(
@ -399,16 +401,22 @@ public function setOgliveDefault(Request $request): Response
* @OA\JsonContent(
* type="object",
* @OA\Property(
* property="iso_url",
* property="url",
* type="string",
* example="https://ognproject.evlt.uma.es/trac/downloads/ogLive-focal-5.13.0-27-beta-amd64-r20210706.5b4bf5f.iso",
* description="Full URL of the ogLive ISO to install"
* example="https://ognproject.evlt.uma.es/trac/downloads/ogLive-focal-5.11.0-22-generic-amd64-r20210413.992ebb9.iso",
* description="URL of the ogLive ISO to download and install"
* ),
* @OA\Property(
* property="id",
* type="string",
* example="12345",
* description="Unique transaction ID to track the ogLive installation process"
* )
* )
* ),
* @OA\Response(
* response=200,
* description="ogLive client installed successfully",
* description="ogLive client installation initiated",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="message", type="string"),
@ -417,11 +425,16 @@ public function setOgliveDefault(Request $request): Response
* ),
* @OA\Response(
* response=400,
* description="Invalid input data"
* description="Invalid input data",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="error", type="string"),
* @OA\Property(property="details", type="string")
* )
* ),
* @OA\Response(
* response=500,
* description="Failed to install ogLive client",
* description="Failed to initiate ogLive installation",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="error", type="string"),
@ -430,24 +443,88 @@ public function setOgliveDefault(Request $request): Response
* )
* )
*/
public function installOglive(Request $request): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data['iso_url'])) {
return new JsonResponse(['error' => 'Invalid input data'], Response::HTTP_BAD_REQUEST);
}
$isoUrl = $data['iso_url'];
// No usar escapeshellarg, sino simplemente agregar las comillas simples para que el comando se interprete correctamente
$result = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoUrl));
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);
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([
'message' => 'ogLive client installation completed',
'details' => $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);
}
}
return new JsonResponse(['message' => 'ogLive client installed successfully', 'details' => $result], Response::HTTP_OK);
}
/**
* Enviar el resultado al webhook
*
* @param string $webhookUrl
* @param array $data Datos para enviar al webhook
*/
private function notifyWebhook(string $webhookUrl, array $data): void
{
try {
error_log('Webhook URL: ' . $webhookUrl);
$this->logger->info('Webhook URL: ' . $webhookUrl);
error_log('Data being sent to webhook: ' . json_encode($data));
$this->logger->info('Data being sent to webhook: ' . json_encode($data));
$this->httpClient->request('POST', $webhookUrl, [
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
'body' => json_encode($data),
]);
} catch (Exception $e) {
// Manejo de errores en la notificación del webhook
error_log('Error sending webhook notification: ' . $e->getMessage());
}
}
/**
* @Route("/ogboot/v1/oglives/{checksum}", name="uninstallOglive", methods={"DELETE"})
@ -576,7 +653,8 @@ public function getBootFiles(): JsonResponse
* response=200,
* description="Successful operation",
* @OA\JsonContent(
* type="object",
* type="obj/opt/ogboot/var/log
* ect",
* @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"),