From 3160b22c55ce15d00081c6bdd0c44ad9b3d674e0 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 16 Apr 2026 14:56:11 +0200 Subject: [PATCH 1/2] =?UTF-8?q?Implementaci=C3=B3n=20para=20poder=20admini?= =?UTF-8?q?strar=20varios=20DHCP,=20se=20ha=20creado=20la=20clase=20padre?= =?UTF-8?q?=20DhpcServer=20y=20se=20ha=20creado=20una=20relacion=201-N=20c?= =?UTF-8?q?on=20subnet,=20de=20manera=20que=20ahora=20tenemos=20varios=20d?= =?UTF-8?q?hcp=20y=20cada=20uno=20de=20ellos=20pueden=20tener=20varias=20s?= =?UTF-8?q?ubredes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/api_platform/DhcpServer.yaml | 56 +++++++++ config/api_platform/Subnet.yaml | 15 --- config/services.yaml | 6 + config/services/api_platform.yaml | 2 +- migrations/Version20260414132000.php | 37 ++++++ .../OgDhcp/AbstractOgDhcpController.php | 11 +- ...{OgDhcpController.php => StatusAction.php} | 30 ++--- src/Controller/OgDhcp/Subnet/DeleteAction.php | 12 +- .../OgDhcp/Subnet/DeleteHostAction.php | 9 +- src/Controller/OgDhcp/Subnet/GetAction.php | 9 +- .../OgDhcp/Subnet/GetCollectionAction.php | 7 +- .../OgDhcp/Subnet/GetHostsAction.php | 9 +- src/Controller/OgDhcp/Subnet/PostAction.php | 25 ++++- .../OgDhcp/Subnet/PostHostAction.php | 9 +- src/Controller/OgDhcp/Subnet/PutAction.php | 9 +- .../OgDhcp/Subnet/PutHostAction.php | 9 +- src/Controller/OgDhcp/Subnet/SyncAction.php | 104 ++++++++++++++--- src/Dto/Input/DhcpServerInput.php | 24 ++++ src/Dto/Input/SubnetInput.php | 5 + src/Dto/Output/DhcpServerOutput.php | 58 ++++++++++ src/Entity/DhcpServer.php | 106 ++++++++++++++++++ src/Entity/Subnet.php | 15 +++ src/Repository/DhcpServerRepository.php | 23 ++++ src/Service/OgDhcp/StatusService.php | 48 -------- src/State/Processor/DhcpServerProcessor.php | 71 ++++++++++++ src/State/Processor/SubnetProcessor.php | 12 ++ src/State/Provider/DhcpServerProvider.php | 79 +++++++++++++ 27 files changed, 681 insertions(+), 119 deletions(-) create mode 100644 config/api_platform/DhcpServer.yaml create mode 100644 migrations/Version20260414132000.php rename src/Controller/OgDhcp/{OgDhcpController.php => StatusAction.php} (50%) create mode 100644 src/Dto/Input/DhcpServerInput.php create mode 100644 src/Dto/Output/DhcpServerOutput.php create mode 100644 src/Entity/DhcpServer.php create mode 100644 src/Repository/DhcpServerRepository.php delete mode 100644 src/Service/OgDhcp/StatusService.php create mode 100644 src/State/Processor/DhcpServerProcessor.php create mode 100644 src/State/Provider/DhcpServerProvider.php diff --git a/config/api_platform/DhcpServer.yaml b/config/api_platform/DhcpServer.yaml new file mode 100644 index 0000000..2208b65 --- /dev/null +++ b/config/api_platform/DhcpServer.yaml @@ -0,0 +1,56 @@ +resources: + App\Entity\DhcpServer: + processor: App\State\Processor\DhcpServerProcessor + input: App\Dto\Input\DhcpServerInput + output: App\Dto\Output\DhcpServerOutput + normalizationContext: + groups: ['default', 'dhcp-server:read'] + denormalizationContext: + groups: ['dhcp-server:write'] + operations: + ApiPlatform\Metadata\GetCollection: + provider: App\State\Provider\DhcpServerProvider + + ApiPlatform\Metadata\Get: + provider: App\State\Provider\DhcpServerProvider + + ApiPlatform\Metadata\Put: + provider: App\State\Provider\DhcpServerProvider + + ApiPlatform\Metadata\Patch: + provider: App\State\Provider\DhcpServerProvider + + ApiPlatform\Metadata\Post: ~ + ApiPlatform\Metadata\Delete: ~ + + subnet_sync: + shortName: DhcpServer + class: ApiPlatform\Metadata\Post + method: POST + input: false + uriTemplate: /dhcp-servers/{uuid}/sync + controller: App\Controller\OgDhcp\Subnet\SyncAction + + get_collection_subnets: + shortName: DhcpServer + description: Get collection of Subnets from external dhcp server + class: ApiPlatform\Metadata\Post + method: POST + input: false + uriTemplate: /dhcp-servers/{uuid}/get-collection + controller: App\Controller\OgDhcp\Subnet\GetCollectionAction + dhcp_server_status: + shortName: DhcpServer + description: Get status of OgDhcp + class: ApiPlatform\Metadata\Get + method: GET + input: false + uriTemplate: /dhcp-servers/server/{uuid}/status + controller: App\Controller\OgDhcp\StatusAction + +properties: + App\Entity\DhcpServer: + id: + identifier: false + uuid: + identifier: true diff --git a/config/api_platform/Subnet.yaml b/config/api_platform/Subnet.yaml index 72ef541..28ede92 100644 --- a/config/api_platform/Subnet.yaml +++ b/config/api_platform/Subnet.yaml @@ -23,21 +23,6 @@ resources: ApiPlatform\Metadata\Post: ~ ApiPlatform\Metadata\Delete: ~ - subnet_sync: - class: ApiPlatform\Metadata\Post - method: POST - input: false - uriTemplate: /subnets/sync - controller: App\Controller\OgDhcp\Subnet\SyncAction - - get_collection_subnets: - shortName: Subnet Server - description: Get collection of Subnet - class: ApiPlatform\Metadata\GetCollection - method: GET - input: false - uriTemplate: /og-dhcp/server/get-collection - controller: App\Controller\OgDhcp\Subnet\GetCollectionAction get_subnet: shortName: Subnet Server diff --git a/config/services.yaml b/config/services.yaml index 5ece707..4080ff4 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -137,6 +137,12 @@ services: bind: $collectionProvider: '@api_platform.doctrine.orm.state.collection_provider' $itemProvider: '@api_platform.doctrine.orm.state.item_provider' + + App\State\Provider\DhcpServerProvider: + bind: + $collectionProvider: '@api_platform.doctrine.orm.state.collection_provider' + $itemProvider: '@api_platform.doctrine.orm.state.item_provider' + App\State\Provider\TraceProvider: bind: $collectionProvider: '@api_platform.doctrine.orm.state.collection_provider' diff --git a/config/services/api_platform.yaml b/config/services/api_platform.yaml index 19a2e47..2d7ad74 100644 --- a/config/services/api_platform.yaml +++ b/config/services/api_platform.yaml @@ -293,7 +293,7 @@ services: api_platform.filter.subnet.search: parent: 'api_platform.doctrine.orm.search_filter' - arguments: [ { 'id': 'exact', 'name': 'partial', ip: 'exact', nextServer: 'exact', netmask: 'exact', bootFileName: 'partial'} ] + arguments: [ { 'id': 'exact', 'name': 'partial', ip: 'exact', nextServer: 'exact', netmask: 'exact', bootFileName: 'partial', 'dhcpServer.uuid': 'exact'} ] tags: [ 'api_platform.filter' ] api_platform.filter.trace.search: diff --git a/migrations/Version20260414132000.php b/migrations/Version20260414132000.php new file mode 100644 index 0000000..0ce7316 --- /dev/null +++ b/migrations/Version20260414132000.php @@ -0,0 +1,37 @@ +addSql('CREATE TABLE dhcp_server (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, ip VARCHAR(255) NOT NULL, api_port INT DEFAULT 8006 NOT NULL, comments VARCHAR(255) DEFAULT NULL, uuid CHAR(36) NOT NULL COMMENT \'(DC2Type:uuid)\', UNIQUE INDEX UNIQ_IDENTIFIER_IP (ip), UNIQUE INDEX UNIQ_IDENTIFIER_NAME (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); + $this->addSql('ALTER TABLE subnet ADD dhcp_server_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE subnet ADD CONSTRAINT FK_50551F51C2C88941 FOREIGN KEY (dhcp_server_id) REFERENCES dhcp_server (id)'); + $this->addSql('CREATE INDEX IDX_50551F51C2C88941 ON subnet (dhcp_server_id)'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('ALTER TABLE subnet DROP FOREIGN KEY FK_50551F51C2C88941'); + $this->addSql('DROP TABLE dhcp_server'); + $this->addSql('DROP INDEX IDX_50551F51C2C88941 ON subnet'); + $this->addSql('ALTER TABLE subnet DROP dhcp_server_id'); + } +} diff --git a/src/Controller/OgDhcp/AbstractOgDhcpController.php b/src/Controller/OgDhcp/AbstractOgDhcpController.php index 5041840..6c535f1 100644 --- a/src/Controller/OgDhcp/AbstractOgDhcpController.php +++ b/src/Controller/OgDhcp/AbstractOgDhcpController.php @@ -4,11 +4,9 @@ declare(strict_types=1); namespace App\Controller\OgDhcp; -use App\Controller\OgBoot\PxeBootFile\PostAction; use App\Service\Utils\GetIpAddressAndNetmaskFromCIDRService; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; -use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\AsController; @@ -23,8 +21,6 @@ use Symfony\Contracts\HttpClient\HttpClientInterface; abstract class AbstractOgDhcpController extends AbstractController { public function __construct( - #[Autowire(env: 'OG_DHCP_API_URL')] - protected readonly string $ogDhcpApiUrl, protected readonly EntityManagerInterface $entityManager, protected readonly GetIpAddressAndNetmaskFromCIDRService $getIpAddressAndNetmaskFromCIDRService, protected readonly HttpClientInterface $httpClient, @@ -45,6 +41,7 @@ abstract class AbstractOgDhcpController extends AbstractController 'accept' => 'application/json', 'Content-Type' => 'application/json' ], + 'timeout' => 30, // Also added a timeout similar to OgRepository ]); try { @@ -53,10 +50,12 @@ abstract class AbstractOgDhcpController extends AbstractController return json_decode($response->getContent(), true); } catch (ClientExceptionInterface | ServerExceptionInterface $e) { $response = $e->getResponse(); + $statusCode = $response->getStatusCode(); $content = json_decode($response->getContent(false), true); - throw new HttpException($response->getStatusCode(), $content['error'] ?? 'An error occurred'); + $errorMessage = $content['error'] ?? $content['message'] ?? $e->getMessage(); + throw new HttpException($statusCode, "External API Error ($statusCode): $errorMessage"); } catch (TransportExceptionInterface $e) { - throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, $e->getMessage()); + throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, "Transport Error: " . $e->getMessage()); } } } diff --git a/src/Controller/OgDhcp/OgDhcpController.php b/src/Controller/OgDhcp/StatusAction.php similarity index 50% rename from src/Controller/OgDhcp/OgDhcpController.php rename to src/Controller/OgDhcp/StatusAction.php index f67f01f..9f69f92 100644 --- a/src/Controller/OgDhcp/OgDhcpController.php +++ b/src/Controller/OgDhcp/StatusAction.php @@ -1,41 +1,35 @@ ogdhcpStatusService->__invoke(); + $content = $this->createRequest('GET', 'http://'.$data->getIp(). ':'.$data->getApiPort().'/ogdhcp/v1/status'); - return new JsonResponse( data: $data, status: Response::HTTP_OK); + if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { + throw new BadRequestHttpException('An error occurred while fetching the status: ' . $content['details']); + } + + return new JsonResponse( data: $content, status: Response::HTTP_OK); } -} +} \ No newline at end of file diff --git a/src/Controller/OgDhcp/Subnet/DeleteAction.php b/src/Controller/OgDhcp/Subnet/DeleteAction.php index 383e587..0e7eb42 100644 --- a/src/Controller/OgDhcp/Subnet/DeleteAction.php +++ b/src/Controller/OgDhcp/Subnet/DeleteAction.php @@ -31,11 +31,15 @@ class DeleteAction extends AbstractOgDhcpController throw new BadRequestHttpException('Data Id is required'); } + $dhcpServer = $data->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets/%d', $dhcpServer->getIp(), $port, $data->getServerId()); + try { - $content = $this->createRequest( - 'DELETE', - 'http://' . $this->ogDhcpApiUrl . '/ogdhcp/v1/subnets/' . $data->getServerId() - ); + $content = $this->createRequest('DELETE', $url); } catch (HttpException $e) { if ($e->getStatusCode() === 404) { $content = ['message' => 'Subnet not found on external API, proceeding with local deletion']; diff --git a/src/Controller/OgDhcp/Subnet/DeleteHostAction.php b/src/Controller/OgDhcp/Subnet/DeleteHostAction.php index 0959f78..a4f0c72 100644 --- a/src/Controller/OgDhcp/Subnet/DeleteHostAction.php +++ b/src/Controller/OgDhcp/Subnet/DeleteHostAction.php @@ -43,7 +43,14 @@ class DeleteHostAction extends AbstractOgDhcpController ] ]; - $content = $this->createRequest('DELETE', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/subnets/'.$data->getServerId().'/hosts', $params); + $dhcpServer = $data->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets/%d/hosts', $dhcpServer->getIp(), $port, $data->getServerId()); + + $content = $this->createRequest('DELETE', $url, $params); $data->removeClient($client); $this->entityManager->persist($data); diff --git a/src/Controller/OgDhcp/Subnet/GetAction.php b/src/Controller/OgDhcp/Subnet/GetAction.php index b9e7ee2..bd272fd 100644 --- a/src/Controller/OgDhcp/Subnet/GetAction.php +++ b/src/Controller/OgDhcp/Subnet/GetAction.php @@ -30,7 +30,14 @@ class GetAction extends AbstractOgDhcpController throw new BadRequestHttpException('Checksum is required'); } - $content = $this->createRequest('GET', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/subnets/'.$data->getServerId()); + $dhcpServer = $data->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets/%d', $dhcpServer->getIp(), $port, $data->getServerId()); + + $content = $this->createRequest('GET', $url); return new JsonResponse(data: $content, status: Response::HTTP_OK); } diff --git a/src/Controller/OgDhcp/Subnet/GetCollectionAction.php b/src/Controller/OgDhcp/Subnet/GetCollectionAction.php index 51fb4d9..6bdb02a 100644 --- a/src/Controller/OgDhcp/Subnet/GetCollectionAction.php +++ b/src/Controller/OgDhcp/Subnet/GetCollectionAction.php @@ -21,9 +21,12 @@ class GetCollectionAction extends AbstractOgDhcpController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(): JsonResponse + public function __invoke(\App\Entity\DhcpServer $data): JsonResponse { - $content = $this->createRequest('GET', 'http://'.$this->ogDhcpApiUrl . '/ogdhcp/v1/subnets'); + $port = $data->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets', $data->getIp(), $port); + + $content = $this->createRequest('GET', $url); return new JsonResponse(data: $content, status: Response::HTTP_OK); } diff --git a/src/Controller/OgDhcp/Subnet/GetHostsAction.php b/src/Controller/OgDhcp/Subnet/GetHostsAction.php index d0334dd..cac5a4e 100644 --- a/src/Controller/OgDhcp/Subnet/GetHostsAction.php +++ b/src/Controller/OgDhcp/Subnet/GetHostsAction.php @@ -30,7 +30,14 @@ class GetHostsAction extends AbstractOgDhcpController throw new BadRequestHttpException('Checksum is required'); } - $content = $this->createRequest('GET', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/subnets/'.$data->getServerId().'/hosts'); + $dhcpServer = $data->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets/%d/hosts', $dhcpServer->getIp(), $port, $data->getServerId()); + + $content = $this->createRequest('GET', $url); return new JsonResponse(data: $content, status: Response::HTTP_OK); } diff --git a/src/Controller/OgDhcp/Subnet/PostAction.php b/src/Controller/OgDhcp/Subnet/PostAction.php index 9cfc41d..bf804e6 100644 --- a/src/Controller/OgDhcp/Subnet/PostAction.php +++ b/src/Controller/OgDhcp/Subnet/PostAction.php @@ -4,6 +4,7 @@ namespace App\Controller\OgDhcp\Subnet; use App\Controller\OgDhcp\AbstractOgDhcpController; use App\Entity\Subnet; +use App\Entity\DhcpServer; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\AsController; @@ -23,11 +24,26 @@ class PostAction extends AbstractOgDhcpController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(Subnet $data): JsonResponse + public function __invoke(Subnet|string $dataOrUuid): JsonResponse { + if ($dataOrUuid instanceof Subnet) { + $data = $dataOrUuid; + } else { + $data = $this->entityManager->getRepository(Subnet::class)->findOneBy(['uuid' => $dataOrUuid]); + } + + if (!$data) { + throw new \Exception('Subred no encontrada.'); + } + + $dhcpServer = $data->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $params = [ 'json' => [ - 'subnetId' => rand(1, 1000), + 'subnetId' => $data->getServerId() ?? rand(1, 1000), 'mask' => $data->getNetmask(), 'address' => $data->getIpAddress(), 'nextServer' => $data->getNextServer(), @@ -37,7 +53,10 @@ class PostAction extends AbstractOgDhcpController ] ]; - $content = $this->createRequest('POST', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/subnets' , $params); + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets', $dhcpServer->getIp(), $port); + + $content = $this->createRequest('POST', $url, $params); $data->setServerId($content['message']['id']); $data->setSynchronized(true); diff --git a/src/Controller/OgDhcp/Subnet/PostHostAction.php b/src/Controller/OgDhcp/Subnet/PostHostAction.php index 4b518c2..469c543 100644 --- a/src/Controller/OgDhcp/Subnet/PostHostAction.php +++ b/src/Controller/OgDhcp/Subnet/PostHostAction.php @@ -47,9 +47,16 @@ class PostHostAction extends AbstractOgDhcpController $params = ['json' => $data]; try { + $dhcpServer = $subnet->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets/%d/hosts', $dhcpServer->getIp(), $port, $subnet->getServerId()); + $content = $this->createRequest( 'POST', - 'http://' . $this->ogDhcpApiUrl . '/ogdhcp/v1/subnets/' . $subnet->getServerId() . '/hosts', + $url, $params ); diff --git a/src/Controller/OgDhcp/Subnet/PutAction.php b/src/Controller/OgDhcp/Subnet/PutAction.php index c90d626..d96d63c 100644 --- a/src/Controller/OgDhcp/Subnet/PutAction.php +++ b/src/Controller/OgDhcp/Subnet/PutAction.php @@ -41,7 +41,14 @@ class PutAction extends AbstractOgDhcpController ] ]; - $content = $this->createRequest('PUT', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/subnets/'.$data->getServerId(), $params); + $dhcpServer = $data->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets/%d', $dhcpServer->getIp(), $port, $data->getServerId()); + + $content = $this->createRequest('PUT', $url, $params); $this->entityManager->persist($data); $this->entityManager->flush(); diff --git a/src/Controller/OgDhcp/Subnet/PutHostAction.php b/src/Controller/OgDhcp/Subnet/PutHostAction.php index d7b6a45..4adcc28 100644 --- a/src/Controller/OgDhcp/Subnet/PutHostAction.php +++ b/src/Controller/OgDhcp/Subnet/PutHostAction.php @@ -40,7 +40,14 @@ class PutHostAction extends AbstractOgDhcpController 'json' => $data ]; - $content = $this->createRequest('PUT', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/subnets/'.$subnet->getServerId().'/hosts', $params); + $dhcpServer = $subnet->getDhcpServer(); + if (!$dhcpServer) { + throw new \Exception('La subred no tiene un servidor DHCP asociado.'); + } + $port = $dhcpServer->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets/%d/hosts', $dhcpServer->getIp(), $port, $subnet->getServerId()); + + $content = $this->createRequest('PUT', $url, $params); return new JsonResponse(status: Response::HTTP_OK); } diff --git a/src/Controller/OgDhcp/Subnet/SyncAction.php b/src/Controller/OgDhcp/Subnet/SyncAction.php index a409eff..7c0adbb 100644 --- a/src/Controller/OgDhcp/Subnet/SyncAction.php +++ b/src/Controller/OgDhcp/Subnet/SyncAction.php @@ -4,16 +4,17 @@ namespace App\Controller\OgDhcp\Subnet; use App\Controller\OgDhcp\AbstractOgDhcpController; use App\Entity\Client; +use App\Model\ClientStatus; use App\Entity\Subnet; -use Doctrine\ORM\EntityManagerInterface; +use App\Entity\DhcpServer; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\AsController; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; -use Symfony\Contracts\HttpClient\HttpClientInterface; #[AsController] class SyncAction extends AbstractOgDhcpController @@ -24,20 +25,40 @@ class SyncAction extends AbstractOgDhcpController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(EntityManagerInterface $entityManager): JsonResponse + public function __invoke(DhcpServer $data, Request $request): JsonResponse { - $content = $this->createRequest('GET', 'http://'.$this->ogDhcpApiUrl . '/ogdhcp/v1/subnets'); + $port = $data->getApiPort() ?? 8081; + $url = sprintf('http://%s:%d/ogdhcp/v1/subnets', $data->getIp(), $port); + $content = $this->createRequest('GET', $url); $arraySync = []; + $parentOuId = null; + $contentRequest = json_decode($request->getContent(), true); + if ($contentRequest && isset($contentRequest['parentOuId'])) { + $parentOuId = $contentRequest['parentOuId']; + } + + $parentOu = null; + if ($parentOuId) { + $parentOu = $this->entityManager->getRepository(\App\Entity\OrganizationalUnit::class)->findOneBy(['uuid' => $parentOuId]); + } + + $skippedClients = []; + foreach ($content['message'] as $subnet) { - $subnetEntity = $this->entityManager->getRepository(Subnet::class)->findOneBy(['serverId' => $subnet['id']]); + $subnetEntity = $this->entityManager->getRepository(Subnet::class)->findOneBy([ + 'serverId' => $subnet['id'], + 'dhcpServer' => $data + ]); + if ($subnetEntity) { - $this->extracted($subnetEntity, $subnet); + $this->extracted($subnetEntity, $subnet, $parentOu, $skippedClients); $this->entityManager->persist($subnetEntity); } else { $subnetEntity = new Subnet(); - $this->extracted($subnetEntity, $subnet); + $subnetEntity->setDhcpServer($data); + $this->extracted($subnetEntity, $subnet, $parentOu, $skippedClients); } $arraySync[] = $subnet['id']; @@ -47,10 +68,12 @@ class SyncAction extends AbstractOgDhcpController $this->entityManager->persist($subnetEntity); } - $this->setSynchronized($arraySync); + $this->setSynchronized($arraySync, $data); $this->entityManager->flush(); + $content['skipped_clients'] = $skippedClients; + return new JsonResponse(data: $content, status: Response::HTTP_OK); } @@ -59,7 +82,7 @@ class SyncAction extends AbstractOgDhcpController * @param mixed $subnet * @return void */ - private function extracted(Subnet|null $subnetEntity, mixed $subnet): void + private function extracted(Subnet|null $subnetEntity, mixed $subnet, ?\App\Entity\OrganizationalUnit $parentOu = null, array &$skippedClients = []): void { $getParsedData = $this->getIpAddressAndNetmaskFromCIDRService->__invoke($subnet['subnet']); @@ -69,22 +92,71 @@ class SyncAction extends AbstractOgDhcpController $subnetEntity->setNetmask($getParsedData['mask']); $subnetEntity->setNextServer($subnet['next-server'] ?? null); + if (isset($subnet['option-data']) && is_array($subnet['option-data'])) { + foreach ($subnet['option-data'] as $option) { + if ($option['name'] === 'routers') { + $subnetEntity->setRouter($option['data']); + } + if ($option['name'] === 'domain-name-servers') { + $subnetEntity->setDns($option['data']); + } + } + } + + $classroomOu = null; + if ($parentOu) { + $classroomName = 'Subred -'.$subnet['id']; + $classroomOu = $this->entityManager->getRepository(\App\Entity\OrganizationalUnit::class)->findOneBy([ + 'name' => $classroomName, + 'parent' => $parentOu, + 'type' => 'group' + ]); + + if (!$classroomOu) { + $classroomOu = new \App\Entity\OrganizationalUnit(); + $classroomOu->setName($classroomName); + $classroomOu->setType('group'); + $classroomOu->setParent($parentOu); + $this->entityManager->persist($classroomOu); + } + } + foreach ($subnet['reservations'] as $host) { $hostEntity = $this->entityManager->getRepository(Client::class)->findOneBy(['mac' => $host['hw-address']]); if ($hostEntity){ $subnetEntity->addClient($hostEntity); + // Registramos siempre la colisión, independientemente de si hay Auto-Discovery o no + $skippedClients[] = $hostEntity->getName() ?? $host['hw-address']; + } elseif ($classroomOu) { + $hostEntity = new Client(); + $hostname = !empty($host['hostname']) ? $host['hostname'] : 'PC-'.str_replace(':', '', $host['hw-address']); + $hostEntity->setName($hostname); + $hostEntity->setMac($host['hw-address']); + $hostEntity->setIp($host['ip-address']); + $hostEntity->setMaintenance(false); + $hostEntity->setOrganizationalUnit($classroomOu); + $hostEntity->setStatus(ClientStatus::OFF); + + $this->entityManager->persist($hostEntity); + $subnetEntity->addClient($hostEntity); } } } - public function setSynchronized(array $array): void + public function setSynchronized(array $array, DhcpServer $dhcpServer): void { - $this->entityManager->createQueryBuilder() - ->update(Subnet::class, 's') + $qb = $this->entityManager->createQueryBuilder(); + $q = $qb->update(Subnet::class, 's') ->set('s.synchronized', 'false') - ->where('s.serverId NOT IN (:array)') - ->setParameter('array', array_values($array)) - ->getQuery() - ->getResult(); + ->where('s.dhcpServer = :dhcpServer'); + + if (!empty($array)) { + $q->andWhere('s.serverId NOT IN (:array)') + ->setParameter('array', array_values($array)); + } + + $q->setParameter('dhcpServer', $dhcpServer) + ->getQuery() + ->getResult(); } } \ No newline at end of file diff --git a/src/Dto/Input/DhcpServerInput.php b/src/Dto/Input/DhcpServerInput.php new file mode 100644 index 0000000..d90bf61 --- /dev/null +++ b/src/Dto/Input/DhcpServerInput.php @@ -0,0 +1,24 @@ +name = $dhcpServer->getName(); + $this->ip = $dhcpServer->getIp(); + $this->apiPort = $dhcpServer->getApiPort(); + $this->comments = $dhcpServer->getComments(); + $this->createdAt = $dhcpServer->getCreatedAt(); + $this->createdBy = $dhcpServer->getCreatedBy(); + } +} diff --git a/src/Entity/DhcpServer.php b/src/Entity/DhcpServer.php new file mode 100644 index 0000000..7e5b342 --- /dev/null +++ b/src/Entity/DhcpServer.php @@ -0,0 +1,106 @@ + + */ + #[ORM\OneToMany(mappedBy: 'dhcpServer', targetEntity: Subnet::class, cascade: ['persist', 'remove'])] + private Collection $subnets; + + public function __construct() + { + parent::__construct(); + $this->subnets = new ArrayCollection(); + } + + public function getIp(): ?string + { + return $this->ip; + } + + public function setIp(string $ip): static + { + $this->ip = $ip; + + return $this; + } + + public function getApiPort(): ?int + { + return $this->apiPort; + } + + public function setApiPort(?int $apiPort): static + { + $this->apiPort = $apiPort; + + return $this; + } + + public function getComments(): ?string + { + return $this->comments; + } + + public function setComments(?string $comments): static + { + $this->comments = $comments; + + return $this; + } + + /** + * @return Collection + */ + public function getSubnets(): Collection + { + return $this->subnets; + } + + public function addSubnet(Subnet $subnet): static + { + if (!$this->subnets->contains($subnet)) { + $this->subnets->add($subnet); + $subnet->setDhcpServer($this); + } + + return $this; + } + + public function removeSubnet(Subnet $subnet): static + { + if ($this->subnets->removeElement($subnet)) { + // set the owning side to null (unless already changed) + if ($subnet->getDhcpServer() === $this) { + $subnet->setDhcpServer(null); + } + } + + return $this; + } +} diff --git a/src/Entity/Subnet.php b/src/Entity/Subnet.php index 0ce6a1e..ef3699c 100644 --- a/src/Entity/Subnet.php +++ b/src/Entity/Subnet.php @@ -37,6 +37,9 @@ class Subnet extends AbstractEntity #[ORM\OneToMany(mappedBy: 'subnet', targetEntity: Client::class)] private Collection $clients; + #[ORM\ManyToOne(inversedBy: 'subnets', targetEntity: DhcpServer::class)] + private ?DhcpServer $dhcpServer = null; + #[ORM\Column(nullable: true)] private ?int $serverId = null; @@ -182,6 +185,18 @@ class Subnet extends AbstractEntity return $this; } + public function getDhcpServer(): ?DhcpServer + { + return $this->dhcpServer; + } + + public function setDhcpServer(?DhcpServer $dhcpServer): static + { + $this->dhcpServer = $dhcpServer; + + return $this; + } + public function getServerId(): ?int { return $this->serverId; diff --git a/src/Repository/DhcpServerRepository.php b/src/Repository/DhcpServerRepository.php new file mode 100644 index 0000000..633df5e --- /dev/null +++ b/src/Repository/DhcpServerRepository.php @@ -0,0 +1,23 @@ + + * + * @method DhcpServer|null find($id, $lockMode = null, $lockVersion = null) + * @method DhcpServer|null findOneBy(array $criteria, array $orderBy = null) + * @method DhcpServer[] findAll() + * @method DhcpServer[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + */ +class DhcpServerRepository extends ServiceEntityRepository +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, DhcpServer::class); + } +} diff --git a/src/Service/OgDhcp/StatusService.php b/src/Service/OgDhcp/StatusService.php deleted file mode 100644 index 6c9cadf..0000000 --- a/src/Service/OgDhcp/StatusService.php +++ /dev/null @@ -1,48 +0,0 @@ - false, - 'verify_host' => false, - ]); - - try { - $response = $httpClient->request('GET', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/status', [ - 'headers' => [ - 'accept' => 'application/json', - ], - ]); - } catch (TransportExceptionInterface $e) { - return new JsonResponse( data: 'An error occurred', status: Response::HTTP_INTERNAL_SERVER_ERROR); - } - - return json_decode($response->getContent(), true); - } -} \ No newline at end of file diff --git a/src/State/Processor/DhcpServerProcessor.php b/src/State/Processor/DhcpServerProcessor.php new file mode 100644 index 0000000..7b2be30 --- /dev/null +++ b/src/State/Processor/DhcpServerProcessor.php @@ -0,0 +1,71 @@ +deleteDhcpServer($uriVariables['uuid']); + } + + if ($operation->getMethod() === 'POST' || $operation->getMethod() === 'PATCH' || $operation->getMethod() === 'PUT') { + return $this->saveDhcpServer($data, $uriVariables['uuid'] ?? null); + } + + return null; // For operations that are handled by provider + } + + private function deleteDhcpServer(string $uuid): ?DhcpServerOutput + { + $dhcpServer = $this->entityManager->getRepository(DhcpServer::class)->findOneBy(['uuid' => $uuid]); + + if (!$dhcpServer) { + throw new NotFoundHttpException('DHCP Server not found'); + } + + $this->entityManager->remove($dhcpServer); + $this->entityManager->flush(); + + return null; + } + + private function saveDhcpServer(DhcpServerInput $data, ?string $uuid = null): DhcpServerOutput + { + if ($uuid) { + $dhcpServer = $this->entityManager->getRepository(DhcpServer::class)->findOneBy(['uuid' => $uuid]); + + if (!$dhcpServer) { + throw new NotFoundHttpException('DHCP Server not found'); + } + } else { + $dhcpServer = new DhcpServer(); + } + + $dhcpServer->setName($data->name); + $dhcpServer->setIp($data->ip); + if ($data->apiPort !== null) { + $dhcpServer->setApiPort($data->apiPort); + } + $dhcpServer->setComments($data->comments); + + $this->entityManager->persist($dhcpServer); + $this->entityManager->flush(); + + return new DhcpServerOutput($dhcpServer); + } +} diff --git a/src/State/Processor/SubnetProcessor.php b/src/State/Processor/SubnetProcessor.php index a999601..bb67d06 100644 --- a/src/State/Processor/SubnetProcessor.php +++ b/src/State/Processor/SubnetProcessor.php @@ -14,12 +14,14 @@ use App\Controller\OgDhcp\Subnet\PutAction; use App\Dto\Input\SubnetInput; use App\Dto\Output\SubnetOutput; use App\Repository\SubnetRepository; +use App\Repository\DhcpServerRepository; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; readonly class SubnetProcessor implements ProcessorInterface { public function __construct( private SubnetRepository $subnetRepository, + private DhcpServerRepository $dhcpServerRepository, private ValidatorInterface $validator, private PostAction $postAction, private PutAction $putAction, @@ -58,6 +60,16 @@ readonly class SubnetProcessor implements ProcessorInterface } $subnet = $data->createOrUpdateEntity($entity); + + if ($data->dhcpServer) { + $parts = explode('/', rtrim($data->dhcpServer, '/')); + $uuid = end($parts); + $dhcpServer = $this->dhcpServerRepository->findOneBy(['uuid' => $uuid]); + if ($dhcpServer) { + $subnet->setDhcpServer($dhcpServer); + } + } + $this->validator->validate($subnet); if (!$subnet->getId() ) { diff --git a/src/State/Provider/DhcpServerProvider.php b/src/State/Provider/DhcpServerProvider.php new file mode 100644 index 0000000..f6c694a --- /dev/null +++ b/src/State/Provider/DhcpServerProvider.php @@ -0,0 +1,79 @@ +provideCollection($operation, $uriVariables, $context); + case $operation instanceof Patch: + case $operation instanceof Put: + return $this->provideInput($operation, $uriVariables, $context); + case $operation instanceof Get: + return $this->provideItem($operation, $uriVariables, $context); + } + } + + private function provideCollection(Operation $operation, array $uriVariables = [], array $context = []): object + { + $paginator = $this->collectionProvider->provide($operation, $uriVariables, $context); + + $items = new \ArrayObject(); + foreach ($paginator->getIterator() as $item){ + $items[] = new DhcpServerOutput($item); + } + + return new TraversablePaginator($items, $paginator->getCurrentPage(), $paginator->getItemsPerPage(), $paginator->getTotalItems()); + } + + public function provideItem(Operation $operation, array $uriVariables = [], array $context = []): object|array|null + { + $item = $this->itemProvider->provide($operation, $uriVariables, $context); + + if (!$item) { + throw new NotFoundHttpException('DHCP Server not found'); + } + + return new DhcpServerOutput($item); + } + + public function provideInput(Operation $operation, array $uriVariables = [], array $context = []): object|array|null + { + if (isset($uriVariables['uuid'])) { + $item = $this->itemProvider->provide($operation, $uriVariables, $context); + + if ($item !== null) { + $input = new DhcpServerInput(); + $input->name = $item->getName(); + $input->ip = $item->getIp(); + $input->apiPort = $item->getApiPort(); + $input->comments = $item->getComments(); + return $input; + } + return null; + } + + return new DhcpServerInput(); + } +} -- 2.40.1 From 8578ff8b839bc7dd08f4fa03768544e0b4566597 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Fri, 17 Apr 2026 08:42:56 +0200 Subject: [PATCH 2/2] Modificacion en el fichero migrations para que las subnets existentes les asigne un servidor dhcp por defecto al migrar --- CHANGELOG.md | 4 ++++ ...14132000.php => Version20260417132000.php} | 24 ++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) rename migrations/{Version20260414132000.php => Version20260417132000.php} (56%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39d73b1..1bbe989 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [1.5.0] - 2026-04-16 +### Added +- Creada nueva estructura jerárquica para administrar varios DHCPs, la clase Subnet ahora tiene una clase padre DhcpServer, de manera que tenemos una relación 1-N entre DhcpServer y Subnet (un servidor Dhcp puede tener varias Subnets) + ## [1.4.2] - 2026-04-13 ### Fixed - Añadido fichero de migración con el cambio en la base de datos para añadir la fecha de despliegue de una partición. diff --git a/migrations/Version20260414132000.php b/migrations/Version20260417132000.php similarity index 56% rename from migrations/Version20260414132000.php rename to migrations/Version20260417132000.php index 0ce7316..0b1eb44 100644 --- a/migrations/Version20260414132000.php +++ b/migrations/Version20260417132000.php @@ -10,7 +10,7 @@ use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ -final class Version20260414132000 extends AbstractMigration +final class Version20260417132000 extends AbstractMigration { public function getDescription(): string { @@ -24,6 +24,28 @@ final class Version20260414132000 extends AbstractMigration $this->addSql('ALTER TABLE subnet ADD dhcp_server_id INT DEFAULT NULL'); $this->addSql('ALTER TABLE subnet ADD CONSTRAINT FK_50551F51C2C88941 FOREIGN KEY (dhcp_server_id) REFERENCES dhcp_server (id)'); $this->addSql('CREATE INDEX IDX_50551F51C2C88941 ON subnet (dhcp_server_id)'); + + // Extract old legacy DHCP URL from env.json if exists, else fallback + $url = '127.0.0.1:8081'; + $envFile = __DIR__ . '/../env.json'; + if (file_exists($envFile)) { + $envData = json_decode(file_get_contents($envFile), true); + if (isset($envData['vars']['OG_DHCP_API_URL'])) { + $url = $envData['vars']['OG_DHCP_API_URL']; + } + } + + // Normalize URL format before parsing since env.json stores it raw like '127.0.0.1:8081' + $url = (str_starts_with($url, 'http')) ? $url : 'http://' . $url; + $parsed = parse_url($url); + $ip = $parsed['host'] ?? '127.0.0.1'; + $port = isset($parsed['port']) ? $parsed['port'] : 8081; + + // Create a default instance to absorb existing subnets and prevent orphans + $this->addSql(sprintf("INSERT INTO dhcp_server (name, ip, api_port, uuid) VALUES ('Servidor DHCP Local (Migrado)', '%s', %d, UUID())", $ip, $port)); + + // Relink all existing orphan subnets to this newly created default server + $this->addSql("UPDATE subnet SET dhcp_server_id = (SELECT id FROM dhcp_server LIMIT 1) WHERE dhcp_server_id IS NULL"); } public function down(Schema $schema): void -- 2.40.1