Merge pull request 'multiple-ogdhcp' (#89) from multiple-ogdhcp into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details

Reviewed-on: #89
pull/90/head
Juan Manuel Bardallo 2026-04-17 09:06:02 +02:00
commit e460d43336
28 changed files with 707 additions and 119 deletions

View File

@ -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.

View File

@ -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

View File

@ -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

View File

@ -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'

View File

@ -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:

View File

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260417132000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create DhcpServer entity and link to Subnet';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->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)');
// 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
{
// 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');
}
}

View File

@ -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());
}
}
}

View File

@ -1,41 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Controller\OgDhcp;
use App\Service\OgDhcp\StatusService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Entity\DhcpServer;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
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;
#[Route('/og-dhcp')]
#[AsController]
class OgDhcpController extends AbstractController
class StatusAction extends AbstractOgDhcpController
{
public function __construct(
private readonly StatusService $ogdhcpStatusService,
)
{
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
#[Route('/status', name: 'ogdhcp_status', methods: ['GET'])]
public function status(): JsonResponse
public function __invoke(DhcpServer $data): JsonResponse
{
$data = $this->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);
}
}
}

View File

@ -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'];

View File

@ -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);

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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);

View File

@ -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
);

View File

@ -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();

View File

@ -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);
}

View File

@ -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();
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Dto\Input;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
class DhcpServerInput
{
#[Assert\NotBlank]
#[Groups(['dhcp-server:write'])]
public ?string $name = null;
#[Assert\NotBlank]
#[Assert\Ip]
#[Groups(['dhcp-server:write'])]
public ?string $ip = null;
#[Groups(['dhcp-server:write'])]
public ?int $apiPort = 8081;
#[Groups(['dhcp-server:write'])]
public ?string $comments = null;
}

View File

@ -6,6 +6,7 @@ use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\OrganizationalUnitOutput;
use App\Dto\Output\SubnetOutput;
use App\Entity\Subnet;
use App\Entity\DhcpServer;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
@ -44,6 +45,10 @@ final class SubnetInput
#[ApiProperty(description: 'The boot file name of the subnet', example: "")]
public ?string $bootFileName = null;
#[Groups(['subnet:write'])]
#[ApiProperty(description: 'The DHCP server associated with this subnet')]
public ?string $dhcpServer = null;
/**
* @var OrganizationalUnitOutput[]
*/

View File

@ -0,0 +1,58 @@
<?php
namespace App\Dto\Output;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Get;
use App\Entity\DhcpServer;
use Symfony\Component\Serializer\Annotation\Groups;
#[Get(shortName: 'DhcpServer')]
class DhcpServerOutput extends AbstractOutput
{
#[Groups(['dhcp-server:read'])]
#[ApiProperty(
description: 'El nombre del servidor DHCP',
example: 'Servidor DHCP Principal'
)]
public ?string $name = '';
#[Groups(['dhcp-server:read'])]
#[ApiProperty(
description: 'La dirección IP del servidor DHCP',
example: '192.168.1.50'
)]
public ?string $ip = '';
#[Groups(['dhcp-server:read'])]
#[ApiProperty(
description: 'Puerto de la API OgDhcp',
example: '8081'
)]
public ?int $apiPort = 8081;
#[Groups(['dhcp-server:read'])]
#[ApiProperty(
description: 'Comentarios sobre el servidor',
example: 'Servidor principal de red'
)]
public ?string $comments = '';
#[Groups(['dhcp-server:read'])]
public \DateTime $createdAt;
#[Groups(['dhcp-server:read'])]
public ?string $createdBy = null;
public function __construct(DhcpServer $dhcpServer)
{
parent::__construct($dhcpServer);
$this->name = $dhcpServer->getName();
$this->ip = $dhcpServer->getIp();
$this->apiPort = $dhcpServer->getApiPort();
$this->comments = $dhcpServer->getComments();
$this->createdAt = $dhcpServer->getCreatedAt();
$this->createdBy = $dhcpServer->getCreatedBy();
}
}

106
src/Entity/DhcpServer.php Normal file
View File

@ -0,0 +1,106 @@
<?php
namespace App\Entity;
use App\Repository\DhcpServerRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
#[ORM\Entity(repositoryClass: DhcpServerRepository::class)]
#[ORM\UniqueConstraint(name: 'UNIQ_DHCP_SERVER_IP', fields: ['ip'])]
#[ORM\UniqueConstraint(name: 'UNIQ_DHCP_SERVER_NAME', fields: ['name'])]
#[UniqueEntity(fields: ['ip'], message: 'This IP address is already in use by another DHCP Server.')]
#[UniqueEntity(fields: ['name'], message: 'This name is already in use by another DHCP Server.')]
class DhcpServer extends AbstractEntity
{
use NameableTrait;
#[ORM\Column(length: 255)]
private ?string $ip = null;
#[ORM\Column(nullable: true)]
private ?int $apiPort = 8081;
#[ORM\Column(length: 255, nullable: true)]
private ?string $comments = null;
/**
* @var Collection<int, Subnet>
*/
#[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<int, Subnet>
*/
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;
}
}

View File

@ -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;

View File

@ -0,0 +1,23 @@
<?php
namespace App\Repository;
use App\Entity\DhcpServer;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<DhcpServer>
*
* @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);
}
}

View File

@ -1,48 +0,0 @@
<?php
namespace App\Service\OgDhcp;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
readonly class StatusService
{
public function __construct(
#[Autowire(env: 'OG_DHCP_API_URL')]
private string $ogDhcpApiUrl
)
{
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __invoke()
{
$httpClient = HttpClient::create([
'verify_peer' => 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);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\State\Processor;
use ApiPlatform\Metadata\DeleteOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Dto\Input\DhcpServerInput;
use App\Dto\Output\DhcpServerOutput;
use App\Entity\DhcpServer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class DhcpServerProcessor implements ProcessorInterface
{
public function __construct(private readonly EntityManagerInterface $entityManager)
{
}
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
{
if ($operation instanceof DeleteOperationInterface) {
return $this->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);
}
}

View File

@ -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() ) {

View File

@ -0,0 +1,79 @@
<?php
namespace App\State\Provider;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Put;
use ApiPlatform\State\Pagination\TraversablePaginator;
use ApiPlatform\State\ProviderInterface;
use App\Dto\Input\DhcpServerInput;
use App\Dto\Output\DhcpServerOutput;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
readonly class DhcpServerProvider implements ProviderInterface
{
public function __construct(
private ProviderInterface $collectionProvider,
private ProviderInterface $itemProvider
)
{
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
switch ($operation){
case $operation instanceof GetCollection:
return $this->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();
}
}