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:
# type: chromephp
# level: info
syslog:
type: syslog
ident: "ogboot" # Puedes dar un nombre de identificador personalizado
level: info
channels: ["!event"]
console:
type: console
process_psr_3_messages: false
@ -60,3 +65,8 @@ when@prod:
channels: [deprecation]
path: php://stderr
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
namespace App\OgBootBundle\Command;
use App\OgBootBundle\Service\CurlRequestService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
@ -7,8 +9,8 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Psr\Log\LoggerInterface;
use Exception;
class OgLiveInstallCommand extends Command
{
@ -16,17 +18,22 @@ class OgLiveInstallCommand extends Command
private $curlRequestService;
private $httpClient;
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();
$this->curlRequestService = $curlRequestService;
#$this->httpClient = $httpClient;
$this->httpClient = HttpClient::create([
'verify_peer' => false, // Ignorar la verificación del certificado SSL
'verify_host' => false, // Ignorar la verificación del nombre del host
]);
$this->logger = $logger; // Añadimos el logger
$this->httpClient = HttpClient::create([
'verify_peer' => false, // Ignorar la verificación del certificado SSL
'verify_host' => false, // Ignorar la verificación del nombre del host
]);
$this->logger = $logger;
$this->ogCoreApiUrl = $ogCoreApiUrl;
}
protected function configure()
@ -37,119 +44,108 @@ class OgLiveInstallCommand extends Command
->addArgument('transactionId', InputArgument::REQUIRED, 'ID de la transacción');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '3000');
$isoUrl = $input->getArgument('isoUrl');
protected function execute(InputInterface $input, OutputInterface $output)
{
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '3000');
$transactionId = $input->getArgument('transactionId');
$isoUrl = $input->getArgument('isoUrl');
$transactionId = $input->getArgument('transactionId');
// Iniciamos los logs para rastrear el proceso
$this->logger->info('Starting ogLive installation', ['transactionId' => $transactionId]);
// Log inicial
$this->logger->info('Starting ogLive installation process.', [
'transactionId' => $transactionId,
'isoUrl' => $isoUrl,
]);
try {
// Log: comenzando la descarga del ISO
$this->logger->info('Starting download', ['isoUrl' => $isoUrl]);
try {
// Log: Iniciando la descarga
$this->logger->info('Initiating ISO download.', ['isoUrl' => $isoUrl]);
// Llamar al servicio para iniciar la instalación
$installResult = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoUrl));
// Llamada al servicio para iniciar la descarga del ISO
$installResult = $this->curlRequestService->callOgLive("download " . escapeshellarg($isoUrl));
// Log: descarga finalizada
$this->logger->info('Download finished', ['transactionId' => $transactionId, 'installResult' => $installResult]);
// Log: Descarga completada
$this->logger->info('ISO download completed.', [
'transactionId' => $transactionId,
'installResult' => $installResult,
]);
// Verificar el resultado de la instalación basado en el output del comando
$status = 'success';
$messageText = 'ogLive client installed successfully';
$exitCode = $installResult['exitCode'];
// Verificación de resultado
$exitCode = $installResult['exitCode'];
$status = ($exitCode === 0) ? 'success' : 'failure';
$messageText = $installResult['output']['message'] ?? 'Unknown error';
if (isset($installResult['output']['error'])) {
// Si hay un error, asignar el estado y mensaje adecuado
$status = $installResult['output']['error'];
$messageText = $installResult['output']['message'];
if ($exitCode !== 0) {
$this->logger->error('Installation failed.', [
'transactionId' => $transactionId,
'exitCode' => $exitCode,
'error' => $messageText,
]);
} else {
$this->logger->info('Installation completed successfully.', [
'transactionId' => $transactionId,
]);
}
// 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 {
// Log: instalación completada con éxito
$messageText = $installResult['output']['message'];
$this->logger->info('Installation completed successfully', ['transactionId' => $transactionId]);
// Preparar datos para el webhook
$webhookData = [
'ogCoreId' => $transactionId,
'status' => $status,
'code' => ($exitCode === 0) ? 200 : $exitCode,
'message' => $messageText,
];
$this->logger->info('Webhook data prepared.', ['webhookData' => $webhookData]);
// Enviar al webhook
$webhookUrl = "{$this->ogCoreApiUrl}/og-lives/install/webhook";
$this->logger->info('Sending data to webhook.', ['webhookUrl' => $webhookUrl]);
$this->notifyWebhook($webhookUrl, $webhookData);
} catch (Exception $e) {
// Log de error
$this->logger->error('Installation process failed.', [
'transactionId' => $transactionId,
'exception' => $e->getMessage(),
]);
// Enviar notificación de error al webhook
$webhookData = [
'ogCoreId' => $transactionId,
'status' => 'failure',
'code' => 500,
'message' => $e->getMessage(),
];
$webhookUrl = "{$this->ogCoreApiUrl}/og-lives/install/webhook";
$this->logger->info('Sending error notification to webhook.', ['webhookUrl' => $webhookUrl]);
$this->notifyWebhook($webhookUrl, $webhookData);
}
// Preparar los datos para el webhook según el resultado
$webhookData = [
'ogCoreId' => $transactionId,
'status' => $status,
'code' => ($exitCode === 0) ? 200 : $exitCode, // Cambiar a 200 si es éxito
'message' => $messageText ,
];
// Log finalización
$this->logger->info('Installation process ended.', ['transactionId' => $transactionId]);
$this->logger->info('Installation completed with details', ['installResult' => $installResult]);
$this->logger->info('Webhook data to be sent: ', ['webhookData' => $webhookData]);
#$webhookUrl = "https://172.17.8.90:8443/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, 'webhookData' => $webhookData]);
// Llamar al webhook para notificar el resultado
$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) {
// Log: error en la instalación
$this->logger->error('Failed to complete ogLive installation', ['transactionId' => $transactionId, 'exception' => $e->getMessage()]);
// Manejar errores y enviar notificación de fallo al webhook
$webhookData = [
'ogCoreId' => $transactionId,
'status' => 'failure',
'code' => 500,
'message' => $e->getMessage()
];
$webhookUrl = "https://172.17.8.90:8443/og-lives/install/webhook";
$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]);
return Command::SUCCESS;
}
// Log: proceso de instalación terminado
$this->logger->info('Installation process ended', ['transactionId' => $transactionId]);
return Command::SUCCESS;
}
/**
* Enviar el resultado al webhook
*/
private function notifyWebhook(string $webhookUrl, array $webhookData): void
{
try {
$this->logger->info('Enter notify webhook');
$this->logger->info('Data to be sent', ['webhookData' => $webhookData]);
try {
$this->logger->info('Sending webhook notification.', ['webhookData' => $webhookData]);
$this->httpClient->request('POST', $webhookUrl, [
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
'Content-Type' => 'application/json',
],
'body' => json_encode(['webhookData' => $webhookData]),
]);
// Log: éxito al enviar la notificación
$this->logger->info('Webhook data sent successfully', ['webhookUrl' => $webhookUrl, 'webhookData' => $webhookData]);
$this->logger->info('Webhook notification sent successfully.', ['webhookUrl' => $webhookUrl]);
} catch (Exception $e) {
// Log: error al enviar al webhook
$this->logger->error('Error sending webhook notification', ['webhookUrl' => $webhookUrl, 'exception' => $e->getMessage()]);
$this->logger->error('Error sending webhook notification.', [
'webhookUrl' => $webhookUrl,
'exception' => $e->getMessage(),
]);
}
}
}

File diff suppressed because it is too large Load Diff

View File

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