From d68208357c168c31fad5de31b06b2a8b8ca55f38 Mon Sep 17 00:00:00 2001 From: lgromero Date: Tue, 8 Oct 2024 12:50:29 +0200 Subject: [PATCH] refs #812 standarize outputs in all endpoints and adds anyof instruction in swagger documentation for 400 error code --- src/DhcpBundle/Controller/DhcpController.php | 782 ++++++++++++------- 1 file changed, 515 insertions(+), 267 deletions(-) diff --git a/src/DhcpBundle/Controller/DhcpController.php b/src/DhcpBundle/Controller/DhcpController.php index b46f948..4bb588c 100644 --- a/src/DhcpBundle/Controller/DhcpController.php +++ b/src/DhcpBundle/Controller/DhcpController.php @@ -238,12 +238,36 @@ class DhcpController * ), * @OA\Response( * response=400, - * description="Error al obtener las subredes", + * description="No subnets found", * @OA\JsonContent( * 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"}) */ @@ -254,7 +278,7 @@ public function getSubnets(): JsonResponse $response = $this->curlKeaService->executeCurlCommand('config-get'); 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"]; @@ -269,10 +293,10 @@ public function getSubnets(): JsonResponse ], 200); } } 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) { - 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( * response=200, - * description="Subnet added successfully and returns the created subnet", + * description="Subnet added successfully", * @OA\JsonContent( * type="object", * @OA\Property(property="success", type="string", example="Subnet added successfully"), @@ -311,21 +335,39 @@ public function getSubnets(): JsonResponse * response=400, * description="Error occurred while adding the subnet", * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="Error: La subred con el nombre 'subnetName' ya existe.") + * oneOf={ + * @OA\Schema( + * @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( - * response=400, - * description="Error occurred while adding the subnet", + * response=500, + * description="Server error", * @OA\JsonContent( * 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"}) */ + + public function addDhcpSubnet(Request $request): JsonResponse { try { @@ -419,52 +461,84 @@ public function addDhcpSubnet(Request $request): JsonResponse } } - /** - * @OA\Delete( - * path="/ogdhcp/v1/subnets/{subnetId}", - * summary="Delete a DHCP subnet", - * @OA\Parameter( - * name="subnetId", - * in="path", - * description="ID of the subnet to delete", - * required=true, - * @OA\Schema(type="integer") - * ), - * @OA\Response( - * response=200, - * description="Subnet deleted successfully", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="success", type="string", example="Subred eliminada correctamente") - * ) - * ), - * @OA\Response( - * response=400, - * description="Error occurred", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="Error: No hay subredes definidas") - * ) - * ), - * @OA\Response( - * response=404, - * description="Subnet not found", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="Error: 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 guardar la configuración en Kea DHCP: Unable to save configuration") - * ) - * ) - * ) - * @Route("/ogdhcp/v1/subnets/{subnetId}", methods={"DELETE"}) - */ + /** + * @OA\Delete( + * path="/ogdhcp/v1/subnets/{subnetId}", + * summary="Delete a DHCP subnet", + * @OA\Parameter( + * name="subnetId", + * in="path", + * description="ID of the subnet to delete", + * required=true, + * @OA\Schema(type="integer") + * ), + * @OA\Response( + * response=200, + * description="Subnet deleted successfully", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="success", type="string", example="Subred eliminada correctamente") + * ) + * ), + * @OA\Response( + * response=400, + * 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="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( + * response=404, + * description="Subnet not found", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="error", type="string", example="Error: 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") + * ) + * ) + * ) + * @Route("/ogdhcp/v1/subnets/{subnetId}", methods={"DELETE"}) + */ public function deleteDhcpSubnet(Request $request): JsonResponse @@ -475,7 +549,7 @@ public function addDhcpSubnet(Request $request): JsonResponse $response = $this->curlKeaService->executeCurlCommand('config-get'); if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) { - $responseError = "Error: No hay subredes definidas"; + $responseError = "No hay subredes definidas"; return new JsonResponse(['error' => $responseError], 400); } @@ -483,8 +557,9 @@ public function addDhcpSubnet(Request $request): JsonResponse if ($subnetIndex === false) { $responseError = "Error: La subred con el id '$subnetId' no existe"; - return new JsonResponse(['error' => $responseError], 400); + return new JsonResponse(['error' => $responseError], 404); } else { + //Borramos la subred con ese id unset($response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex]); // Eliminar el campo 'hash' si existe if (isset($response[0]['arguments']['hash'])) { @@ -504,7 +579,7 @@ public function addDhcpSubnet(Request $request): JsonResponse } else { $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); 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); } else { $responseSuccess = "Subred eliminada correctamente"; @@ -512,7 +587,7 @@ public function addDhcpSubnet(Request $request): JsonResponse } } } else { - $responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; + $responseError = "Error configuracion de kea invalido: " . $responseTest[0]["text"]; return new JsonResponse(['error' => $responseError], 400); } } @@ -558,10 +633,58 @@ public function addDhcpSubnet(Request $request): JsonResponse * ), * @OA\Response( * 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( * 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')); 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); } else { $response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex] = [ @@ -616,7 +739,7 @@ public function addDhcpSubnet(Request $request): JsonResponse } else { $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); 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); } else { $responseSuccess = "Subred modificada correctamente"; @@ -624,13 +747,13 @@ public function addDhcpSubnet(Request $request): JsonResponse } } } else { - $responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; + $responseError = "Error configuracion de kea invalido: " . $responseTest[0]["text"]; return new JsonResponse(['error' => $responseError], 400); } } } catch (Exception $e) { $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", * @OA\JsonContent( * 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'); 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"]; @@ -698,140 +822,215 @@ public function getHosts($subnetId): JsonResponse $subnets = $response[0]['arguments']['Dhcp4']['subnet4']; foreach ($subnets as $subnet) { 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); } 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) { - 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); } } - /** - * @OA\Post( - * path="/ogdhcp/v1/subnets/{subnetId}/hosts", - * summary="Add a DHCP host to a subnet", - * @OA\Parameter( - * name="subnetId", - * in="path", - * description="ID of the subnet to add the host to", - * required=true, - * @OA\Schema( - * type="integer" - * ) - * ), - * @OA\RequestBody( - * description="Data for the new host", - * required=true, - * @OA\JsonContent( - * type="object", - * @OA\Property(property="host", type="string", example="pc11"), - * @OA\Property(property="macAddress", type="string", example="56:6f:c7:4f:00:4f"), - * @OA\Property(property="address", type="string", example="172.30.4.11") - * ) - * ), - * @OA\Response( - * response=200, - * description="Host added successfully", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="success", type="string") - * ) - * ), - * @OA\Response( - * response=400, - * description="Error occurred", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string") - * ) - * ) - * ) - * @Route("/ogdhcp/v1/subnets/{subnetId}/hosts", methods={"POST"}) - */ - public function addDhcpHost(Request $request): JsonResponse - { - $subnetId = (int) $request->get('subnetId'); - try { - $input = json_decode($request->getContent()); - $host = htmlspecialchars($input->host); - $macAddress = htmlspecialchars($input->macAddress); - $address = htmlspecialchars($input->address); - } catch (Exception $e) { - $response["message"] = $e->getMessage(); - return new JsonResponse(['error' => $response], 400); - } - - try { - $response = $this->curlKeaService->executeCurlCommand('config-get'); - $newHost = [ - "hostname" => $host, - "hw-address" => $macAddress, - "ip-address" => $address - ]; - - $subnetFound = false; - foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) { - if ($subnet['id'] == $subnetId) { - $subnetFound = true; - if (!isset($subnet['reservations'])) { - $subnet['reservations'] = []; - } - - $exists = array_reduce($subnet['reservations'], function ($exists, $reservation) use ($host) { - return $exists || ($reservation['hostname'] === $host); - }); - - if ($exists) { - $responseError = "Error: El host con el hostname '$host' ya existe en las reservaciones."; - return new JsonResponse(['error' => $responseError], 400); - } else { - $subnet['reservations'][] = $newHost; - break; - } - } - } - - if (!$subnetFound) { - $responseError = "Error: No se encontró la subnet con id '$subnetId'."; - return new JsonResponse(['error' => $responseError], 400); - } - - $array_encoded = json_encode($response[0]['arguments']); - $configurationParsed = str_replace('\\', '', $array_encoded); - $configuration = json_decode($configurationParsed); - $responseTest = $this->curlKeaService->executeCurlCommand('config-test', $configuration); - - if ($responseTest[0]["result"] == 0) { - $responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration); - if ($responseSet == false || $responseSet[0]["result"] != 0) { - $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); - } else { - $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); - if ($responseWrite == false || $responseWrite[0]["result"] != 0) { - $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseWrite[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); - } else { - $responseSuccess = "Configuración cargada correctamente"; - return new JsonResponse(['success' => $responseSuccess], 200); - } - } - } else { - $responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); - } - } catch (Exception $e) { - $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); - return new JsonResponse(['error' => $responseError], 400); - } +/** + * @OA\Post( + * path="/ogdhcp/v1/subnets/{subnetId}/hosts", + * summary="Add a DHCP host to a subnet", + * @OA\Parameter( + * name="subnetId", + * in="path", + * description="ID of the subnet to add the host to", + * required=true, + * @OA\Schema( + * type="integer" + * ) + * ), + * @OA\RequestBody( + * description="Data for the new host", + * required=true, + * @OA\JsonContent( + * type="object", + * @OA\Property(property="host", type="string", example="pc11"), + * @OA\Property(property="macAddress", type="string", example="56:6f:c7:4f:00:4f"), + * @OA\Property(property="address", type="string", example="172.30.4.11") + * ) + * ), + * @OA\Response( + * response=200, + * description="Host added successfully and returns the new host details", + * @OA\JsonContent( + * type="object", + * @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( + * response=400, + * description="Error occurred while adding the host", + * @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="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"}) + */ +public function addDhcpHost(Request $request, $subnetId): JsonResponse +{ + try { + $input = json_decode($request->getContent()); + $host = htmlspecialchars($input->host); + $macAddress = htmlspecialchars($input->macAddress); + $address = htmlspecialchars($input->address); + } catch (Exception $e) { + return new JsonResponse(['error' => $e->getMessage()], 400); } + try { + $response = $this->curlKeaService->executeCurlCommand('config-get'); + $newHost = [ + "hostname" => $host, + "hw-address" => $macAddress, + "ip-address" => $address + ]; + + $subnetFound = false; + + foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) { + if ($subnet['id'] == $subnetId) { + $subnetFound = true; + if (!isset($subnet['reservations'])) { + $subnet['reservations'] = []; + } + + $exists = array_reduce($subnet['reservations'], function ($exists, $reservation) use ($host) { + return $exists || ($reservation['hostname'] === $host); + }); + + if ($exists) { + return new JsonResponse(['error' => "Error: El host con el hostname '$host' ya existe en las reservaciones."], 400); + } else { + $subnet['reservations'][] = $newHost; + break; + } + } + } + + if (!$subnetFound) { + return new JsonResponse(['error' => "Error: No se encontró la subnet con id '$subnetId'."], 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']); + $configurationParsed = str_replace('\\', '', $array_encoded); + $configuration = json_decode($configurationParsed); + $responseTest = $this->curlKeaService->executeCurlCommand('config-test', $configuration); + + if ($responseTest[0]["result"] == 0) { + $responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration); + if ($responseSet == false || $responseSet[0]["result"] != 0) { + return new JsonResponse(['error' => "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]], 400); + } else { + $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); + if ($responseWrite == false || $responseWrite[0]["result"] != 0) { + return new JsonResponse(['error' => "Error al escribir en la configuración en Kea DHCP: " . $responseWrite[0]["text"]], 400); + } else { + // Ahora volvemos a consultar el host recién creado + $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 { + return new JsonResponse(['error' => "Error kea configuration invalid: " . $responseTest[0]["text"]], 400); + } + } catch (Exception $e) { + $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); + return new JsonResponse(['error' => $responseError], 500); + } +} + + /** * @OA\Delete( * path="/ogdhcp/v1/subnets/{subnetId}/hosts", @@ -869,10 +1068,50 @@ public function getHosts($subnetId): JsonResponse * ), * @OA\Response( * response=400, - * description="Error occurred", + * description="Error occurred while adding the host", * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string") + * oneOf={ + * @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) { - 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) { - 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 @@ -935,16 +1174,17 @@ public function deleteDhcpHost(Request $request, $subnetId): JsonResponse } else { $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); 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 { return new JsonResponse(['success' => "Host eliminado correctamente"], 200); } } } 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) { - 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( * response=400, - * description="Error occurred", + * description="Error occurred while updating the host", * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="Invalid input data") - * ) - * ), - * @OA\Response( - * response=404, - * description="Host not found", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="Error: The host with MAC '56:6f:c7:4f:00:4f' was not found") + * oneOf={ + * @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 '$oldMacAddress' no existe en las reservaciones") + * ), + * @OA\Schema( + * @OA\Property(property="error", type="string", example="Error configuración de kea inválida") + * ), + * @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( @@ -1020,8 +1267,7 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse $macAddress = htmlspecialchars($input->macAddress); $address = htmlspecialchars($input->address); } catch (Exception $e) { - $response["message"] = $e->getMessage(); - return new JsonResponse(['error' => $response], 400); + return new JsonResponse(['error' => $e->getMessage()], 400); } try { @@ -1029,23 +1275,22 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse $response = $this->curlKeaService->executeCurlCommand('config-get'); $subnetFound = false; $hostFound = false; + $updatedHost = null; foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) { if ($subnet['id'] == $subnetId) { - $this->logger->info('FOUND SUBNET'); $subnetFound = true; if (!isset($subnet['reservations'])) { $subnet['reservations'] = []; } foreach ($subnet['reservations'] as &$reservation) { - $this->logger->info('LOOKING FOR HOST'); if ($reservation['hw-address'] == $oldMacAddress) { - $this->logger->info('FOUND HOST'); $hostFound = true; $reservation['hw-address'] = $macAddress; $reservation['ip-address'] = $address; $reservation['hostname'] = $host; + $updatedHost = $reservation; break; } } @@ -1053,8 +1298,6 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse } if ($subnetFound && $hostFound) { - $this->logger->info('UPDATING HOST'); - // Eliminar el campo 'hash' si existe if (isset($response[0]['arguments']['hash'])) { unset($response[0]['arguments']['hash']); @@ -1071,35 +1314,31 @@ public function updateDhcpHost(Request $request, $subnetId): JsonResponse // Guardar la configuración $responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration); if ($responseSet == false || $responseSet[0]["result"] != 0) { - $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); + return new JsonResponse(['error' => "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]], 400); } else { // Escribir la configuración en disco $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); if ($responseWrite == false || $responseWrite[0]["result"] != 0) { - $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseWrite[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); + return new JsonResponse(['error' => "Error al escribir la configuración en Kea DHCP: " . $responseWrite[0]["text"]], 400); } else { - return new JsonResponse(['success' => "Host actualizado correctamente"], 200); + // Devolver el host actualizado + return new JsonResponse(['success' => "Host actualizado correctamente", 'message' => $updatedHost], 200); } } } else { - $responseError = "Error en la configuración de Kea: " . $responseTest[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); + return new JsonResponse(['error' => "Error en la configuración de Kea: " . $responseTest[0]["text"]], 400); } } elseif (!$subnetFound) { - $responseError = "Error: La subred con el id '$subnetId' no existe."; - return new JsonResponse(['error' => $responseError], 404); + return new JsonResponse(['error' => "Error: La subred con el id '$subnetId' no existe."], 400); } elseif (!$hostFound) { - $responseError = "Error: El host con la MAC " . $oldMacAddress . " no existe en las reservaciones."; - return new JsonResponse(['error' => $responseError], 404); + return new JsonResponse(['error' => "Error: El host con la MAC '$oldMacAddress' no existe en las reservaciones."], 400); } } catch (Exception $e) { - $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); - return new JsonResponse(['error' => $responseError], 400); + return new JsonResponse(['error' => "Error al obtener la configuración de Kea DHCP: " . $e->getMessage()], 500); } } + /** * @OA\Get( * path="/ogdhcp/v1/subnets/backup", @@ -1164,15 +1403,14 @@ public function getLatestBackupConfiguration(): JsonResponse // Leer el archivo más reciente $backup_file = reset($backup_files); $config = file_get_contents($backup_file); - $configuration = json_decode($config, true); // Decodificar como arreglo + $configuration = json_decode($config, true); if (!isset($configuration['Dhcp4']['subnet4'])) { $responseError = "No se encontró el parámetro 'subnet4' en el backup"; return new JsonResponse(['error' => $responseError], 400); } - // Devolver solo el parámetro 'subnet4' - $responseSuccess = "Backup configuration retrieved successfully"; + $responseSuccess = "Backup obtenido con exito"; return new JsonResponse(['success' => $responseSuccess, 'message' => ['subnet4' => $configuration['Dhcp4']['subnet4']]], 200); } catch (Exception $e) { $responseError = "Error al obtener la configuración de backup: " . $e->getMessage(); @@ -1193,43 +1431,53 @@ public function getLatestBackupConfiguration(): JsonResponse * @OA\Property(property="success", type="string", example="Configuración cargada correctamente") * ) * ), - * @OA\Response( +* @OA\Response( * response=400, - * description="Error occurred during the restore process", + * description="Error occurred while adding the host", * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="No se encontraron archivos de backup") - * ) - * ), - * @OA\Response( - * response=400, - * description="Error occurred during Kea configuration validation", - * @OA\JsonContent( - * 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\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" - * } + * oneOf={ + * @OA\Schema( + * @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\Examples( + * example="noBackup", + * summary="No backup files found", + * value={"error": "No se encontraron archivos de backup"} + * ), + * @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"} + * ) * ), * ) * @Route("/ogdhcp/v1/backup/restore", methods={"POST"})