refs #984 #1000 adds to modify subnet the gateway and makes nextserver and bootfilename optional parameters
testing/og-dhcp-API/pipeline/head There was a failure building this commit Details

nginx_conf
Luis Gerardo Romero Garcia 2024-10-21 09:15:11 +00:00
parent 9ea652070c
commit aaacfe1286
1 changed files with 171 additions and 197 deletions

View File

@ -363,8 +363,10 @@ public function getSubnets(): JsonResponse
$subnetId = (int) htmlspecialchars($input->subnetId); $subnetId = (int) htmlspecialchars($input->subnetId);
$mask = htmlspecialchars($input->mask); $mask = htmlspecialchars($input->mask);
$address = htmlspecialchars($input->address); $address = htmlspecialchars($input->address);
$nextServer = htmlspecialchars($input->nextServer);
$bootFileName = htmlspecialchars($input->bootFileName); // Verificar si next-server y boot-file-name están presentes
$nextServer = isset($input->nextServer) ? htmlspecialchars($input->nextServer) : null;
$bootFileName = isset($input->bootFileName) ? htmlspecialchars($input->bootFileName) : null;
} catch (Exception $e) { } catch (Exception $e) {
$response["message"] = $e->getMessage(); $response["message"] = $e->getMessage();
if (strpos($e->getMessage(), 'Undefined property') !== false) { if (strpos($e->getMessage(), 'Undefined property') !== false) {
@ -381,11 +383,10 @@ public function getSubnets(): JsonResponse
// Crear el campo option-data para la puerta de enlace (gateway) // Crear el campo option-data para la puerta de enlace (gateway)
$gatewayIP = substr($address, 0, strrpos($address, '.')) . '.1'; $gatewayIP = substr($address, 0, strrpos($address, '.')) . '.1';
// Crear el array newSubnet con los valores obligatorios
$newSubnet = [ $newSubnet = [
"id" => $subnetId, "id" => $subnetId,
"subnet" => $subnetName, "subnet" => $subnetName,
"next-server" => $nextServer,
"boot-file-name" => $bootFileName,
"reservations" => [], "reservations" => [],
"option-data" => [ "option-data" => [
[ [
@ -396,6 +397,16 @@ public function getSubnets(): JsonResponse
] ]
]; ];
// Añadir next-server si está presente
if ($nextServer) {
$newSubnet["next-server"] = $nextServer;
}
// Añadir boot-file-name si está presente
if ($bootFileName) {
$newSubnet["boot-file-name"] = $bootFileName;
}
if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) { if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) {
$response[0]['arguments']['Dhcp4']['subnet4'] = []; $response[0]['arguments']['Dhcp4']['subnet4'] = [];
} }
@ -466,6 +477,7 @@ public function getSubnets(): JsonResponse
} }
/** /**
* @OA\Delete( * @OA\Delete(
* path="/ogdhcp/v1/subnets/{subnetId}", * path="/ogdhcp/v1/subnets/{subnetId}",
@ -602,7 +614,6 @@ public function getSubnets(): JsonResponse
} }
} }
/** /**
* @Route("/ogdhcp/v1/subnets/{subnetId}", methods={"PUT"}) * @Route("/ogdhcp/v1/subnets/{subnetId}", methods={"PUT"})
* @OA\Put( * @OA\Put(
@ -613,9 +624,7 @@ public function getSubnets(): JsonResponse
* in="path", * in="path",
* description="ID of the subnet to modify", * description="ID of the subnet to modify",
* required=true, * required=true,
* @OA\Schema( * @OA\Schema(type="integer")
* type="integer"
* )
* ), * ),
* @OA\RequestBody( * @OA\RequestBody(
* description="Data to modify the subnet", * description="Data to modify the subnet",
@ -641,84 +650,45 @@ public function getSubnets(): JsonResponse
* description="Error occurred while deleting the subnet", * description="Error occurred while deleting the subnet",
* @OA\JsonContent( * @OA\JsonContent(
* oneOf={ * oneOf={
* @OA\Schema( * @OA\Schema(@OA\Property(property="error", type="string", example="Falta un parámetro requerido: $paramFaltante")),
* @OA\Property(property="error", type="string", example="Falta un parámetro requerido: $paramFaltante") * @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\Schema(@OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")),
* @OA\Property(property="error", type="string", example="No hay subredes definidas") * @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="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="parameterMissing",
* summary="Missing required parameter",
* value={"error": "Falta un parámetro requerido: $paramFaltante"}
* ),
* @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( * @OA\Response(
* response=404, * response=404,
* description="Subnet not found", * description="Subnet not found",
* @OA\JsonContent( * @OA\JsonContent(type="object", @OA\Property(property="error", type="string", example="La subred con el id '2' no existe"))
* type="object",
* @OA\Property(property="error", type="string", example="La subred con el id '2' no existe")
* )
* ), * ),
* @OA\Response( * @OA\Response(
* response=500, * response=500,
* description="Error saving configuration in Kea DHCP", * description="Error saving configuration in Kea DHCP",
* @OA\JsonContent( * @OA\JsonContent(type="object", @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP"))
* type="object",
* @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP")
* )
* ) * )
* ) * )
*/ */
public function modifyDhcpSubnet(Request $request): JsonResponse public function modifyDhcpSubnet(Request $request): JsonResponse
{ {
$subnetId = (int) $request->get('subnetId'); $subnetId = (int) $request->get('subnetId');
try { try {
$input = json_decode($request->getContent()); $input = json_decode($request->getContent());
$mask = htmlspecialchars($input->mask); $mask = htmlspecialchars($input->mask);
$address = htmlspecialchars($input->address); $address = htmlspecialchars($input->address);
$nextServer = htmlspecialchars($input->nextServer);
$bootFileName = htmlspecialchars($input->bootFileName); // Verificar si next-server y boot-file-name están presentes
$nextServer = isset($input->nextServer) ? htmlspecialchars($input->nextServer) : null;
$bootFileName = isset($input->bootFileName) ? htmlspecialchars($input->bootFileName) : null;
} catch (Exception $e) { } catch (Exception $e) {
$response["message"] = $e->getMessage();
if (strpos($e->getMessage(), 'Undefined property') !== false) { if (strpos($e->getMessage(), 'Undefined property') !== false) {
preg_match('/Undefined property: stdClass::\$(\w+)/', $e->getMessage(), $matches); preg_match('/Undefined property: stdClass::\$(\w+)/', $e->getMessage(), $matches);
$paramFaltante = $matches[1] ?? 'desconocido'; $paramFaltante = $matches[1] ?? 'desconocido';
return new JsonResponse(['error' => "Falta un parámetro requerido: $paramFaltante"], 400); return new JsonResponse(['error' => "Falta un parámetro requerido: $paramFaltante"], 400);
} }
return new JsonResponse(['error' => $e->getMessage()], 400);
} }
try { try {
@ -726,25 +696,21 @@ public function getSubnets(): JsonResponse
$subnetName = $address . '/' . $this->curlKeaService->convertMaskToCIDR($mask); $subnetName = $address . '/' . $this->curlKeaService->convertMaskToCIDR($mask);
if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) { if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) {
$responseError = "Error: No hay subredes definidas"; return new JsonResponse(['error' => "No hay subredes definidas"], 400);
return new JsonResponse(['error' => $responseError], 400);
} }
$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 = "La subred con el id '$subnetId' no existe"; return new JsonResponse(['error' => "La subred con el id '$subnetId' no existe"], 400);
return new JsonResponse(['error' => $responseError], 400);
} else { } else {
// Calcular el gateway añadiendo .1 al final de la subred // Calcular el gateway añadiendo .1 al final de la subred
$gateway = preg_replace('/\d+$/', '1', $address); $gateway = preg_replace('/\d+$/', '1', $address);
// Modificar la subred existente // Modificar la subred existente
$response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex] = [ $newSubnet = [
"id" => $subnetId, "id" => $subnetId,
"subnet" => $subnetName, "subnet" => $subnetName,
"next-server" => $nextServer,
"boot-file-name" => $bootFileName,
"reservations" => [], "reservations" => [],
"option-data" => [ "option-data" => [
[ [
@ -755,6 +721,18 @@ public function getSubnets(): JsonResponse
] ]
]; ];
// Añadir next-server si está presente
if ($nextServer) {
$newSubnet["next-server"] = $nextServer;
}
// Añadir boot-file-name si está presente
if ($bootFileName) {
$newSubnet["boot-file-name"] = $bootFileName;
}
$response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex] = $newSubnet;
// 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']);
@ -769,13 +747,11 @@ public function getSubnets(): 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 escribir en 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 {
// Volvemos a consultar la configuración para devolver la subred modificada // Volvemos a consultar la configuración para devolver la subred modificada
$updatedResponse = $this->curlKeaService->executeCurlCommand('config-get'); $updatedResponse = $this->curlKeaService->executeCurlCommand('config-get');
@ -783,20 +759,17 @@ public function getSubnets(): JsonResponse
return $subnet['id'] == $subnetId; return $subnet['id'] == $subnetId;
}); });
$responseSuccess = "Subred modificada correctamente"; return new JsonResponse(['success' => "Subred modificada correctamente", 'message' => reset($updatedSubnet)], 200);
return new JsonResponse(['success' => $responseSuccess,'message' => reset($updatedSubnet)], 200);
} }
} }
} else { } else {
$responseError = "Error configuracion de kea invalido: " . $responseTest[0]["text"]; return new JsonResponse(['error' => "Error configuracion de kea invalido: " . $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(); return new JsonResponse(['error' => "Error al obtener la configuración de Kea DHCP: " . $e->getMessage()], 500);
return new JsonResponse(['error' => $responseError], 500);
}
} }
}
/** /**
* @OA\Get( * @OA\Get(
@ -1566,3 +1539,4 @@ public function restoreDhcpConfiguration(): JsonResponse
} }