refs #812 standarize outputs in all endpoints and adds anyof instruction in swagger documentation for 400 error code
testing/og-dhcp-API/pipeline/head There was a failure building this commit Details

nginx_conf
Luis Gerardo Romero Garcia 2024-10-08 12:50:29 +02:00
parent b1d2f2eb22
commit d68208357c
1 changed files with 515 additions and 267 deletions

View File

@ -238,12 +238,36 @@ class DhcpController
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=400,
* description="Error al obtener las subredes", * description="No subnets found",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * type="object",
* @OA\Property(property="error", type="string", example="Error al obtener las subredes") * @OA\Property(property="error", type="string", example="El campo subnet4 no está inicializado")
* ) * )
* ),
* @OA\Response(
* response=500,
* description="Error occurred in kea configuration",
* @OA\JsonContent(
* oneOf={
* @OA\Schema(
* @OA\Property(property="error", type="string", example="No se pudo acceder al archivo de configuración de Kea")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error: La subred con el ID 'subnetId' ya existe.")
* ) * )
* }
* ),
* @OA\Examples(
* example="noResponse",
* summary="No response from kea configuration",
* value={"error": "No se pudo acceder al archivo de configuración de Kea"}
* ),
* @OA\Examples(
* example="keaError",
* summary="Kea agent down",
* value={"error": "Error al obtener la configuración de Kea DHCP"}
* )
* ),
* ) * )
* @Route("/ogdhcp/v1/subnets", methods={"GET"}) * @Route("/ogdhcp/v1/subnets", methods={"GET"})
*/ */
@ -254,7 +278,7 @@ public function getSubnets(): JsonResponse
$response = $this->curlKeaService->executeCurlCommand('config-get'); $response = $this->curlKeaService->executeCurlCommand('config-get');
if (!$response) { if (!$response) {
return new JsonResponse(['error' => 'Error: No se pudo acceder al archivo de configuración de Kea'], 400); return new JsonResponse(['error' => 'No se pudo acceder al archivo de configuración de Kea'], 500);
} }
$result_code = $response[0]["result"]; $result_code = $response[0]["result"];
@ -269,10 +293,10 @@ public function getSubnets(): JsonResponse
], 200); ], 200);
} }
} else { } else {
return new JsonResponse(['error' => "Error en la configuración de Kea: " . $response[0]["text"]], 400); return new JsonResponse(['error' => "Error al obtener la configuración de Kea DHCP: " . $response[0]["text"]], 500);
} }
} catch (Exception $e) { } catch (Exception $e) {
return new JsonResponse(['error' => "Error al obtener la configuración de Kea DHCP: " . $e->getMessage()], 400); return new JsonResponse(['error' => "Error al obtener la configuración de Kea DHCP: " . $e->getMessage()], 500);
} }
} }
@ -294,7 +318,7 @@ public function getSubnets(): JsonResponse
* ), * ),
* @OA\Response( * @OA\Response(
* response=200, * response=200,
* description="Subnet added successfully and returns the created subnet", * description="Subnet added successfully",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * type="object",
* @OA\Property(property="success", type="string", example="Subnet added successfully"), * @OA\Property(property="success", type="string", example="Subnet added successfully"),
@ -311,21 +335,39 @@ public function getSubnets(): JsonResponse
* response=400, * response=400,
* description="Error occurred while adding the subnet", * description="Error occurred while adding the subnet",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * oneOf={
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error: La subred con el nombre 'subnetName' ya existe.") * @OA\Property(property="error", type="string", example="Error: La subred con el nombre 'subnetName' ya existe.")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error: La subred con el ID 'subnetId' ya existe.")
* )
* }
* ),
* @OA\Examples(
* example="nameConflict",
* summary="Subnet name already exists",
* value={"error": "Error: La subred con el nombre 'subnetName' ya existe."}
* ),
* @OA\Examples(
* example="idConflict",
* summary="Subnet ID already exists",
* value={"error": "Error: La subred con el ID 'subnetId' ya existe."}
* ) * )
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=500,
* description="Error occurred while adding the subnet", * description="Server error",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * type="object",
* @OA\Property(property="error", type="string", example="Error: La subred con el ID 'subnetId' ya existe.") * @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP.")
* ) * )
* ) * )
* ) * )
* @Route("/ogdhcp/v1/subnets", methods={"POST"}) * @Route("/ogdhcp/v1/subnets", methods={"POST"})
*/ */
public function addDhcpSubnet(Request $request): JsonResponse public function addDhcpSubnet(Request $request): JsonResponse
{ {
try { try {
@ -440,10 +482,42 @@ public function addDhcpSubnet(Request $request): JsonResponse
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=400,
* description="Error occurred", * description="Error occurred while deleting the subnet",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * oneOf={
* @OA\Property(property="error", type="string", example="Error: No hay subredes definidas") * @OA\Schema(
* @OA\Property(property="error", type="string", example="No hay subredes definidas")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error configuracion de kea invalido")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al escribir en la configuración en Kea DHCP")
* )
* }
* ),
* @OA\Examples(
* example="noSubnets",
* summary="Subnet name already exists",
* value={"error": "No hay subredes definidas"}
* ),
* @OA\Examples(
* example="invalidKea",
* summary="Error in config-test in kea",
* value={"error": "Error configuracion de kea invalido"}
* ),
* @OA\Examples(
* example="saveKea",
* summary="Error in config-set in kea",
* value={"error": "Error al guardar la configuración en Kea DHCP"}
* ),
* @OA\Examples(
* example="writeKea",
* summary="Error in config-write in kea",
* value={"error": "Error al escribir en la configuración en Kea DHCP"}
* ) * )
* ), * ),
* @OA\Response( * @OA\Response(
@ -459,7 +533,7 @@ public function addDhcpSubnet(Request $request): JsonResponse
* description="Error saving configuration in Kea DHCP", * description="Error saving configuration in Kea DHCP",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * type="object",
* @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP: Unable to save configuration") * @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP")
* ) * )
* ) * )
* ) * )
@ -475,7 +549,7 @@ public function addDhcpSubnet(Request $request): JsonResponse
$response = $this->curlKeaService->executeCurlCommand('config-get'); $response = $this->curlKeaService->executeCurlCommand('config-get');
if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) { if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) {
$responseError = "Error: No hay subredes definidas"; $responseError = "No hay subredes definidas";
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 400);
} }
@ -483,8 +557,9 @@ public function addDhcpSubnet(Request $request): JsonResponse
if ($subnetIndex === false) { if ($subnetIndex === false) {
$responseError = "Error: La subred con el id '$subnetId' no existe"; $responseError = "Error: La subred con el id '$subnetId' no existe";
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 404);
} else { } else {
//Borramos la subred con ese id
unset($response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex]); unset($response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex]);
// Eliminar el campo 'hash' si existe // Eliminar el campo 'hash' si existe
if (isset($response[0]['arguments']['hash'])) { if (isset($response[0]['arguments']['hash'])) {
@ -504,7 +579,7 @@ public function addDhcpSubnet(Request $request): JsonResponse
} else { } else {
$responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration);
if ($responseWrite == false || $responseWrite[0]["result"] != 0) { if ($responseWrite == false || $responseWrite[0]["result"] != 0) {
$responseError = "Error al guardar la configuración en Kea DHCP: " . $responseWrite[0]["text"]; $responseError = "Error al escribir en la configuración en Kea DHCP: " . $responseWrite[0]["text"];
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 400);
} else { } else {
$responseSuccess = "Subred eliminada correctamente"; $responseSuccess = "Subred eliminada correctamente";
@ -512,7 +587,7 @@ public function addDhcpSubnet(Request $request): JsonResponse
} }
} }
} else { } else {
$responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; $responseError = "Error configuracion de kea invalido: " . $responseTest[0]["text"];
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 400);
} }
} }
@ -558,10 +633,58 @@ public function addDhcpSubnet(Request $request): JsonResponse
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=400,
* description="Error occurred", * description="Error occurred while deleting the subnet",
* @OA\JsonContent(
* oneOf={
* @OA\Schema(
* @OA\Property(property="error", type="string", example="No hay subredes definidas")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error configuracion de kea invalido")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al escribir en la configuración en Kea DHCP")
* )
* }
* ),
* @OA\Examples(
* example="noSubnets",
* summary="No subnets initialized",
* value={"error": "No hay subredes definidas"}
* ),
* @OA\Examples(
* example="invalidKea",
* summary="Error in config-test in kea",
* value={"error": "Error configuracion de kea invalido"}
* ),
* @OA\Examples(
* example="saveKea",
* summary="Error in config-set in kea",
* value={"error": "Error al guardar la configuración en Kea DHCP"}
* ),
* @OA\Examples(
* example="writeKea",
* summary="Error in config-write in kea",
* value={"error": "Error al escribir en la configuración en Kea DHCP"}
* )
* ),
* @OA\Response(
* response=404,
* description="Subnet not found",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * type="object",
* @OA\Property(property="error", type="string") * @OA\Property(property="error", type="string", example="La subred con el id '2' no existe")
* )
* ),
* @OA\Response(
* response=500,
* description="Error saving configuration in Kea DHCP",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP")
* ) * )
* ) * )
* ) * )
@ -593,7 +716,7 @@ public function addDhcpSubnet(Request $request): JsonResponse
$subnetIndex = array_search($subnetId, array_column($response[0]['arguments']['Dhcp4']['subnet4'], 'id')); $subnetIndex = array_search($subnetId, array_column($response[0]['arguments']['Dhcp4']['subnet4'], 'id'));
if ($subnetIndex === false) { if ($subnetIndex === false) {
$responseError = "Error: La subred con el id '$subnetId' no existe"; $responseError = "La subred con el id '$subnetId' no existe";
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 400);
} else { } else {
$response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex] = [ $response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex] = [
@ -616,7 +739,7 @@ public function addDhcpSubnet(Request $request): JsonResponse
} else { } else {
$responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration);
if ($responseWrite == false || $responseWrite[0]["result"] != 0) { if ($responseWrite == false || $responseWrite[0]["result"] != 0) {
$responseError = "Error al guardar la configuración en Kea DHCP: " . $responseWrite[0]["text"]; $responseError = "Error al escribir en la configuración en Kea DHCP: " . $responseWrite[0]["text"];
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 400);
} else { } else {
$responseSuccess = "Subred modificada correctamente"; $responseSuccess = "Subred modificada correctamente";
@ -624,13 +747,13 @@ public function addDhcpSubnet(Request $request): JsonResponse
} }
} }
} else { } else {
$responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; $responseError = "Error configuracion de kea invalido: " . $responseTest[0]["text"];
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 400);
} }
} }
} catch (Exception $e) { } catch (Exception $e) {
$responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 500);
} }
} }
@ -674,7 +797,7 @@ public function addDhcpSubnet(Request $request): JsonResponse
* description="Server error when loading Kea DHCP configuration", * description="Server error when loading Kea DHCP configuration",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * type="object",
* @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP: unable to access Kea configuration file.") * @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP")
* ) * )
* ) * )
* ) * )
@ -686,7 +809,8 @@ public function getHosts($subnetId): JsonResponse
$response = $this->curlKeaService->executeCurlCommand('config-get'); $response = $this->curlKeaService->executeCurlCommand('config-get');
if (!$response) { if (!$response) {
throw new \Exception('Error al obtener la configuración de Kea DHCP: No se pudo acceder al archivo de configuración.'); $responseError = "Error: No hay subredes definidas";
return new JsonResponse(['error' => $responseError], 400);
} }
$result_code = $response[0]["result"]; $result_code = $response[0]["result"];
@ -698,16 +822,21 @@ public function getHosts($subnetId): JsonResponse
$subnets = $response[0]['arguments']['Dhcp4']['subnet4']; $subnets = $response[0]['arguments']['Dhcp4']['subnet4'];
foreach ($subnets as $subnet) { foreach ($subnets as $subnet) {
if ($subnet['id'] == $subnetId) { if ($subnet['id'] == $subnetId) {
return new JsonResponse($subnet['reservations'], 200); return new JsonResponse([
'success' => 'Hosts obtenidos correctamente correctamente',
'message' => $subnet['reservations']
], 200);
} }
} }
return new JsonResponse(['error' => 'Error: La subred con el id \'' . $subnetId . '\' no existe.'], 400); return new JsonResponse(['error' => 'Error: La subred con el id \'' . $subnetId . '\' no existe.'], 400);
} else { } else {
throw new \Exception('Error en la configuración de Kea: ' . $response[0]['text']); $responseError = "Error: No hay subredes definidas";
return new JsonResponse(['error' => $responseError], 400);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
return new JsonResponse(['error' => $e->getMessage()], 500); $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
return new JsonResponse(['error' => $responseError], 500);
} }
} }
@ -737,34 +866,85 @@ public function getHosts($subnetId): JsonResponse
* ), * ),
* @OA\Response( * @OA\Response(
* response=200, * response=200,
* description="Host added successfully", * description="Host added successfully and returns the new host details",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * type="object",
* @OA\Property(property="success", type="string") * @OA\Property(property="success", type="string", example="Host added successfully"),
* @OA\Property(property="newHost", type="object",
* @OA\Property(property="hostname", type="string", example="pc11"),
* @OA\Property(property="hw-address", type="string", example="56:6f:c7:4f:00:4f"),
* @OA\Property(property="ip-address", type="string", example="172.30.4.11")
* )
* ) * )
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=400,
* description="Error occurred", * description="Error occurred while adding the host",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * oneOf={
* @OA\Property(property="error", type="string") * @OA\Schema(
* @OA\Property(property="error", type="string", example="No hay subredes definidas")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="El host con el hostname 'host' ya existe en las reservaciones.")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error configuracion de kea invalido")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al escribir en la configuración en Kea DHCP")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="No se pudo encontrar el host recién creado")
* )
* }
* ),
* @OA\Examples(
* example="noSubnet",
* summary="No subnets initialized",
* value={"error": "No se encontró la subnet con id '$subnetId'"}
* ),
* @OA\Examples(
* example="hostExists",
* summary="Host already exists",
* value={"error": "El host con el hostname '$host' ya existe en las reservaciones."}
* ),
* @OA\Examples(
* example="invalidKea",
* summary="Error in config-test in kea",
* value={"error": "Error configuracion de kea invalido"}
* ),
* @OA\Examples(
* example="saveKea",
* summary="Error in config-set in kea",
* value={"error": "Error al guardar la configuración en Kea DHCP"}
* ),
* @OA\Examples(
* example="writeKea",
* summary="Error in config-write in kea",
* value={"error": "Error al escribir en la configuración en Kea DHCP"}
* ),
* @OA\Examples(
* example="notFound",
* summary="Host created not found",
* value={"error": "No se pudo encontrar el host recién creado"}
* ) * )
* ) * )
* ) * )
* @Route("/ogdhcp/v1/subnets/{subnetId}/hosts", methods={"POST"}) * @Route("/ogdhcp/v1/subnets/{subnetId}/hosts", methods={"POST"})
*/ */
public function addDhcpHost(Request $request): JsonResponse public function addDhcpHost(Request $request, $subnetId): JsonResponse
{ {
$subnetId = (int) $request->get('subnetId');
try { try {
$input = json_decode($request->getContent()); $input = json_decode($request->getContent());
$host = htmlspecialchars($input->host); $host = htmlspecialchars($input->host);
$macAddress = htmlspecialchars($input->macAddress); $macAddress = htmlspecialchars($input->macAddress);
$address = htmlspecialchars($input->address); $address = htmlspecialchars($input->address);
} catch (Exception $e) { } catch (Exception $e) {
$response["message"] = $e->getMessage(); return new JsonResponse(['error' => $e->getMessage()], 400);
return new JsonResponse(['error' => $response], 400);
} }
try { try {
@ -776,6 +956,7 @@ public function getHosts($subnetId): JsonResponse
]; ];
$subnetFound = false; $subnetFound = false;
foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) { foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) {
if ($subnet['id'] == $subnetId) { if ($subnet['id'] == $subnetId) {
$subnetFound = true; $subnetFound = true;
@ -788,8 +969,7 @@ public function getHosts($subnetId): JsonResponse
}); });
if ($exists) { if ($exists) {
$responseError = "Error: El host con el hostname '$host' ya existe en las reservaciones."; return new JsonResponse(['error' => "Error: El host con el hostname '$host' ya existe en las reservaciones."], 400);
return new JsonResponse(['error' => $responseError], 400);
} else { } else {
$subnet['reservations'][] = $newHost; $subnet['reservations'][] = $newHost;
break; break;
@ -798,8 +978,12 @@ public function getHosts($subnetId): JsonResponse
} }
if (!$subnetFound) { if (!$subnetFound) {
$responseError = "Error: No se encontró la subnet con id '$subnetId'."; return new JsonResponse(['error' => "Error: No se encontró la subnet con id '$subnetId'."], 400);
return new JsonResponse(['error' => $responseError], 400); }
// Eliminar el campo 'hash' si existe
if (isset($response[0]['arguments']['hash'])) {
unset($response[0]['arguments']['hash']);
} }
$array_encoded = json_encode($response[0]['arguments']); $array_encoded = json_encode($response[0]['arguments']);
@ -810,28 +994,43 @@ public function getHosts($subnetId): JsonResponse
if ($responseTest[0]["result"] == 0) { if ($responseTest[0]["result"] == 0) {
$responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration); $responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration);
if ($responseSet == false || $responseSet[0]["result"] != 0) { if ($responseSet == false || $responseSet[0]["result"] != 0) {
$responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; return new JsonResponse(['error' => "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]], 400);
return new JsonResponse(['error' => $responseError], 400);
} else { } else {
$responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration);
if ($responseWrite == false || $responseWrite[0]["result"] != 0) { if ($responseWrite == false || $responseWrite[0]["result"] != 0) {
$responseError = "Error al guardar la configuración en Kea DHCP: " . $responseWrite[0]["text"]; return new JsonResponse(['error' => "Error al escribir en la configuración en Kea DHCP: " . $responseWrite[0]["text"]], 400);
return new JsonResponse(['error' => $responseError], 400);
} else { } else {
$responseSuccess = "Configuración cargada correctamente"; // Ahora volvemos a consultar el host recién creado
return new JsonResponse(['success' => $responseSuccess], 200); $updatedResponse = $this->curlKeaService->executeCurlCommand('config-get');
$createdHost = null;
foreach ($updatedResponse[0]['arguments']['Dhcp4']['subnet4'] as $subnet) {
if ($subnet['id'] == $subnetId) {
foreach ($subnet['reservations'] as $reservation) {
if ($reservation['hw-address'] === $macAddress) {
$createdHost = $reservation;
break;
}
}
}
}
if ($createdHost) {
return new JsonResponse(['success' => "Host agregado correctamente", 'newHost' => $createdHost], 200);
} else {
return new JsonResponse(['error' => "No se pudo encontrar el host recién creado"], 400);
}
} }
} }
} else { } else {
$responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; return new JsonResponse(['error' => "Error kea configuration invalid: " . $responseTest[0]["text"]], 400);
return new JsonResponse(['error' => $responseError], 400);
} }
} catch (Exception $e) { } catch (Exception $e) {
$responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 500);
} }
} }
/** /**
* @OA\Delete( * @OA\Delete(
* path="/ogdhcp/v1/subnets/{subnetId}/hosts", * path="/ogdhcp/v1/subnets/{subnetId}/hosts",
@ -869,10 +1068,50 @@ public function getHosts($subnetId): JsonResponse
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=400,
* description="Error occurred", * description="Error occurred while adding the host",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * oneOf={
* @OA\Property(property="error", type="string") * @OA\Schema(
* @OA\Property(property="error", type="string", example="No se encontró la subnet con id '$subnetId'")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="El host con la MAC '$mac' no existe en las reservaciones")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error configuracion de kea invalido")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al escribir en la configuración en Kea DHCP")
* )
* }
* ),
* @OA\Examples(
* example="noSubnet",
* summary="No subnets initialized",
* value={"error": "No se encontró la subnet con id '$subnetId'"}
* ),
* @OA\Examples(
* example="hostNotFound",
* summary="Host not found",
* value={"error": "El host con la MAC '$mac' no existe en las reservaciones"}
* ),
* @OA\Examples(
* example="invalidKea",
* summary="Error in config-test in kea",
* value={"error": "Error configuracion de kea invalido"}
* ),
* @OA\Examples(
* example="saveKea",
* summary="Error in config-set in kea",
* value={"error": "Error al guardar la configuración en Kea DHCP"}
* ),
* @OA\Examples(
* example="writeKea",
* summary="Error in config-write in kea",
* value={"error": "Error al escribir en la configuración en Kea DHCP"}
* ) * )
* ) * )
* ) * )
@ -911,11 +1150,11 @@ public function deleteDhcpHost(Request $request, $subnetId): JsonResponse
} }
if (!$subnetFound) { if (!$subnetFound) {
return new JsonResponse(['error' => "Error: La subred con el id '$subnetId' no existe."], 404); return new JsonResponse(['error' => "No se encontró la subnet con id '$subnetId'"], 400);
} }
if (!$hostFound) { if (!$hostFound) {
return new JsonResponse(['error' => "Error: El host con la MAC '$macAddress' no existe en las reservaciones."], 404); return new JsonResponse(['error' => "El host con la MAC '$macAddress' no existe en las reservaciones"], 400);
} }
// Eliminar el campo 'hash' si existe // Eliminar el campo 'hash' si existe
@ -935,16 +1174,17 @@ public function deleteDhcpHost(Request $request, $subnetId): JsonResponse
} else { } else {
$responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration);
if ($responseWrite == false || $responseWrite[0]["result"] != 0) { if ($responseWrite == false || $responseWrite[0]["result"] != 0) {
return new JsonResponse(['error' => "Error al guardar la configuración en Kea DHCP: " . $responseWrite[0]["text"]], 400); return new JsonResponse(['error' => "Error al escribir en la configuración en Kea DHCP: " . $responseWrite[0]["text"]], 400);
} else { } else {
return new JsonResponse(['success' => "Host eliminado correctamente"], 200); return new JsonResponse(['success' => "Host eliminado correctamente"], 200);
} }
} }
} else { } else {
return new JsonResponse(['error' => "Error en la configuración de Kea: " . $responseTest[0]["text"]], 400); return new JsonResponse(['error' => "Error configuracion de kea invalido: " . $responseTest[0]["text"]], 400);
} }
} catch (Exception $e) { } catch (Exception $e) {
return new JsonResponse(['error' => $e->getMessage()], 400); $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
return new JsonResponse(['error' => $responseError], 500);
} }
} }
@ -986,18 +1226,25 @@ public function deleteDhcpHost(Request $request, $subnetId): JsonResponse
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=400,
* description="Error occurred", * description="Error occurred while updating the host",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * oneOf={
* @OA\Property(property="error", type="string", example="Invalid input data") * @OA\Schema(
* ) * @OA\Property(property="error", type="string", example="No se encontró la subnet con id '$subnetId'")
* ), * ),
* @OA\Response( * @OA\Schema(
* response=404, * @OA\Property(property="error", type="string", example="El host con la MAC '$oldMacAddress' no existe en las reservaciones")
* description="Host not found", * ),
* @OA\JsonContent( * @OA\Schema(
* type="object", * @OA\Property(property="error", type="string", example="Error configuración de kea inválida")
* @OA\Property(property="error", type="string", example="Error: The host with MAC '56:6f:c7:4f:00:4f' was not found") * ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al escribir la configuración en Kea DHCP")
* )
* }
* ) * )
* ), * ),
* @OA\Response( * @OA\Response(
@ -1020,8 +1267,7 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse
$macAddress = htmlspecialchars($input->macAddress); $macAddress = htmlspecialchars($input->macAddress);
$address = htmlspecialchars($input->address); $address = htmlspecialchars($input->address);
} catch (Exception $e) { } catch (Exception $e) {
$response["message"] = $e->getMessage(); return new JsonResponse(['error' => $e->getMessage()], 400);
return new JsonResponse(['error' => $response], 400);
} }
try { try {
@ -1029,23 +1275,22 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse
$response = $this->curlKeaService->executeCurlCommand('config-get'); $response = $this->curlKeaService->executeCurlCommand('config-get');
$subnetFound = false; $subnetFound = false;
$hostFound = false; $hostFound = false;
$updatedHost = null;
foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) { foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) {
if ($subnet['id'] == $subnetId) { if ($subnet['id'] == $subnetId) {
$this->logger->info('FOUND SUBNET');
$subnetFound = true; $subnetFound = true;
if (!isset($subnet['reservations'])) { if (!isset($subnet['reservations'])) {
$subnet['reservations'] = []; $subnet['reservations'] = [];
} }
foreach ($subnet['reservations'] as &$reservation) { foreach ($subnet['reservations'] as &$reservation) {
$this->logger->info('LOOKING FOR HOST');
if ($reservation['hw-address'] == $oldMacAddress) { if ($reservation['hw-address'] == $oldMacAddress) {
$this->logger->info('FOUND HOST');
$hostFound = true; $hostFound = true;
$reservation['hw-address'] = $macAddress; $reservation['hw-address'] = $macAddress;
$reservation['ip-address'] = $address; $reservation['ip-address'] = $address;
$reservation['hostname'] = $host; $reservation['hostname'] = $host;
$updatedHost = $reservation;
break; break;
} }
} }
@ -1053,8 +1298,6 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse
} }
if ($subnetFound && $hostFound) { if ($subnetFound && $hostFound) {
$this->logger->info('UPDATING HOST');
// Eliminar el campo 'hash' si existe // Eliminar el campo 'hash' si existe
if (isset($response[0]['arguments']['hash'])) { if (isset($response[0]['arguments']['hash'])) {
unset($response[0]['arguments']['hash']); unset($response[0]['arguments']['hash']);
@ -1071,35 +1314,31 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse
// Guardar la configuración // Guardar la configuración
$responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration); $responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration);
if ($responseSet == false || $responseSet[0]["result"] != 0) { if ($responseSet == false || $responseSet[0]["result"] != 0) {
$responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; return new JsonResponse(['error' => "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]], 400);
return new JsonResponse(['error' => $responseError], 400);
} else { } else {
// Escribir la configuración en disco // Escribir la configuración en disco
$responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration);
if ($responseWrite == false || $responseWrite[0]["result"] != 0) { if ($responseWrite == false || $responseWrite[0]["result"] != 0) {
$responseError = "Error al guardar la configuración en Kea DHCP: " . $responseWrite[0]["text"]; return new JsonResponse(['error' => "Error al escribir la configuración en Kea DHCP: " . $responseWrite[0]["text"]], 400);
return new JsonResponse(['error' => $responseError], 400);
} else { } else {
return new JsonResponse(['success' => "Host actualizado correctamente"], 200); // Devolver el host actualizado
return new JsonResponse(['success' => "Host actualizado correctamente", 'message' => $updatedHost], 200);
} }
} }
} else { } else {
$responseError = "Error en la configuración de Kea: " . $responseTest[0]["text"]; return new JsonResponse(['error' => "Error en la configuración de Kea: " . $responseTest[0]["text"]], 400);
return new JsonResponse(['error' => $responseError], 400);
} }
} elseif (!$subnetFound) { } elseif (!$subnetFound) {
$responseError = "Error: La subred con el id '$subnetId' no existe."; return new JsonResponse(['error' => "Error: La subred con el id '$subnetId' no existe."], 400);
return new JsonResponse(['error' => $responseError], 404);
} elseif (!$hostFound) { } elseif (!$hostFound) {
$responseError = "Error: El host con la MAC " . $oldMacAddress . " no existe en las reservaciones."; return new JsonResponse(['error' => "Error: El host con la MAC '$oldMacAddress' no existe en las reservaciones."], 400);
return new JsonResponse(['error' => $responseError], 404);
} }
} catch (Exception $e) { } catch (Exception $e) {
$responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); return new JsonResponse(['error' => "Error al obtener la configuración de Kea DHCP: " . $e->getMessage()], 500);
return new JsonResponse(['error' => $responseError], 400);
} }
} }
/** /**
* @OA\Get( * @OA\Get(
* path="/ogdhcp/v1/subnets/backup", * path="/ogdhcp/v1/subnets/backup",
@ -1164,15 +1403,14 @@ public function getLatestBackupConfiguration(): JsonResponse
// Leer el archivo más reciente // Leer el archivo más reciente
$backup_file = reset($backup_files); $backup_file = reset($backup_files);
$config = file_get_contents($backup_file); $config = file_get_contents($backup_file);
$configuration = json_decode($config, true); // Decodificar como arreglo $configuration = json_decode($config, true);
if (!isset($configuration['Dhcp4']['subnet4'])) { if (!isset($configuration['Dhcp4']['subnet4'])) {
$responseError = "No se encontró el parámetro 'subnet4' en el backup"; $responseError = "No se encontró el parámetro 'subnet4' en el backup";
return new JsonResponse(['error' => $responseError], 400); return new JsonResponse(['error' => $responseError], 400);
} }
// Devolver solo el parámetro 'subnet4' $responseSuccess = "Backup obtenido con exito";
$responseSuccess = "Backup configuration retrieved successfully";
return new JsonResponse(['success' => $responseSuccess, 'message' => ['subnet4' => $configuration['Dhcp4']['subnet4']]], 200); return new JsonResponse(['success' => $responseSuccess, 'message' => ['subnet4' => $configuration['Dhcp4']['subnet4']]], 200);
} catch (Exception $e) { } catch (Exception $e) {
$responseError = "Error al obtener la configuración de backup: " . $e->getMessage(); $responseError = "Error al obtener la configuración de backup: " . $e->getMessage();
@ -1195,42 +1433,52 @@ public function getLatestBackupConfiguration(): JsonResponse
* ), * ),
* @OA\Response( * @OA\Response(
* response=400, * response=400,
* description="Error occurred during the restore process", * description="Error occurred while adding the host",
* @OA\JsonContent( * @OA\JsonContent(
* type="object", * oneOf={
* @OA\Schema(
* @OA\Property(property="error", type="string", example="No se encontraron archivos de backup") * @OA\Property(property="error", type="string", example="No se encontraron archivos de backup")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="El host con la MAC '$mac' no existe en las reservaciones")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error configuracion de kea invalido")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")
* ),
* @OA\Schema(
* @OA\Property(property="error", type="string", example="Error al escribir en la configuración en Kea DHCP")
* ) * )
* }
* ), * ),
* @OA\Response( * @OA\Examples(
* response=400, * example="noBackup",
* description="Error occurred during Kea configuration validation", * summary="No backup files found",
* @OA\JsonContent( * value={"error": "No se encontraron archivos de backup"}
* type="object", * ),
* @OA\Property(property="error", type="string", example="Error al comprobar la configuración de Kea: unable to forward command to the dhcp4 service") * @OA\Examples(
* example="hostNotFound",
* summary="Host not found",
* value={"error": "El host con la MAC '$mac' no existe en las reservaciones"}
* ),
* @OA\Examples(
* example="invalidKea",
* summary="Error in config-test in kea",
* value={"error": "Error configuracion de kea invalido"}
* ),
* @OA\Examples(
* example="saveKea",
* summary="Error in config-set in kea",
* value={"error": "Error al guardar la configuración en Kea DHCP"}
* ),
* @OA\Examples(
* example="writeKea",
* summary="Error in config-write in kea",
* value={"error": "Error al escribir en la configuración en Kea DHCP"}
* ) * )
* ), * ),
* @OA\Response(
* response=400,
* description="Error en el proceso de restauración",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="error", type="string"),
* ),
* examples={
* "errorBackupNotFound": {
* "summary": "No se encontraron archivos de backup",
* "value": {
* "error": "No se encontraron archivos de backup"
* }
* },
* "errorConfigTest": {
* "summary": "Error en la configuración de Kea",
* "value": {
* "error": "Error al comprobar la configuración de Kea: Error específico"
* }
* }
* }
* ),
* ) * )
* @Route("/ogdhcp/v1/backup/restore", methods={"POST"}) * @Route("/ogdhcp/v1/backup/restore", methods={"POST"})
*/ */