refs #668 adds status endpoint to dhcp controller
testing/og-dhcp-API/pipeline/head There was a failure building this commit Details

nginx_conf
Luis Gerardo Romero Garcia 2024-10-02 13:59:32 +02:00
parent 2d391cdd34
commit aaa06152d1
1 changed files with 91 additions and 61 deletions

View File

@ -71,22 +71,28 @@ class DhcpController
*/
public function getDhcpStatus(): Response
{
try {
// Obtener el uso de disco
$diskUsageResult = $this->getDiskUsage();
if (!$diskUsageResult) {
return new JsonResponse(['error' => 'Failed to retrieve disk usage'], Response::HTTP_INTERNAL_SERVER_ERROR);
throw new \Exception('Failed to retrieve disk usage');
}
// Obtener el estado de los servicios de ogDHCP (similar a check_services_status en ogboot)
// Obtener el estado de los servicios de ogDHCP
$servicesStatusResult = $this->getServicesStatus();
if (!$servicesStatusResult) {
return new JsonResponse(['error' => 'Failed to retrieve services status'], Response::HTTP_INTERNAL_SERVER_ERROR);
throw new \Exception('Failed to retrieve services status');
}
// Obtener las subredes y las reservas asociadas
// Intentar obtener las subredes, pero si falla devolver un array vacío
$subnetsResult = [];
try {
$subnetsResult = $this->getSubnetsService();
if (!$subnetsResult) {
return new JsonResponse(['error' => 'Failed to retrieve subnets'], Response::HTTP_INTERNAL_SERVER_ERROR);
} catch (\Exception $e) {
// Si ocurre un error, simplemente dejar $subnetsResult vacío
$subnetsResult = [];
}
// Componer la respuesta
$response = [
'disk_usage' => $diskUsageResult,
@ -94,7 +100,12 @@ class DhcpController
'services_status' => $servicesStatusResult
];
return new JsonResponse($response, Response::HTTP_OK);
return new JsonResponse(['success' => "Información obtenida con éxito", 'message' => $response], Response::HTTP_OK);
} catch (\Exception $e) {
// Capturar la excepción y devolver el mensaje de error
return new JsonResponse(['error' => $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
private function getDiskUsage(): array
@ -119,40 +130,59 @@ class DhcpController
private function getServicesStatus(): array
{
$services = [
'tftpboot' => 'active',
'nginx' => 'active',
'kea-dhcp4-server' => $this->getServiceStatus('kea-dhcp4-server.service'),
'kea-ctrl-agent' => $this->getServiceStatus('kea-ctrl-agent.service'),
'nginx' => $this->getServiceStatus('nginx.service')
];
return $services;
}
private function getServiceStatus(string $service): string
{
// Ejecutar el comando systemctl para verificar el estado del servicio
$output = shell_exec("systemctl is-active " . escapeshellarg($service));
// Si el comando retorna "active", el servicio está corriendo
if (trim($output) === 'active') {
return 'active';
} else {
return 'inactive';
}
}
private function getSubnetsService(): ?array
{
try {
// Ejecutar el comando para obtener la configuración
$response = $this->curlKeaService->executeCurlCommand('config-get');
// Verificar si la respuesta es nula
if (!$response) {
$this->logger->error('Error: No se pudo acceder al archivo de configuración Kea.');
return null;
throw new \Exception('Error: No se pudo acceder a la configuración de Kea. Respuesta nula.');
}
// Verificar el código de resultado
$result_code = $response[0]["result"];
if ($result_code == 0) {
if ($result_code != 0) {
throw new \Exception("Error en la configuración de Kea: " . $response[0]["text"]);
}
// Verificar si el campo 'subnet4' está presente en la respuesta
if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) {
$this->logger->error("El campo 'subnet4' no está inicializado");
return null;
} else {
return $response[0]['arguments']['Dhcp4']['subnet4']; // Subredes y sus reservas
}
} else {
$this->logger->error("Error en la configuración Kea: " . $response[0]["text"]);
return null;
throw new \Exception("El campo 'subnet4' no está inicializado. Respuesta: " . json_encode($response[0]['arguments']));
}
// Subredes encontradas, devolver resultado
return $response[0]['arguments']['Dhcp4']['subnet4'];
} catch (\Exception $e) {
$this->logger->error("Error al obtener la configuración de Kea DHCP: " . $e->getMessage());
return null;
// Escalar la excepción para que sea gestionada por la función que llama
throw new \Exception("Error al obtener las subredes: " . $e->getMessage());
}
}
/**
* @OA\Schema(
* schema="Subnet",