From ad7cd037bf88751565ca324b34c2dfcfd5c412b7 Mon Sep 17 00:00:00 2001 From: lgromero Date: Thu, 3 Oct 2024 12:31:36 +0200 Subject: [PATCH] refs #797 in delete and modify identifiques the host with subnet id and mac, changes swagger and functionality with this logic. Fix duplicated 400 output in swagger addsubnet doc --- src/DhcpBundle/Controller/DhcpController.php | 361 ++++++++++--------- 1 file changed, 187 insertions(+), 174 deletions(-) diff --git a/src/DhcpBundle/Controller/DhcpController.php b/src/DhcpBundle/Controller/DhcpController.php index aa325e6..bfa3016 100644 --- a/src/DhcpBundle/Controller/DhcpController.php +++ b/src/DhcpBundle/Controller/DhcpController.php @@ -308,14 +308,6 @@ public function getSubnets(): JsonResponse * type="object", * @OA\Property(property="error", type="string", example="Error: La subred con el nombre 'subnetName' ya existe.") * ) - * ), - * @OA\Response( - * 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 ID 'subnetId' ya existe.") - * ) * ) * ) * @Route("/ogdhcp/v1/subnets", methods={"POST"}) @@ -859,110 +851,122 @@ public function getSubnets(): JsonResponse } } - /** - * @OA\Delete( - * path="/ogdhcp/v1/subnets/{subnetId}/hosts", - * summary="Delete a DHCP host from a specific subnet", - * @OA\Parameter( - * name="subnetId", - * in="path", - * description="The ID of the subnet", - * required=true, - * @OA\Schema(type="integer") - * ), - * @OA\RequestBody( - * description="Data for the host to delete", - * required=true, - * @OA\JsonContent( - * type="object", - * @OA\Property(property="host", type="string", example="pc11") - * ) - * ), - * @OA\Response( - * response=200, - * description="Host deleted 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={"DELETE"}) - */ - public function deleteDhcpHost(Request $request, $subnetId): JsonResponse - { - try { - $input = json_decode($request->getContent()); - $host = htmlspecialchars($input->host); - } catch (Exception $e) { - $response["message"] = $e->getMessage(); - return new JsonResponse(['error' => $response], 400); - } - - try { - $response = $this->curlKeaService->executeCurlCommand('config-get'); - $subnetFound = false; - - foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) { - if ($subnet['id'] == $subnetId) { - $subnetFound = true; - if (!isset($subnet['reservations'])) { - $subnet['reservations'] = []; - } - - foreach ($subnet['reservations'] as $key => $reservation) { - if (isset($reservation['hostname']) && $reservation['hostname'] === $host) { - unset($subnet['reservations'][$key]); - $subnet['reservations'] = array_values($subnet['reservations']); - break; - } - } - } - } - - if ($subnetFound) { - $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 al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); - } - } else { - $responseError = "Error: El host con el hostname '$host' no existe en las reservaciones."; - 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\Delete( + * path="/ogdhcp/v1/subnets/{subnetId}/hosts", + * summary="Delete a DHCP host from a specific subnet", + * @OA\Parameter( + * name="subnetId", + * in="path", + * description="The ID of the subnet", + * required=true, + * @OA\Schema(type="integer") + * ), + * @OA\RequestBody( + * description="Data for the host to delete", + * required=true, + * @OA\JsonContent( + * type="object", + * @OA\Property(property="macAddress", type="string", example="56:6f:c7:4f:00:4f") + * ) + * ), + * @OA\Response( + * response=200, + * description="Host deleted successfully", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="success", type="string") + * ) + * ), + * @OA\Response( + * response=404, + * description="Host or subnet not found", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="error", 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={"DELETE"}) + */ +public function deleteDhcpHost(Request $request, $subnetId): JsonResponse +{ + try { + $input = json_decode($request->getContent()); + $macAddress = htmlspecialchars($input->macAddress); + } catch (Exception $e) { + return new JsonResponse(['error' => $e->getMessage()], 400); } + try { + $response = $this->curlKeaService->executeCurlCommand('config-get'); + $subnetFound = false; + $hostFound = false; + + foreach ($response[0]['arguments']['Dhcp4']['subnet4'] as &$subnet) { + if ($subnet['id'] == $subnetId) { + $subnetFound = true; + if (!isset($subnet['reservations'])) { + $subnet['reservations'] = []; + } + + foreach ($subnet['reservations'] as $key => $reservation) { + if ($reservation['hw-address'] === $macAddress) { + unset($subnet['reservations'][$key]); + $subnet['reservations'] = array_values($subnet['reservations']); + $hostFound = true; + break; + } + } + } + } + + if (!$subnetFound) { + return new JsonResponse(['error' => "Error: La subred con el id '$subnetId' no existe."], 404); + } + + if (!$hostFound) { + return new JsonResponse(['error' => "Error: El host con la MAC '$macAddress' no existe en las reservaciones."], 404); + } + + // 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 guardar 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); + } + } catch (Exception $e) { + return new JsonResponse(['error' => $e->getMessage()], 400); + } +} + /** * @OA\Put( @@ -1026,86 +1030,95 @@ public function getSubnets(): JsonResponse * ) * @Route("/ogdhcp/v1/subnets/{subnetId}/hosts", methods={"PUT"}) */ - public function updateDhcpHost(Request $request, $subnetId): JsonResponse - { +public function updateDhcpHost(Request $request, $subnetId): JsonResponse +{ + try { + $input = json_decode($request->getContent()); + $host = htmlspecialchars($input->host); + $oldMacAddress = htmlspecialchars($input->oldMacAddress); + $macAddress = htmlspecialchars($input->macAddress); + $address = htmlspecialchars($input->address); + } catch (Exception $e) { + $response["message"] = $e->getMessage(); + return new JsonResponse(['error' => $response], 400); + } - try { - $input = json_decode($request->getContent()); - $host = htmlspecialchars($input->host); - $oldMacAddress = htmlspecialchars($input->oldMacAddress); - $oldAddress = htmlspecialchars($input->oldAddress); - $macAddress = htmlspecialchars($input->macAddress); - $address = htmlspecialchars($input->address); - } catch (Exception $e) { - $response["message"] = $e->getMessage(); - return new JsonResponse(['error' => $response], 400); - } + try { + // Ejecutar el comando para obtener la configuración actual + $response = $this->curlKeaService->executeCurlCommand('config-get'); + $subnetFound = false; + $hostFound = false; - try { - $response = $this->curlKeaService->executeCurlCommand('config-get'); - $subnetFound = false; - $hostFound = false; + 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 ($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 && $reservation['ip-address'] == $oldAddress) { - $this->logger->info('FOUND HOST'); - $hostFound = true; - $reservation['hw-address'] = $macAddress; - $reservation['ip-address'] = $address; - $reservation['hostname'] = $host; - break; - } + 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; + break; } } } + } - if ($subnetFound && $hostFound) { - $this->logger->info('UPDATING HOST'); - $array_encoded = json_encode($response[0]['arguments']); - $configurationParsed = str_replace('\\', '', $array_encoded); - $configuration = json_decode($configurationParsed); + if ($subnetFound && $hostFound) { + $this->logger->info('UPDATING HOST'); - $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"]; + // Eliminar el campo 'hash' si existe + if (isset($response[0]['arguments']['hash'])) { + unset($response[0]['arguments']['hash']); + } + + // Preparar la configuración modificada + $array_encoded = json_encode($response[0]['arguments']); + $configurationParsed = str_replace('\\', '', $array_encoded); + $configuration = json_decode($configurationParsed); + + // Test de la configuración + $responseTest = $this->curlKeaService->executeCurlCommand('config-test', $configuration); + if ($responseTest[0]["result"] == 0) { + // 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); + } 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); } 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); - } + return new JsonResponse(['success' => "Host actualizado correctamente"], 200); } - } else { - $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); } - } elseif (!$subnetFound) { - $responseError = "Error: La subred con el id '$subnetId' no existe."; - return new JsonResponse(['error' => $responseError], 400); - } elseif (!$hostFound) { - $responseError = "Error: La IP " . $oldAddress . " y la MAC " . $oldMacAddress . " no existe en las reservaciones."; + } else { + $responseError = "Error en la configuración de Kea: " . $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); + } elseif (!$subnetFound) { + $responseError = "Error: La subred con el id '$subnetId' no existe."; + return new JsonResponse(['error' => $responseError], 404); + } elseif (!$hostFound) { + $responseError = "Error: El host con la MAC " . $oldMacAddress . " no existe en las reservaciones."; + return new JsonResponse(['error' => $responseError], 404); } + } catch (Exception $e) { + $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); + return new JsonResponse(['error' => $responseError], 400); } +} + public function restoreDhcpConfiguration(): JsonResponse {