ogboot-log #6

Merged
lgromero merged 2 commits from ogboot-log into main 2025-01-13 10:36:04 +01:00
4 changed files with 1263 additions and 468 deletions

View File

@ -18,6 +18,11 @@ when@dev:
#chromephp: #chromephp:
# type: chromephp # type: chromephp
# level: info # level: info
syslog:
type: syslog
ident: "ogboot" # Puedes dar un nombre de identificador personalizado
level: info
channels: ["!event"]
console: console:
type: console type: console
process_psr_3_messages: false process_psr_3_messages: false
@ -60,3 +65,8 @@ when@prod:
channels: [deprecation] channels: [deprecation]
path: php://stderr path: php://stderr
formatter: monolog.formatter.json formatter: monolog.formatter.json
syslog:
type: syslog
ident: "ogboot" # Puedes dar un nombre de identificador personalizado
level: info
channels: ["!event"]

View File

@ -1,5 +1,7 @@
<?php <?php
namespace App\OgBootBundle\Command; namespace App\OgBootBundle\Command;
use App\OgBootBundle\Service\CurlRequestService; use App\OgBootBundle\Service\CurlRequestService;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
@ -7,8 +9,8 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Exception;
class OgLiveInstallCommand extends Command class OgLiveInstallCommand extends Command
{ {
@ -16,17 +18,22 @@ class OgLiveInstallCommand extends Command
private $curlRequestService; private $curlRequestService;
private $httpClient; private $httpClient;
private $logger; private $logger;
private $ogCoreApiUrl;
public function __construct(CurlRequestService $curlRequestService, HttpClientInterface $httpClient, LoggerInterface $logger, protected readonly string $ogCoreApiUrl) public function __construct(
{ CurlRequestService $curlRequestService,
HttpClientInterface $httpClient,
LoggerInterface $logger,
string $ogCoreApiUrl
) {
parent::__construct(); parent::__construct();
$this->curlRequestService = $curlRequestService; $this->curlRequestService = $curlRequestService;
#$this->httpClient = $httpClient;
$this->httpClient = HttpClient::create([ $this->httpClient = HttpClient::create([
'verify_peer' => false, // Ignorar la verificación del certificado SSL 'verify_peer' => false, // Ignorar la verificación del certificado SSL
'verify_host' => false, // Ignorar la verificación del nombre del host 'verify_host' => false, // Ignorar la verificación del nombre del host
]); ]);
$this->logger = $logger; // Añadimos el logger $this->logger = $logger;
$this->ogCoreApiUrl = $ogCoreApiUrl;
} }
protected function configure() protected function configure()
@ -41,101 +48,91 @@ protected function execute(InputInterface $input, OutputInterface $output)
{ {
ini_set('memory_limit', '-1'); ini_set('memory_limit', '-1');
ini_set('max_execution_time', '3000'); ini_set('max_execution_time', '3000');
$isoUrl = $input->getArgument('isoUrl');
$isoUrl = $input->getArgument('isoUrl');
$transactionId = $input->getArgument('transactionId'); $transactionId = $input->getArgument('transactionId');
// Iniciamos los logs para rastrear el proceso // Log inicial
$this->logger->info('Starting ogLive installation', ['transactionId' => $transactionId]); $this->logger->info('Starting ogLive installation process.', [
'transactionId' => $transactionId,
'isoUrl' => $isoUrl,
]);
try { try {
// Log: comenzando la descarga del ISO // Log: Iniciando la descarga
$this->logger->info('Starting download', ['isoUrl' => $isoUrl]); $this->logger->info('Initiating ISO download.', ['isoUrl' => $isoUrl]);
// Llamar al servicio para iniciar la instalación // Llamada al servicio para iniciar la descarga del ISO
$installResult = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoUrl)); $installResult = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoUrl));
// Log: descarga finalizada // Log: Descarga completada
$this->logger->info('Download finished', ['transactionId' => $transactionId, 'installResult' => $installResult]); $this->logger->info('ISO download completed.', [
'transactionId' => $transactionId,
'installResult' => $installResult,
]);
// Verificar el resultado de la instalación basado en el output del comando // Verificación de resultado
$status = 'success';
$messageText = 'ogLive client installed successfully';
$exitCode = $installResult['exitCode']; $exitCode = $installResult['exitCode'];
$status = ($exitCode === 0) ? 'success' : 'failure';
$messageText = $installResult['output']['message'] ?? 'Unknown error';
if (isset($installResult['output']['error'])) { if ($exitCode !== 0) {
// Si hay un error, asignar el estado y mensaje adecuado $this->logger->error('Installation failed.', [
$status = $installResult['output']['error']; 'transactionId' => $transactionId,
$messageText = $installResult['output']['message']; 'exitCode' => $exitCode,
'error' => $messageText,
// Log: la instalación falló ]);
$this->logger->error('Installation failed', ['transactionId' => $transactionId, 'error' => $messageText]);
} elseif ($installResult['exitCode'] !== 0) {
// Si hubo un exitCode distinto de 0, manejar como error desconocido
$status = 'UNKNOWN_ERROR';
$messageText = 'An unknown error occurred during the installation process.';
$this->logger->error('Unknown installation error', ['transactionId' => $transactionId, 'exitCode' => $installResult['exitCode']]);
} else { } else {
// Log: instalación completada con éxito $this->logger->info('Installation completed successfully.', [
$messageText = $installResult['output']['message']; 'transactionId' => $transactionId,
$this->logger->info('Installation completed successfully', ['transactionId' => $transactionId]); ]);
} }
// Preparar los datos para el webhook según el resultado // Preparar datos para el webhook
$webhookData = [ $webhookData = [
'ogCoreId' => $transactionId, 'ogCoreId' => $transactionId,
'status' => $status, 'status' => $status,
'code' => ($exitCode === 0) ? 200 : $exitCode, // Cambiar a 200 si es éxito 'code' => ($exitCode === 0) ? 200 : $exitCode,
'message' => $messageText, 'message' => $messageText,
]; ];
$this->logger->info('Installation completed with details', ['installResult' => $installResult]); $this->logger->info('Webhook data prepared.', ['webhookData' => $webhookData]);
$this->logger->info('Webhook data to be sent: ', ['webhookData' => $webhookData]);
#$webhookUrl = "https://172.17.8.90:8443/og-lives/install/webhook"; // Enviar al webhook
$webhookUrl = "{$this->ogCoreApiUrl}/og-lives/install/webhook"; $webhookUrl = "{$this->ogCoreApiUrl}/og-lives/install/webhook";
// Log: enviando datos al webhook $this->logger->info('Sending data to webhook.', ['webhookUrl' => $webhookUrl]);
$this->logger->info('Sending data to webhook', ['webhookUrl' => $webhookUrl, 'webhookData' => $webhookData]);
// Llamar al webhook para notificar el resultado
$this->notifyWebhook($webhookUrl, $webhookData); $this->notifyWebhook($webhookUrl, $webhookData);
$this->logger->info('Notify webhook con exito');
// Log: notificación al webhook finalizada
$this->logger->info('Webhook notification sent', ['transactionId' => $transactionId]);
} catch (Exception $e) { } catch (Exception $e) {
// Log: error en la instalación // Log de error
$this->logger->error('Failed to complete ogLive installation', ['transactionId' => $transactionId, 'exception' => $e->getMessage()]); $this->logger->error('Installation process failed.', [
'transactionId' => $transactionId,
'exception' => $e->getMessage(),
]);
// Manejar errores y enviar notificación de fallo al webhook // Enviar notificación de error al webhook
$webhookData = [ $webhookData = [
'ogCoreId' => $transactionId, 'ogCoreId' => $transactionId,
'status' => 'failure', 'status' => 'failure',
'code' => 500, 'code' => 500,
'message' => $e->getMessage() 'message' => $e->getMessage(),
]; ];
$webhookUrl = "https://172.17.8.90:8443/og-lives/install/webhook"; $webhookUrl = "{$this->ogCoreApiUrl}/og-lives/install/webhook";
$this->logger->info('Sending error notification to webhook.', ['webhookUrl' => $webhookUrl]);
$this->notifyWebhook($webhookUrl, $webhookData); $this->notifyWebhook($webhookUrl, $webhookData);
$this->logger->info('Notify webhook terminado con errores');
// Log: notificación de error enviada al webhook
$this->logger->info('Failure notification sent to webhook', ['transactionId' => $transactionId]);
} }
// Log: proceso de instalación terminado // Log finalización
$this->logger->info('Installation process ended', ['transactionId' => $transactionId]); $this->logger->info('Installation process ended.', ['transactionId' => $transactionId]);
return Command::SUCCESS; return Command::SUCCESS;
} }
/**
* Enviar el resultado al webhook
*/
private function notifyWebhook(string $webhookUrl, array $webhookData): void private function notifyWebhook(string $webhookUrl, array $webhookData): void
{ {
try { try {
$this->logger->info('Enter notify webhook'); $this->logger->info('Sending webhook notification.', ['webhookData' => $webhookData]);
$this->logger->info('Data to be sent', ['webhookData' => $webhookData]);
$this->httpClient->request('POST', $webhookUrl, [ $this->httpClient->request('POST', $webhookUrl, [
'headers' => [ 'headers' => [
'accept' => 'application/json', 'accept' => 'application/json',
@ -143,13 +140,12 @@ protected function execute(InputInterface $input, OutputInterface $output)
], ],
'body' => json_encode(['webhookData' => $webhookData]), 'body' => json_encode(['webhookData' => $webhookData]),
]); ]);
$this->logger->info('Webhook notification sent successfully.', ['webhookUrl' => $webhookUrl]);
// Log: éxito al enviar la notificación
$this->logger->info('Webhook data sent successfully', ['webhookUrl' => $webhookUrl, 'webhookData' => $webhookData]);
} catch (Exception $e) { } catch (Exception $e) {
// Log: error al enviar al webhook $this->logger->error('Error sending webhook notification.', [
$this->logger->error('Error sending webhook notification', ['webhookUrl' => $webhookUrl, 'exception' => $e->getMessage()]); 'webhookUrl' => $webhookUrl,
'exception' => $e->getMessage(),
]);
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -2,26 +2,31 @@
// src/OgBootBundle/Service/CurlRequestService.php // src/OgBootBundle/Service/CurlRequestService.php
namespace App\OgBootBundle\Service; namespace App\OgBootBundle\Service;
use Exception; use Exception;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
class CurlRequestService class CurlRequestService
{ {
private LoggerInterface $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function convertMaskToCIDR($mask) public function convertMaskToCIDR($mask)
{ {
$bits = 0; $bits = 0;
$mask = explode(".", $mask); $mask = explode(".", $mask);
foreach ($mask as $octect) foreach ($mask as $octet) {
$bits += strlen(str_replace("0", "", decbin($octect))); $bits += strlen(str_replace("0", "", decbin($octet)));
}
return $bits; return $bits;
} }
// src/Service/CurlRequestService.php
public function callOgLive($parameter) public function callOgLive($parameter)
{ {
// Ruta completa al script oglivecli // Ruta completa al script oglivecli
@ -32,38 +37,37 @@ public function callOgLive($parameter)
$action = array_shift($args); $action = array_shift($args);
// Registrar la acción y los argumentos // Registrar la acción y los argumentos
syslog(LOG_INFO, 'action ' . $action); $this->logger->debug('Action: ' . $action);
syslog(LOG_INFO, 'args ' . json_encode($args)); $this->logger->debug('Arguments: ' . json_encode($args));
// Limpiar los argumentos de comillas innecesarias // Limpiar los argumentos de comillas innecesarias
$cleanedArgs = array_map(function ($arg) { $cleanedArgs = array_map(function ($arg) {
return trim($arg, '\'\"'); return trim($arg, '\'\"');
}, $args); }, $args);
// Construir el comando final sin añadir comillas alrededor de cada elemento // Construir el comando final sin añadir comillas alrededor de cada elemento
$commandToRun = $ogLiveCliPath . ' ' . $action . ' ' . implode(' ', $cleanedArgs); $commandToRun = $ogLiveCliPath . ' ' . $action . ' ' . implode(' ', $cleanedArgs);
// Registrar el comando en syslog para depuración // Registrar el comando para depuración
$this->logger->debug('Command: ' . $commandToRun);
// Ejecutar el comando, capturando la salida y el código de salida // Ejecutar el comando, capturando la salida y el código de salida
$output = []; $output = [];
$exitCode = null; $exitCode = null;
exec($commandToRun, $output, $exitCode); // Ejecuta el comando, captura la salida y el código de salida exec($commandToRun, $output, $exitCode);
// Unir la salida en una sola cadena y registrar en syslog // Unir la salida en una sola cadena y registrar en el logger
$outputString = implode("\n", $output); $outputString = implode("\n", $output);
syslog(LOG_INFO, 'output ' . $outputString); $this->logger->debug('Output: ' . $outputString);
syslog(LOG_INFO, 'exitCode ' . $exitCode); $this->logger->debug('Exit Code: ' . $exitCode);
// Decodificar la salida JSON si es posible // Decodificar la salida JSON si es posible
$decodedOutput = json_decode($outputString, true); $decodedOutput = json_decode($outputString, true);
error_log('Decoded Output: ' . print_r($decodedOutput, true)); $this->logger->debug('Decoded Output: ' . print_r($decodedOutput, true));
error_log('exitCode ' . $exitCode);
return [ return [
'output' => $decodedOutput, // Retorna la salida decodificada (JSON) 'output' => $decodedOutput, // Retorna la salida decodificada (JSON)
'exitCode' => $exitCode // Retorna el código de salida del comando 'exitCode' => $exitCode // Retorna el código de salida del comando
]; ];
} }
} }