diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bbe989..f7611a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [1.6.0] - 2026-04-21 +### Added +- Creada nueva estructura jerárquica para administrar varios OgBoot servers, las clases PxeTemplate y OgLive ahora tiene una clase padre BootServer, de manera que tenemos una relación 1-N entre BootServer y dichas clases (un Boot Server puede tener varias Plantillas PXE y varios OgLives) + ## [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) diff --git a/config/api_platform/BootServer.yaml b/config/api_platform/BootServer.yaml new file mode 100644 index 0000000..058339d --- /dev/null +++ b/config/api_platform/BootServer.yaml @@ -0,0 +1,88 @@ +resources: + App\Entity\BootServer: + processor: App\State\Processor\BootServerProcessor + input: App\Dto\Input\BootServerInput + output: App\Dto\Output\BootServerOutput + normalizationContext: + groups: ['default', 'boot-server:read'] + denormalizationContext: + groups: ['boot-server:write'] + operations: + ApiPlatform\Metadata\GetCollection: + provider: App\State\Provider\BootServerProvider + ApiPlatform\Metadata\Get: + provider: App\State\Provider\BootServerProvider + ApiPlatform\Metadata\Put: + provider: App\State\Provider\BootServerProvider + ApiPlatform\Metadata\Patch: + provider: App\State\Provider\BootServerProvider + ApiPlatform\Metadata\Post: ~ + ApiPlatform\Metadata\Delete: ~ + + oglives_sync: + shortName: BootServer + class: ApiPlatform\Metadata\Post + method: POST + input: false + uriTemplate: /boot-servers/{uuid}/oglives/sync + controller: App\Controller\OgBoot\OgLive\SyncAction + + pxe_templates_sync: + shortName: BootServer + class: ApiPlatform\Metadata\Post + method: POST + input: false + uriTemplate: /boot-servers/{uuid}/pxe-templates/sync + controller: App\Controller\OgBoot\PxeTemplate\SyncAction + + get_collection_oglives: + shortName: BootServer + description: Get collection of OgLives from external boot server + class: ApiPlatform\Metadata\Get + method: GET + input: false + uriTemplate: /boot-servers/{uuid}/oglives/get-collection + controller: App\Controller\OgBoot\OgLive\GetCollectionAction + + get_isos: + shortName: BootServer + description: Get Isos of OgLive from external boot server + class: ApiPlatform\Metadata\Get + method: GET + input: false + uriTemplate: /boot-servers/{uuid}/oglives/get-isos + controller: App\Controller\OgBoot\OgLive\GetIsosAction + + get_default_oglive: + shortName: BootServer + description: Get default OgLive attached to BootServer + class: ApiPlatform\Metadata\Get + method: GET + input: false + uriTemplate: /boot-servers/{uuid}/oglives/get-default + controller: App\Controller\OgBoot\OgLive\GetDefaultAction + + get_collection_templates: + shortName: BootServer + description: Get collection of PxeTemplate from external boot server + class: ApiPlatform\Metadata\Get + method: GET + input: false + uriTemplate: /boot-servers/{uuid}/pxe-templates/get-collection + controller: App\Controller\OgBoot\PxeTemplate\GetCollectionAction + + boot_server_status: + shortName: BootServer + description: Get status of OgBoot server + class: ApiPlatform\Metadata\Get + method: GET + input: false + uriTemplate: /boot-servers/server/{uuid}/status + controller: App\Controller\OgBoot\StatusAction + +properties: + App\Entity\BootServer: + id: + identifier: false + uuid: + identifier: true diff --git a/config/api_platform/OgLive.yaml b/config/api_platform/OgLive.yaml index a40fa2a..5b5a284 100644 --- a/config/api_platform/OgLive.yaml +++ b/config/api_platform/OgLive.yaml @@ -24,22 +24,6 @@ resources: ApiPlatform\Metadata\Post: ~ ApiPlatform\Metadata\Delete: ~ - oglives_sync: - class: ApiPlatform\Metadata\Post - method: POST - input: false - uriTemplate: /og-lives/sync - controller: App\Controller\OgBoot\OgLive\SyncAction - - get_collection_oglives: - shortName: OgLive Server - description: Get collection of OgLive - class: ApiPlatform\Metadata\GetCollection - method: GET - input: false - uriTemplate: /og-lives/server/get-collection - controller: App\Controller\OgBoot\OgLive\GetCollectionAction - get_oglive: shortName: OgLive Server description: Get OgLive @@ -49,24 +33,6 @@ resources: uriTemplate: /og-lives/server/{uuid}/get controller: App\Controller\OgBoot\OgLive\GetAction - get_isos: - shortName: OgLive Server - description: Get Isos of OgLive - class: ApiPlatform\Metadata\GetCollection - method: GET - input: false - uriTemplate: /og-lives/server/get-isos - controller: App\Controller\OgBoot\OgLive\GetIsosAction - - get_default: - shortName: OgLive Server - description: Get default OgLive - class: ApiPlatform\Metadata\GetCollection - method: GET - input: false - uriTemplate: /og-lives/server/get-default - controller: App\Controller\OgBoot\OgLive\GetDefaultAction - set_default: shortName: OgLive Server description: Set default OgLive diff --git a/config/api_platform/PxeTemplate.yaml b/config/api_platform/PxeTemplate.yaml index ce4ae4d..faa67c4 100644 --- a/config/api_platform/PxeTemplate.yaml +++ b/config/api_platform/PxeTemplate.yaml @@ -24,22 +24,6 @@ resources: ApiPlatform\Metadata\Post: ~ ApiPlatform\Metadata\Delete: ~ - pxe_template_sync: - class: ApiPlatform\Metadata\Post - method: POST - input: false - uriTemplate: /pxe-templates/sync - controller: App\Controller\OgBoot\PxeTemplate\SyncAction - - get_collection_templates: - shortName: PxeTemplate Server - description: Get collection of PxeTemplate - class: ApiPlatform\Metadata\GetCollection - method: GET - input: false - uriTemplate: /pxe-templates/server/get-collection - controller: App\Controller\OgBoot\PxeTemplate\GetCollectionAction - get_template: shortName: PxeTemplate Server description: Get PxeTemplate diff --git a/config/services.yaml b/config/services.yaml index 4080ff4..f4560ed 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -172,3 +172,8 @@ services: bind: $collectionProvider: '@api_platform.doctrine.orm.state.collection_provider' $itemProvider: '@api_platform.doctrine.orm.state.item_provider' + + App\State\Provider\BootServerProvider: + bind: + $collectionProvider: '@api_platform.doctrine.orm.state.collection_provider' + $itemProvider: '@api_platform.doctrine.orm.state.item_provider' diff --git a/config/services/api_platform.yaml b/config/services/api_platform.yaml index 6810947..2553ba1 100644 --- a/config/services/api_platform.yaml +++ b/config/services/api_platform.yaml @@ -132,7 +132,7 @@ services: api_platform.filter.og_live.search: parent: 'api_platform.doctrine.orm.search_filter' - arguments: [ { 'id': 'exact', 'name': 'partial', 'status': 'exact' } ] + arguments: [ { 'id': 'exact', 'name': 'partial', 'status': 'exact', 'bootServer.uuid': 'exact' } ] tags: [ 'api_platform.filter' ] api_platform.filter.og_live.boolean: @@ -212,7 +212,7 @@ services: api_platform.filter.pxe_template.search: parent: 'api_platform.doctrine.orm.search_filter' - arguments: [ { 'id': 'exact', 'name': 'partial', } ] + arguments: [ { 'id': 'exact', 'name': 'partial', 'bootServer.uuid': 'exact' } ] tags: [ 'api_platform.filter' ] api_platform.filter.pxe_template.boolean: diff --git a/migrations/Version20260420123904.php b/migrations/Version20260420123904.php new file mode 100644 index 0000000..9e9d1e7 --- /dev/null +++ b/migrations/Version20260420123904.php @@ -0,0 +1,76 @@ +addSql('CREATE TABLE boot_server (id INT AUTO_INCREMENT NOT NULL, uuid CHAR(36) NOT NULL COMMENT \'(DC2Type:uuid)\', migration_id VARCHAR(255) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, created_by VARCHAR(255) DEFAULT NULL, updated_by VARCHAR(255) DEFAULT NULL, name VARCHAR(255) NOT NULL, ip VARCHAR(255) NOT NULL, api_port INT DEFAULT 8082 NOT NULL, pxe_port INT DEFAULT 8082 NOT NULL, comments VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D621FDFCD17F50A6 (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 client ADD boot_server_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE client ADD CONSTRAINT FK_C744045537E4C0FC FOREIGN KEY (boot_server_id) REFERENCES boot_server (id) ON DELETE SET NULL'); + $this->addSql('CREATE INDEX IDX_C744045537E4C0FC ON client (boot_server_id)'); + $this->addSql('ALTER TABLE network_settings ADD boot_server_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE network_settings ADD CONSTRAINT FK_48869B5437E4C0FC FOREIGN KEY (boot_server_id) REFERENCES boot_server (id) ON DELETE SET NULL'); + $this->addSql('CREATE INDEX IDX_48869B5437E4C0FC ON network_settings (boot_server_id)'); + $this->addSql('ALTER TABLE og_live ADD boot_server_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE og_live ADD CONSTRAINT FK_3D6B773937E4C0FC FOREIGN KEY (boot_server_id) REFERENCES boot_server (id)'); + $this->addSql('CREATE INDEX IDX_3D6B773937E4C0FC ON og_live (boot_server_id)'); + $this->addSql('ALTER TABLE `partition` CHANGE cache_content cache_content LONGTEXT DEFAULT NULL'); + $this->addSql('ALTER TABLE pxe_template ADD boot_server_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE pxe_template ADD CONSTRAINT FK_7319755437E4C0FC FOREIGN KEY (boot_server_id) REFERENCES boot_server (id)'); + $this->addSql('CREATE INDEX IDX_7319755437E4C0FC ON pxe_template (boot_server_id)'); + + // Extract old legacy OgBoot URL from env.json if exists, else fallback + $ip = '127.0.0.1'; + $envFile = __DIR__ . '/../env.json'; + if (file_exists($envFile)) { + $envData = json_decode(file_get_contents($envFile), true); + if (isset($envData['vars']['OG_BOOT_IP'])) { + $ip = $envData['vars']['OG_BOOT_IP']; + } + } + + // Create a default instance to absorb existing relations and prevent orphans + $this->addSql(sprintf("INSERT INTO boot_server (uuid, created_at, updated_at, name, ip, api_port, pxe_port) VALUES (UUID(), NOW(), NOW(), 'Servidor OgBoot Local (Migrado)', '%s', 8082, 8082)", $ip)); + + // Relink all existing orphan properties to this newly created default server + $this->addSql("UPDATE og_live SET boot_server_id = (SELECT id FROM boot_server LIMIT 1) WHERE boot_server_id IS NULL"); + $this->addSql("UPDATE pxe_template SET boot_server_id = (SELECT id FROM boot_server LIMIT 1) WHERE boot_server_id IS NULL"); + $this->addSql("UPDATE network_settings SET boot_server_id = (SELECT id FROM boot_server LIMIT 1) WHERE boot_server_id IS NULL"); + $this->addSql("UPDATE client SET boot_server_id = (SELECT id FROM boot_server LIMIT 1) WHERE boot_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 client DROP FOREIGN KEY FK_C744045537E4C0FC'); + $this->addSql('ALTER TABLE network_settings DROP FOREIGN KEY FK_48869B5437E4C0FC'); + $this->addSql('ALTER TABLE og_live DROP FOREIGN KEY FK_3D6B773937E4C0FC'); + $this->addSql('ALTER TABLE pxe_template DROP FOREIGN KEY FK_7319755437E4C0FC'); + $this->addSql('DROP TABLE boot_server'); + $this->addSql('DROP INDEX IDX_48869B5437E4C0FC ON network_settings'); + $this->addSql('ALTER TABLE network_settings DROP boot_server_id'); + $this->addSql('DROP INDEX IDX_7319755437E4C0FC ON pxe_template'); + $this->addSql('ALTER TABLE pxe_template DROP boot_server_id'); + $this->addSql('DROP INDEX IDX_C744045537E4C0FC ON client'); + $this->addSql('ALTER TABLE client DROP boot_server_id'); + $this->addSql('ALTER TABLE `partition` CHANGE cache_content cache_content VARCHAR(255) DEFAULT NULL'); + $this->addSql('DROP INDEX IDX_3D6B773937E4C0FC ON og_live'); + $this->addSql('ALTER TABLE og_live DROP boot_server_id'); + } +} diff --git a/migrations/Version20260421091127.php b/migrations/Version20260421091127.php new file mode 100644 index 0000000..7879110 --- /dev/null +++ b/migrations/Version20260421091127.php @@ -0,0 +1,37 @@ +addSql('DROP INDEX UNIQ_IDENTIFIER_FILENAME ON og_live'); + $this->addSql('CREATE UNIQUE INDEX UNIQ_OGLIVE_FILENAME_SERVER ON og_live (filename, boot_server_id)'); + $this->addSql('DROP INDEX UNIQ_IDENTIFIER_NAME ON pxe_template'); + $this->addSql('CREATE UNIQUE INDEX UNIQ_PXE_TEMPLATE_NAME_SERVER ON pxe_template (name, boot_server_id)'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('DROP INDEX UNIQ_PXE_TEMPLATE_NAME_SERVER ON pxe_template'); + $this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_NAME ON pxe_template (name)'); + $this->addSql('DROP INDEX UNIQ_OGLIVE_FILENAME_SERVER ON og_live'); + $this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_FILENAME ON og_live (filename)'); + } +} diff --git a/src/Controller/OgBoot/AbstractOgBootController.php b/src/Controller/OgBoot/AbstractOgBootController.php index 2d3918e..e1b7b9b 100644 --- a/src/Controller/OgBoot/AbstractOgBootController.php +++ b/src/Controller/OgBoot/AbstractOgBootController.php @@ -69,21 +69,49 @@ abstract class AbstractOgBootController extends AbstractController return json_decode($response->getContent(), true); } catch (ClientExceptionInterface | ServerExceptionInterface $e) { - $this->logger->error(sprintf('Client/Server error in request to %s: %s', $url, $e->getMessage())); - - return [ - 'code' => Response::HTTP_INTERNAL_SERVER_ERROR, - 'error' => 'Client/Server error', - 'details' => $e->getMessage(), - ]; + $response = $e->getResponse(); + $statusCode = $response->getStatusCode(); + $content = json_decode($response->getContent(false), true); + $errorMessage = $content['error'] ?? $content['message'] ?? $e->getMessage(); + + $this->logger->error(sprintf('Client/Server error in request to %s: %s', $url, $errorMessage)); + throw new HttpException($statusCode, "External API Error ($statusCode): $errorMessage"); } catch (TransportExceptionInterface $e) { $this->logger->error(sprintf('Transport error in request to %s: %s', $url, $e->getMessage())); + throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, "Transport Error: " . $e->getMessage()); + } + } - return [ - 'code' => Response::HTTP_INTERNAL_SERVER_ERROR, - 'error' => 'Transport error', - 'details' => $e->getMessage(), - ]; + /** + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + * @throws RedirectionExceptionInterface + * @throws ClientExceptionInterface + */ + public function createRequestFromBootServer (\App\Entity\BootServer $bootServer, string $method, string $url, array $params = []): JsonResponse|array + { + $params = array_merge($params, [ + 'headers' => [ + 'accept' => 'application/json', + 'Content-Type' => 'application/json' + ], + ]); + + try { + $response = $this->httpClient->request($method, 'http://'.$bootServer->getIp().':'.$bootServer->getApiPort().$url, $params); + + return json_decode($response->getContent(), true); + } catch (ClientExceptionInterface | ServerExceptionInterface $e) { + $response = $e->getResponse(); + $statusCode = $response->getStatusCode(); + $content = json_decode($response->getContent(false), true); + $errorMessage = $content['error'] ?? $content['message'] ?? $e->getMessage(); + + $this->logger->error(sprintf('Client/Server error in request to %s: %s', $url, $errorMessage)); + throw new HttpException($statusCode, "External API Error ($statusCode): $errorMessage"); + } catch (TransportExceptionInterface $e) { + $this->logger->error(sprintf('Transport error in request to %s: %s', $url, $e->getMessage())); + throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, "Transport Error: " . $e->getMessage()); } } } diff --git a/src/Controller/OgBoot/OgLive/GetAction.php b/src/Controller/OgBoot/OgLive/GetAction.php index cceeddf..0c21c21 100644 --- a/src/Controller/OgBoot/OgLive/GetAction.php +++ b/src/Controller/OgBoot/OgLive/GetAction.php @@ -30,7 +30,12 @@ class GetAction extends AbstractOgBootController throw new BadRequestHttpException('Checksum is required'); } - $content = $this->createRequest('GET', '/ogboot/v1/oglives/'.$data->getChecksum()); + $bootServer = $data->getBootServer(); + if (!$bootServer) { + throw new BadRequestHttpException('This OgLive is not attached to any BootServer.'); + } + + $content = $this->createRequestFromBootServer($bootServer, 'GET', '/ogboot/v1/oglives/'.$data->getChecksum()); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred while fetching the OgLive: ' . $content['error']. ' (' . $content['details'] . ')'); diff --git a/src/Controller/OgBoot/OgLive/GetCollectionAction.php b/src/Controller/OgBoot/OgLive/GetCollectionAction.php index f328530..22e5d3c 100644 --- a/src/Controller/OgBoot/OgLive/GetCollectionAction.php +++ b/src/Controller/OgBoot/OgLive/GetCollectionAction.php @@ -22,9 +22,9 @@ class GetCollectionAction extends AbstractOgBootController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(): JsonResponse + public function __invoke(\App\Entity\BootServer $data): JsonResponse { - $content = $this->createRequest('GET', '/ogboot/v1/oglives'); + $content = $this->createRequestFromBootServer($data, 'GET', '/ogboot/v1/oglives'); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred while fetching the collection: ' . $content['error']. ' (' . $content['details'] . ')'); diff --git a/src/Controller/OgBoot/OgLive/GetDefaultAction.php b/src/Controller/OgBoot/OgLive/GetDefaultAction.php index 5feea2e..903792a 100644 --- a/src/Controller/OgBoot/OgLive/GetDefaultAction.php +++ b/src/Controller/OgBoot/OgLive/GetDefaultAction.php @@ -22,9 +22,9 @@ class GetDefaultAction extends AbstractOgBootController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(): JsonResponse + public function __invoke(\App\Entity\BootServer $data): JsonResponse { - $content = $this->createRequest('GET', '/ogboot/v1/oglives/default'); + $content = $this->createRequestFromBootServer($data, 'GET', '/ogboot/v1/oglives/default'); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred: ' . $content['error']. ' (' . $content['details'] . ')'); diff --git a/src/Controller/OgBoot/OgLive/GetIsosAction.php b/src/Controller/OgBoot/OgLive/GetIsosAction.php index ff97ab5..39fab88 100644 --- a/src/Controller/OgBoot/OgLive/GetIsosAction.php +++ b/src/Controller/OgBoot/OgLive/GetIsosAction.php @@ -22,9 +22,9 @@ class GetIsosAction extends AbstractOgBootController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(): JsonResponse + public function __invoke(\App\Entity\BootServer $data): JsonResponse { - $content = $this->createRequest('GET', '/ogboot/v1/oglives/isos'); + $content = $this->createRequestFromBootServer($data, 'GET', '/ogboot/v1/oglives/isos'); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred while fetching ISOs: ' . $content['error']. ' (' . $content['details'] . ')'); diff --git a/src/Controller/OgBoot/OgLive/InstallAction.php b/src/Controller/OgBoot/OgLive/InstallAction.php index 5d09625..67ed159 100644 --- a/src/Controller/OgBoot/OgLive/InstallAction.php +++ b/src/Controller/OgBoot/OgLive/InstallAction.php @@ -46,7 +46,12 @@ class InstallAction extends AbstractOgBootController 'uuid' => 'InstallOgLive_'.$data->getUuid() ]; - $content = $this->createRequest('POST', '/ogboot/v1/oglives/install', $params); + $bootServer = $data->getBootServer(); + if (!$bootServer) { + throw new BadRequestHttpException('This OgLive is not attached to any BootServer.'); + } + + $content = $this->createRequestFromBootServer($bootServer, 'POST', '/ogboot/v1/oglives/install', $params); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred while installing OgLive: ' . $content['error']. ' (' . $content['details'] . ')'); diff --git a/src/Controller/OgBoot/OgLive/SetDefaultAction.php b/src/Controller/OgBoot/OgLive/SetDefaultAction.php index c9e4ca7..47e41e5 100644 --- a/src/Controller/OgBoot/OgLive/SetDefaultAction.php +++ b/src/Controller/OgBoot/OgLive/SetDefaultAction.php @@ -37,13 +37,18 @@ class SetDefaultAction extends AbstractOgBootController ] ]; - $content = $this->createRequest('PUT', '/ogboot/v1/oglives/default', $params); + $bootServer = $data->getBootServer(); + if (!$bootServer) { + throw new BadRequestHttpException('This OgLive is not attached to any BootServer.'); + } + + $content = $this->createRequestFromBootServer($bootServer, 'PUT', '/ogboot/v1/oglives/default', $params); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred: ' . $content['error'] . ' (' . $content['details'] . ')'); } - $oldDefaultOgLive = $this->entityManager->getRepository(OgLive::class)->findBy(['isDefault' => true]); + $oldDefaultOgLive = $this->entityManager->getRepository(OgLive::class)->findBy(['isDefault' => true, 'bootServer' => $bootServer]); foreach ($oldDefaultOgLive as $oldOgLive) { $oldOgLive->setIsDefault(false); diff --git a/src/Controller/OgBoot/OgLive/SyncAction.php b/src/Controller/OgBoot/OgLive/SyncAction.php index 6bd57ae..a29358c 100644 --- a/src/Controller/OgBoot/OgLive/SyncAction.php +++ b/src/Controller/OgBoot/OgLive/SyncAction.php @@ -28,9 +28,9 @@ class SyncAction extends AbstractOgBootController * @throws ClientExceptionInterface * @throws \Exception */ - public function __invoke(): JsonResponse + public function __invoke(\App\Entity\BootServer $data): JsonResponse { - $content = $this->createRequest('GET', '/ogboot/v1/oglives'); + $content = $this->createRequestFromBootServer($data, 'GET', '/ogboot/v1/oglives'); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred while fetching ogLives: ' . $content['message'] . ' (' . $content['details'] . ')'); @@ -40,20 +40,27 @@ class SyncAction extends AbstractOgBootController $apiChecksums = array_map(fn($ogLive) => $ogLive['id'], $content['message']['installed_ogLives']); foreach ($content['message']['installed_ogLives'] as $ogLive) { - $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['checksum' => $ogLive['id']]); + $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['checksum' => $ogLive['id'], 'bootServer' => $data]); if (!$ogLiveEntity) { - $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['filename' => str_replace(self::OG_BOOT_DIRECTORY, '', $ogLive['directory'])]); + $filename = str_replace(self::OG_BOOT_DIRECTORY, '', $ogLive['directory']); + $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['filename' => $filename, 'bootServer' => $data]); if (!$ogLiveEntity) { $ogLiveEntity = new OgLive(); } } + $ogLiveEntity->setBootServer($data); $this->extracted($ogLiveEntity, $ogLive); $this->entityManager->persist($ogLiveEntity); } foreach ($allOgLives as $localOgLive) { + // Only process OgLives that belong to THIS boot server + if ($localOgLive->getBootServer() !== $data) { + continue; + } + if ($localOgLive->getStatus() === OgLiveStatus::PENDING ) { continue; } @@ -66,7 +73,7 @@ class SyncAction extends AbstractOgBootController $this->entityManager->flush(); if (isset($content['message']['default_oglive'])) { - $this->serDefaultOgLive($content['message']['default_oglive']); + $this->serDefaultOgLive($content['message']['default_oglive'], $data); } return new JsonResponse(data: $content, status: Response::HTTP_OK); @@ -95,16 +102,16 @@ class SyncAction extends AbstractOgBootController $ogLiveEntity->setStatus(OgLiveStatus::ACTIVE); } - private function serDefaultOgLive(string $defaultOgLive): void + private function serDefaultOgLive(string $defaultOgLive, \App\Entity\BootServer $data): void { - $oldDefaultOgLive = $this->entityManager->getRepository(OgLive::class)->findAll(); + $oldDefaultOgLive = $this->entityManager->getRepository(OgLive::class)->findBy(['bootServer' => $data]); foreach ($oldDefaultOgLive as $oldOgLive) { $oldOgLive->setIsDefault(false); $this->entityManager->persist($oldOgLive); } - $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['filename' => $defaultOgLive]); + $ogLiveEntity = $this->entityManager->getRepository(OgLive::class)->findOneBy(['filename' => $defaultOgLive, 'bootServer' => $data]); if (!$ogLiveEntity) { return; diff --git a/src/Controller/OgBoot/OgLive/UninstallAction.php b/src/Controller/OgBoot/OgLive/UninstallAction.php index 47948a0..9e5e34a 100644 --- a/src/Controller/OgBoot/OgLive/UninstallAction.php +++ b/src/Controller/OgBoot/OgLive/UninstallAction.php @@ -32,7 +32,12 @@ class UninstallAction extends AbstractOgBootController throw new BadRequestHttpException('Checksum is required'); } - $content = $this->createRequest( 'DELETE', '/ogboot/v1/oglives/'.$data->getChecksum()); + $bootServer = $data->getBootServer(); + if (!$bootServer) { + throw new BadRequestHttpException('This OgLive is not attached to any BootServer.'); + } + + $content = $this->createRequestFromBootServer($bootServer, 'DELETE', '/ogboot/v1/oglives/'.$data->getChecksum()); if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred while uninstalling the OgLive: ' . $content['error'] . ' (' . $content['details'] . ')'); diff --git a/src/Controller/OgBoot/PxeBootFile/PostAction.php b/src/Controller/OgBoot/PxeBootFile/PostAction.php index 4ca7410..6ed0b09 100644 --- a/src/Controller/OgBoot/PxeBootFile/PostAction.php +++ b/src/Controller/OgBoot/PxeBootFile/PostAction.php @@ -32,15 +32,21 @@ class PostAction extends AbstractOgBootController $ogLive = $client->getOgLive()?->getFilename() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getOgLive()?->getFilename(); + $bootServer = $pxeTemplate->getBootServer(); + + if (!$bootServer) { + throw new \RuntimeException('The PXE template does not have an associated boot server.'); + } + $params = [ 'json' => [ 'template_name' => $pxeTemplate->getName(), 'mac' => strtolower($client->getMac()), 'lang' => 'es_ES.UTF-8', 'ip' => $client->getIp(), - 'server_ip' => $this->ogBootIp, - 'server_api_port' => $this->ogBootApiPort, - 'server_pxe_port' => $this->ogBootPxePort, + 'server_ip' => $bootServer->getIp(), + 'server_api_port' => $bootServer->getApiPort(), + 'server_pxe_port' => $bootServer->getPxePort(), 'router' => $client->getOrganizationalUnit()->getNetworkSettings()?->getRouter(), 'netmask' => $client->getOrganizationalUnit()->getNetworkSettings() ? $client->getOrganizationalUnit()->getNetworkSettings()->getNetmask() : '255.255.255.0', 'computer_name' => $client->getName(), @@ -48,10 +54,10 @@ class PostAction extends AbstractOgBootController 'group' => $client->getOrganizationalUnit()->getName(), 'ogrepo' => $ogRepoIp, 'ogcore' => $this->ogCoreIP, - 'oglive' => $this->ogBootIp, + 'oglive' => $bootServer->getIp(), 'oglog' => $this->ogLogIp, 'ogshare' => $client->getOrganizationalUnit()->getNetworkSettings()?->getOgShare() - ? $client->getOrganizationalUnit()->getNetworkSettings()?->getOgShare(): $this->ogBootIp, + ? $client->getOrganizationalUnit()->getNetworkSettings()?->getOgShare(): $bootServer->getIp(), 'oglivedir' => $ogLive, 'ogprof' => 'false', 'hardprofile' => $client->getHardwareProfile() ? $client->getHardwareProfile()->getDescription() : 'default', @@ -63,7 +69,7 @@ class PostAction extends AbstractOgBootController ] ]; - $content = $this->createRequest('POST', '/ogboot/v1/pxes', $params); + $content = $this->createRequestFromBootServer($bootServer, 'POST', '/ogboot/v1/pxes', $params); $client->setPxeSync(true); $this->entityManager->persist($client); diff --git a/src/Controller/OgBoot/PxeTemplate/AddClientAction.php b/src/Controller/OgBoot/PxeTemplate/AddClientAction.php index 01a00a8..f62f749 100644 --- a/src/Controller/OgBoot/PxeTemplate/AddClientAction.php +++ b/src/Controller/OgBoot/PxeTemplate/AddClientAction.php @@ -40,12 +40,30 @@ class AddClientAction extends AbstractController $clients = $input->clients; foreach ($clients as $client) { - $this->postAction->__invoke($client->getEntity(), $pxeTemplate); - /** @var Client $clientEntity */ $clientEntity = $client->getEntity(); + + $newBootServer = $pxeTemplate->getBootServer(); + $oldBootServer = $clientEntity->getBootServer(); + + // If the boot server changes, we must also update the ogLive to the new server's default + if ($oldBootServer !== $newBootServer) { + $clientEntity->setBootServer($newBootServer); + + $defaultOgLive = $this->entityManager->getRepository(\App\Entity\OgLive::class)->findOneBy([ + 'bootServer' => $newBootServer, + 'isDefault' => true + ]); + + if ($defaultOgLive) { + $clientEntity->setOgLive($defaultOgLive); + } + } + $clientEntity->setTemplate($pxeTemplate); + $this->postAction->__invoke($clientEntity, $pxeTemplate); + $this->entityManager->persist($clientEntity); } diff --git a/src/Controller/OgBoot/PxeTemplate/DeleteAction.php b/src/Controller/OgBoot/PxeTemplate/DeleteAction.php index 51d97ef..1eb7153 100644 --- a/src/Controller/OgBoot/PxeTemplate/DeleteAction.php +++ b/src/Controller/OgBoot/PxeTemplate/DeleteAction.php @@ -29,24 +29,34 @@ class DeleteAction extends AbstractOgBootController */ public function __invoke(PxeTemplate $data): JsonResponse { + $bootServer = $data->getBootServer(); + if (!$bootServer) { + throw new BadRequestHttpException('This PxeTemplate is not attached to any BootServer.'); + } + + // Notify remote server first + $content = $this->createRequestFromBootServer($bootServer, 'DELETE', '/ogboot/v1/pxe-templates/'.$data->getName()); + + if (isset($content['error']) && $content['error'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { + throw new BadRequestHttpException('Remote server error: ' . $content['error']); + } + + // Delete from local DB if remote call succeeded $this->entityManager->remove($data); $this->entityManager->flush(); - $content = $this->createRequest('DELETE', '/ogboot/v1/pxe-templates/'.$data->getName()); - - if (isset($content['error']) && $content['error'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { - throw new BadRequestHttpException('An error occurred: ' . $content['error']); - } - + // Check for default template to inform the user $defaultTemplateEntity = $this->entityManager->getRepository(PxeTemplate::class)->findOneBy(['isDefault' => true]); + $responseData = [ + 'status' => 'success', + 'message' => 'Plantilla eliminada correctamente.' + ]; + if ($defaultTemplateEntity === null) { - return new JsonResponse( - 'Default template not found', - Response::HTTP_NOT_FOUND - ); + $responseData['warning'] = 'No se ha detectado ninguna otra plantilla marcada por defecto en este servidor.'; } - return new JsonResponse(status: Response::HTTP_OK); + return new JsonResponse($responseData, Response::HTTP_OK); } } \ No newline at end of file diff --git a/src/Controller/OgBoot/PxeTemplate/GetAction.php b/src/Controller/OgBoot/PxeTemplate/GetAction.php index cc94c2c..bc4b6d5 100644 --- a/src/Controller/OgBoot/PxeTemplate/GetAction.php +++ b/src/Controller/OgBoot/PxeTemplate/GetAction.php @@ -23,15 +23,20 @@ class GetAction extends AbstractOgBootController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(PxeTemplate $template, HttpClientInterface $httpClient): JsonResponse + public function __invoke(PxeTemplate $template): JsonResponse { - $response = $this->createRequest('GET', '/ogboot/v1/pxe-templates/'.$template->getName()); + $bootServer = $template->getBootServer(); + if (!$bootServer) { + return new JsonResponse( data: 'No boot server attached to template', status: Response::HTTP_BAD_REQUEST); + } - if ($response->getStatusCode() !== Response::HTTP_OK) { + $response = $this->createRequestFromBootServer($bootServer, 'GET', '/ogboot/v1/pxe-templates/'.$template->getName()); + + if (isset($response['error'])) { return new JsonResponse( data: 'An error occurred', status: Response::HTTP_INTERNAL_SERVER_ERROR); } - $data = json_decode($response->getContent(), true); + $data = $response; $template->setName($data['template_name']); $template->setTemplateContent($data['template_content']); diff --git a/src/Controller/OgBoot/PxeTemplate/GetCollectionAction.php b/src/Controller/OgBoot/PxeTemplate/GetCollectionAction.php index 7c63ae0..ffa619d 100644 --- a/src/Controller/OgBoot/PxeTemplate/GetCollectionAction.php +++ b/src/Controller/OgBoot/PxeTemplate/GetCollectionAction.php @@ -24,9 +24,9 @@ class GetCollectionAction extends AbstractOgBootController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(HttpClientInterface $httpClient): JsonResponse + public function __invoke(\App\Entity\BootServer $data): JsonResponse { - $content = $this->createRequest('GET', '/ogboot/v1/pxe-templates'); + $content = $this->createRequestFromBootServer($data, 'GET', '/ogboot/v1/pxe-templates'); if (isset($content['error']) && $content['error'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred: ' . $content['error']); diff --git a/src/Controller/OgBoot/PxeTemplate/PostAction.php b/src/Controller/OgBoot/PxeTemplate/PostAction.php index f22aece..069b8cf 100644 --- a/src/Controller/OgBoot/PxeTemplate/PostAction.php +++ b/src/Controller/OgBoot/PxeTemplate/PostAction.php @@ -35,10 +35,20 @@ class PostAction extends AbstractOgBootController ] ]; - $content = $this->createRequest('POST', '/ogboot/v1/pxe-templates' , $params); + $bootServer = $data->getBootServer(); + if (!$bootServer) { + throw new BadRequestHttpException('This PxeTemplate is not attached to any BootServer.'); + } - if (isset($content['error']) && $content['error'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { - throw new BadRequestHttpException('An error occurred: ' . $content['error']); + $this->logger->info(sprintf('Synchronizing PxeTemplate "%s" to BootServer "%s" at IP %s', $data->getName(), $bootServer->getName(), $bootServer->getIp())); + + $content = $this->createRequestFromBootServer($bootServer, 'POST', '/ogboot/v1/pxe-templates' , $params); + + if (isset($content['error']) ) { + $data->setSynchronized(false); + $this->entityManager->persist($data); + $this->entityManager->flush(); + throw new BadRequestHttpException('Sync failed: ' . ($content['message'] ?? $content['error'])); } $data->setSynchronized(true); diff --git a/src/Controller/OgBoot/PxeTemplate/SyncAction.php b/src/Controller/OgBoot/PxeTemplate/SyncAction.php index 489aaca..afe8724 100644 --- a/src/Controller/OgBoot/PxeTemplate/SyncAction.php +++ b/src/Controller/OgBoot/PxeTemplate/SyncAction.php @@ -27,9 +27,9 @@ class SyncAction extends AbstractOgBootController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function __invoke(): JsonResponse + public function __invoke(\App\Entity\BootServer $data): JsonResponse { - $content = $this->createRequest('GET', '/ogboot/v1/pxe-templates'); + $content = $this->createRequestFromBootServer($data, 'GET', '/ogboot/v1/pxe-templates'); $templateNamesFromApi = $content['message']; $existingTemplates = $this->entityManager->getRepository(PxeTemplate::class)->findAll(); @@ -37,20 +37,26 @@ class SyncAction extends AbstractOgBootController $existingTemplateNames = array_map(fn($t) => $t->getName(), $existingTemplates); foreach ($existingTemplates as $existingTemplate) { + // Only process Templates that belong to THIS boot server + if ($existingTemplate->getBootServer() !== $data) { + continue; + } + if (!in_array($existingTemplate->getName(), $templateNamesFromApi, true)) { $this->entityManager->remove($existingTemplate); } } foreach ($templateNamesFromApi as $templateName) { - $templateEntity = $this->entityManager->getRepository(PxeTemplate::class)->findOneBy(['name' => $templateName]); + $templateEntity = $this->entityManager->getRepository(PxeTemplate::class)->findOneBy(['name' => $templateName, 'bootServer' => $data]); if (!$templateEntity) { $templateEntity = new PxeTemplate(); $templateEntity->setName($templateName); + $templateEntity->setBootServer($data); } - $templateContent = $this->createRequest('GET', '/ogboot/v1/pxe-templates/' . $templateEntity->getName()); + $templateContent = $this->createRequestFromBootServer($data, 'GET', '/ogboot/v1/pxe-templates/' . $templateEntity->getName()); if (isset($templateContent['error']) && $templateContent['error'] === Response::HTTP_INTERNAL_SERVER_ERROR ) { throw new BadRequestHttpException('An error occurred: ' . $templateContent['error']); diff --git a/src/Controller/OgBoot/StatusAction.php b/src/Controller/OgBoot/StatusAction.php new file mode 100644 index 0000000..d020e02 --- /dev/null +++ b/src/Controller/OgBoot/StatusAction.php @@ -0,0 +1,34 @@ +createRequestFromBootServer($data,'GET', '/ogboot/v1/status'); + + if (isset($content['error'])) { + throw new BadRequestHttpException('An error occurred while fetching the status: ' . ($content['details'] ?? $content['message'] ?? 'Unknown error')); + } + + return new JsonResponse( data: $content, status: Response::HTTP_OK); + } +} diff --git a/src/Controller/PropagateNetworkSettingsAction.php b/src/Controller/PropagateNetworkSettingsAction.php index 7d1d103..1c5ab51 100644 --- a/src/Controller/PropagateNetworkSettingsAction.php +++ b/src/Controller/PropagateNetworkSettingsAction.php @@ -2,7 +2,10 @@ namespace App\Controller; +use App\Entity\Client; use App\Entity\OrganizationalUnit; +use App\Entity\PxeTemplate; +use App\Repository\ClientRepository; use App\Repository\OrganizationalUnitRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; @@ -15,6 +18,9 @@ class PropagateNetworkSettingsAction extends AbstractController public function __construct( private readonly OrganizationalUnitRepository $organizationalUnitRepository, private readonly EntityManagerInterface $entityManager, + private readonly \App\Controller\OgBoot\PxeBootFile\PostAction $postAction, + private readonly \App\Controller\OgDhcp\Subnet\PutHostAction $putHostAction, + private readonly ClientRepository $clientRepository, ) { } @@ -38,13 +44,35 @@ class PropagateNetworkSettingsAction extends AbstractController foreach ($organizationalUnit->getClients() as $client) { $client->setMenu($networkSettings->getMenu()); $client->setHardwareProfile($networkSettings->getHardwareProfile()); - $client->setOgLive($networkSettings->getOgLive()); $client->setRepository($networkSettings->getRepository()); + $client->setBootServer($networkSettings->getBootServer()); + $client->setOgLive($networkSettings->getOgLive()); $client->setTemplate($networkSettings->getPxeTemplate()); } $this->entityManager->flush(); + $clients = $this->clientRepository->findClientsByOrganizationalUnitAndDescendants($organizationalUnit->getId(), []); + + /** @var Client $client */ + foreach ($clients as $client) { + $template = $client->getTemplate() ? + $client->getTemplate() : + $client->getOrganizationalUnit()?->getNetworkSettings()?->getPxeTemplate(); + + if ($template === null) { + $template = $this->entityManager->getRepository(PxeTemplate::class)->findOneBy(['isDefault' => true]); + } + + if ($template !== null) { + $this->postAction->__invoke($client, $template); + } + + if ($client->getSubnet()) { + $this->putHostAction->__invoke($client->getMac(), $client); + } + } + return new JsonResponse( data: 'Network settings propagated successfully', status: Response::HTTP_OK diff --git a/src/Dto/Input/BootServerInput.php b/src/Dto/Input/BootServerInput.php new file mode 100644 index 0000000..b8de076 --- /dev/null +++ b/src/Dto/Input/BootServerInput.php @@ -0,0 +1,64 @@ +name = $bootServer->getName(); + $this->ip = $bootServer->getIp(); + $this->apiPort = $bootServer->getApiPort(); + $this->pxePort = $bootServer->getPxePort(); + $this->comments = $bootServer->getComments(); + } + + public function createOrUpdateEntity(?BootServer $bootServer = null): BootServer + { + if (!$bootServer) { + $bootServer = new BootServer(); + } + + $bootServer->setName($this->name); + $bootServer->setIp($this->ip); + $bootServer->setApiPort((int)$this->apiPort); + $bootServer->setPxePort((int)$this->pxePort); + $bootServer->setComments($this->comments); + + return $bootServer; + } +} diff --git a/src/Dto/Input/ClientInput.php b/src/Dto/Input/ClientInput.php index 12173b5..efa8e84 100644 --- a/src/Dto/Input/ClientInput.php +++ b/src/Dto/Input/ClientInput.php @@ -3,6 +3,7 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; +use App\Dto\Output\BootServerOutput; use App\Dto\Output\HardwareProfileOutput; use App\Dto\Output\ImageRepositoryOutput; use App\Dto\Output\MenuOutput; @@ -124,6 +125,12 @@ final class ClientInput )] public ?string $notes = null; + #[Groups(['client:write'])] + #[ApiProperty( + description: 'El servidor OgBoot del cliente' + )] + public ?string $bootServer = null; + public function __construct(?Client $client = null) { @@ -158,6 +165,10 @@ final class ClientInput if ($client->getRepository()) { $this->repository = new ImageRepositoryOutput($client->getRepository()); } + + if ($client->getBootServer()) { + $this->bootServer = '/boot-servers/' . $client->getBootServer()->getUuid(); + } } public function createOrUpdateEntity(?Client $client = null): Client diff --git a/src/Dto/Input/NetworkSettingsInput.php b/src/Dto/Input/NetworkSettingsInput.php index 161aa2e..a9d2e8b 100644 --- a/src/Dto/Input/NetworkSettingsInput.php +++ b/src/Dto/Input/NetworkSettingsInput.php @@ -3,6 +3,7 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; +use App\Dto\Output\BootServerOutput; use App\Dto\Output\HardwareProfileOutput; use App\Dto\Output\ImageRepositoryOutput; use App\Dto\Output\MenuOutput; @@ -160,6 +161,13 @@ class NetworkSettingsInput )] public ?string $ogshare = null; + #[Groups(['organizational-unit:write'])] + #[ApiProperty( + description: 'El servidor OgBoot de la configuración de red' + )] + public ?string $bootServer = null; + + public function __construct(?NetworkSettings $networkSettings = null) { if (!$networkSettings) { @@ -201,6 +209,10 @@ class NetworkSettingsInput if ($networkSettings->getPxeTemplate()) { $this->pxeTemplate = new PxeTemplateOutput($networkSettings->getPxeTemplate()); } + + if ($networkSettings->getBootServer()) { + $this->bootServer = '/boot-servers/' . $networkSettings->getBootServer()->getUuid(); + } } public function createOrUpdateEntity(?NetworkSettings $networkSettings = null): NetworkSettings @@ -227,22 +239,32 @@ class NetworkSettingsInput if ($this->menu) { $networkSettings->setMenu($this->menu->getEntity()); + } else { + $networkSettings->setMenu(null); } if ($this->hardwareProfile) { $networkSettings->setHardwareProfile($this->hardwareProfile->getEntity()); + } else { + $networkSettings->setHardwareProfile(null); } if ($this->ogLive) { $networkSettings->setOgLive($this->ogLive->getEntity()); + } else { + $networkSettings->setOgLive(null); } if ($this->repository) { $networkSettings->setRepository($this->repository->getEntity()); + } else { + $networkSettings->setRepository(null); } if ($this->pxeTemplate) { $networkSettings->setPxeTemplate($this->pxeTemplate->getEntity()); + } else { + $networkSettings->setPxeTemplate(null); } return $networkSettings; diff --git a/src/Dto/Input/PxeTemplateInput.php b/src/Dto/Input/PxeTemplateInput.php index e221edd..4a881a7 100644 --- a/src/Dto/Input/PxeTemplateInput.php +++ b/src/Dto/Input/PxeTemplateInput.php @@ -3,8 +3,8 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; +use App\Entity\BootServer; use App\Entity\PxeTemplate; -use App\Validator\Constraints\PxeTemplateUniqueDefault; use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Validator\Constraints as Assert; @@ -12,18 +12,26 @@ use Symfony\Component\Validator\Constraints as Assert; final class PxeTemplateInput { #[Assert\NotBlank(message: 'validators.pxe_template.name.not_blank')] + #[Assert\Regex( + pattern: '/^[a-zA-Z0-9._-]+$/', + message: 'El nombre solo puede contener letras, números, puntos, guiones y guiones bajos.' + )] #[Groups(['pxe-template:write'])] - #[ApiProperty(description: 'The name of the pxeTemplate', example: "PxeTemplate 1")] + #[ApiProperty(description: 'The name of the pxeTemplate', example: "Pxe_Template_1")] public ?string $name = null; #[Groups(['pxe-template:write'])] - #[ApiProperty(description: 'The content of the pxeTemplate', example: "content of the pxeTemplate 1")] + #[ApiProperty(description: 'The content of the pxeTemplate', example: "content of the Pxe_Template_1")] public ?string $templateContent = null; #[Groups(['pxe-template:write'])] #[ApiProperty(description: 'The default pxeTemplate', example: "true")] public ?bool $isDefault = null; + #[Groups(['pxe-template:write'])] + #[ApiProperty(description: 'The boot server which this template belongs to')] + public ?string $bootServer = null; + public function __construct(?PxeTemplate $pxeTemplate = null) { if (!$pxeTemplate) { @@ -33,6 +41,10 @@ final class PxeTemplateInput $this->name = $pxeTemplate->getName(); $this->templateContent = $pxeTemplate->getTemplateContent(); $this->isDefault = $pxeTemplate->isDefault(); + + if ($pxeTemplate->getBootServer()) { + $this->bootServer = '/boot-servers/' . $pxeTemplate->getBootServer()->getUuid(); + } } public function createOrUpdateEntity(?PxeTemplate $pxeTemplate = null): PxeTemplate diff --git a/src/Dto/Output/BootServerOutput.php b/src/Dto/Output/BootServerOutput.php new file mode 100644 index 0000000..d31e3ac --- /dev/null +++ b/src/Dto/Output/BootServerOutput.php @@ -0,0 +1,66 @@ +name = $bootServer->getName(); + $this->ip = $bootServer->getIp(); + $this->apiPort = $bootServer->getApiPort(); + $this->pxePort = $bootServer->getPxePort(); + $this->comments = $bootServer->getComments(); + $this->createdAt = $bootServer->getCreatedAt(); + $this->createdBy = $bootServer->getCreatedBy(); + } +} diff --git a/src/Dto/Output/ClientOutput.php b/src/Dto/Output/ClientOutput.php index 8be920c..6f81c9c 100644 --- a/src/Dto/Output/ClientOutput.php +++ b/src/Dto/Output/ClientOutput.php @@ -7,6 +7,7 @@ use ApiPlatform\Metadata\Get; use App\Entity\Client; use App\Entity\Partition; use Symfony\Component\Serializer\Annotation\Groups; +use App\Dto\Output\BootServerOutput; #[Get(shortName: 'Client')] final class ClientOutput extends AbstractOutput @@ -174,6 +175,13 @@ final class ClientOutput extends AbstractOutput )] public ?string $notes = null; + #[Groups(['client:read'])] + #[ApiProperty( + description: 'El servidor OgBoot asignado al cliente', + readableLink: true + )] + public ?BootServerOutput $bootServer = null; + public function __construct(Client $client) { parent::__construct($client); @@ -224,6 +232,10 @@ final class ClientOutput extends AbstractOutput $this->pxeSync = $client->isPxeSync(); $this->resolution = $client->getResolution(); $this->notes = $client->getNotes(); + + if ($client->getBootServer()) { + $this->bootServer = new BootServerOutput($client->getBootServer()); + } } public function convertMaskToCIDR($mask): int diff --git a/src/Dto/Output/NetworkSettingsOutput.php b/src/Dto/Output/NetworkSettingsOutput.php index e797034..28975f6 100644 --- a/src/Dto/Output/NetworkSettingsOutput.php +++ b/src/Dto/Output/NetworkSettingsOutput.php @@ -4,6 +4,7 @@ namespace App\Dto\Output; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\Get; +use App\Dto\Output\BootServerOutput; use App\Entity\NetworkSettings; use Symfony\Component\Serializer\Annotation\Groups; @@ -143,6 +144,13 @@ final class NetworkSettingsOutput extends AbstractOutput )] public ?PxeTemplateOutput $pxeTemplate = null; + #[Groups(['network-settings:read', "organizational-unit:read", "client:read"])] + #[ApiProperty( + description: 'El servidor OgBoot configurado', + example: null + )] + public ?BootServerOutput $bootServer = null; + #[Groups(['network-settings:read', "organizational-unit:read", "client:read"])] #[ApiProperty( description: 'La ruta compartida de OGAgent', @@ -204,6 +212,10 @@ final class NetworkSettingsOutput extends AbstractOutput $this->pxeTemplate = new PxeTemplateOutput($networkSettings->getPxeTemplate()); } + if ($networkSettings->getBootServer()) { + $this->bootServer = new BootServerOutput($networkSettings->getBootServer()); + } + $this->createdAt = $networkSettings->getCreatedAt(); $this->createdBy = $networkSettings->getCreatedBy(); } diff --git a/src/Dto/Output/PxeTemplateOutput.php b/src/Dto/Output/PxeTemplateOutput.php index 87c3578..26d9204 100644 --- a/src/Dto/Output/PxeTemplateOutput.php +++ b/src/Dto/Output/PxeTemplateOutput.php @@ -4,6 +4,7 @@ namespace App\Dto\Output; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\Get; +use App\Dto\Output\BootServerOutput; use App\Entity\Client; use App\Entity\PxeTemplate; use Symfony\Component\Serializer\Annotation\Groups; @@ -60,6 +61,12 @@ final class PxeTemplateOutput extends AbstractOutput )] public ?string $createdBy = null; + #[Groups(['pxe-template:read'])] + #[ApiProperty( + description: 'El servidor de arranque asociado', + )] + public ?BootServerOutput $bootServer = null; + public function __construct(PxeTemplate $pxeTemplate) { parent::__construct($pxeTemplate); @@ -71,5 +78,9 @@ final class PxeTemplateOutput extends AbstractOutput $this->isDefault = $pxeTemplate->isDefault(); $this->createdAt = $pxeTemplate->getCreatedAt(); $this->createdBy = $pxeTemplate->getCreatedBy(); + + if ($pxeTemplate->getBootServer()) { + $this->bootServer = new BootServerOutput($pxeTemplate->getBootServer()); + } } } \ No newline at end of file diff --git a/src/Entity/AbstractEntity.php b/src/Entity/AbstractEntity.php index 031fc7f..b4d7cba 100644 --- a/src/Entity/AbstractEntity.php +++ b/src/Entity/AbstractEntity.php @@ -8,6 +8,7 @@ use Gedmo\Timestampable\Traits\TimestampableEntity; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use Symfony\Bridge\Doctrine\Types\UuidType; +use Symfony\Component\Serializer\Annotation\Groups; #[ORM\MappedSuperclass] abstract class AbstractEntity @@ -18,9 +19,11 @@ abstract class AbstractEntity #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] + #[Groups(['boot-server:read', 'dhcp-server:read'])] protected ?int $id = null; #[ORM\Column(type: UuidType::NAME, unique: true)] + #[Groups(['boot-server:read', 'dhcp-server:read'])] protected UuidInterface $uuid; #[ORM\Column(length: 255, nullable: true)] diff --git a/src/Entity/BootServer.php b/src/Entity/BootServer.php new file mode 100644 index 0000000..9a43c11 --- /dev/null +++ b/src/Entity/BootServer.php @@ -0,0 +1,176 @@ + 8082])] + #[Groups(['boot-server:read', 'boot-server:write'])] + private int $apiPort = 8082; + + #[ORM\Column(type: 'integer', options: ['default' => 8082])] + #[Groups(['boot-server:read', 'boot-server:write'])] + private int $pxePort = 8082; + + #[ORM\Column(length: 255, nullable: true)] + #[Groups(['boot-server:read', 'boot-server:write'])] + private ?string $comments = null; + + /** + * @var Collection + */ + #[ORM\OneToMany(mappedBy: 'bootServer', targetEntity: OgLive::class, cascade: ['persist', 'remove'])] + private Collection $oglives; + + /** + * @var Collection + */ + #[ORM\OneToMany(mappedBy: 'bootServer', targetEntity: PxeTemplate::class, cascade: ['persist', 'remove'])] + private Collection $templates; + + public function __construct() + { + parent::__construct(); + $this->oglives = new ArrayCollection(); + $this->templates = new ArrayCollection(); + } + + public function getName(): ?string + { + return $this->name; + } + + public function setName(string $name): static + { + $this->name = $name; + + return $this; + } + + 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 getPxePort(): int + { + return $this->pxePort; + } + + public function setPxePort(int $pxePort): static + { + $this->pxePort = $pxePort; + + return $this; + } + + public function getComments(): ?string + { + return $this->comments; + } + + public function setComments(?string $comments): static + { + $this->comments = $comments; + + return $this; + } + + /** + * @return Collection + */ + public function getOglives(): Collection + { + return $this->oglives; + } + + public function addOglife(OgLive $oglife): static + { + if (!$this->oglives->contains($oglife)) { + $this->oglives->add($oglife); + $oglife->setBootServer($this); + } + + return $this; + } + + public function removeOglife(OgLive $oglife): static + { + if ($this->oglives->removeElement($oglife)) { + if ($oglife->getBootServer() === $this) { + $oglife->setBootServer(null); + } + } + + return $this; + } + + /** + * @return Collection + */ + public function getTemplates(): Collection + { + return $this->templates; + } + + public function addTemplate(PxeTemplate $template): static + { + if (!$this->templates->contains($template)) { + $this->templates->add($template); + $template->setBootServer($this); + } + + return $this; + } + + public function removeTemplate(PxeTemplate $template): static + { + if ($this->templates->removeElement($template)) { + if ($template->getBootServer() === $this) { + $template->setBootServer(null); + } + } + + return $this; + } +} diff --git a/src/Entity/Client.php b/src/Entity/Client.php index 79d9eaf..cccd45d 100644 --- a/src/Entity/Client.php +++ b/src/Entity/Client.php @@ -79,6 +79,10 @@ class Client extends AbstractEntity #[ORM\JoinColumn( onDelete: 'SET NULL')] private ?OgLive $ogLive = null; + #[ORM\ManyToOne] + #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')] + private ?BootServer $bootServer = null; + #[ORM\Column] private ?bool $maintenance = null; @@ -389,6 +393,18 @@ class Client extends AbstractEntity return $this; } + public function getBootServer(): ?BootServer + { + return $this->bootServer; + } + + public function setBootServer(?BootServer $bootServer): static + { + $this->bootServer = $bootServer; + + return $this; + } + public function getNotes(): ?string { return $this->notes; diff --git a/src/Entity/NetworkSettings.php b/src/Entity/NetworkSettings.php index 8267783..b338981 100644 --- a/src/Entity/NetworkSettings.php +++ b/src/Entity/NetworkSettings.php @@ -80,6 +80,10 @@ class NetworkSettings extends AbstractEntity #[ORM\ManyToOne] private ?PxeTemplate $pxeTemplate = null; + #[ORM\ManyToOne] + #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')] + private ?BootServer $bootServer = null; + public function __construct() { parent::__construct(); @@ -353,4 +357,16 @@ class NetworkSettings extends AbstractEntity return $this; } + + public function getBootServer(): ?BootServer + { + return $this->bootServer; + } + + public function setBootServer(?BootServer $bootServer): static + { + $this->bootServer = $bootServer; + + return $this; + } } diff --git a/src/Entity/OgLive.php b/src/Entity/OgLive.php index f6f5e3a..d6f8975 100644 --- a/src/Entity/OgLive.php +++ b/src/Entity/OgLive.php @@ -10,8 +10,8 @@ use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; #[ORM\Entity(repositoryClass: OgLiveRepository::class)] -#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_FILENAME', fields: ['filename'])] -#[UniqueEntity(fields: ['filename'], message: 'validators.og_live.filename.unique')] +#[ORM\UniqueConstraint(name: 'UNIQ_OGLIVE_FILENAME_SERVER', fields: ['filename', 'bootServer'])] +#[UniqueEntity(fields: ['filename', 'bootServer'], message: 'El fichero OgLive ya existe en este servidor')] class OgLive extends AbstractEntity { use NameableTrait; @@ -59,6 +59,10 @@ class OgLive extends AbstractEntity #[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)] private ?\DateTimeInterface $date = null; + #[ORM\ManyToOne(inversedBy: 'oglives')] + #[ORM\JoinColumn(nullable: true)] + private ?BootServer $bootServer = null; + public function __construct() { parent::__construct(); @@ -236,4 +240,16 @@ class OgLive extends AbstractEntity return $this; } + + public function getBootServer(): ?BootServer + { + return $this->bootServer; + } + + public function setBootServer(?BootServer $bootServer): static + { + $this->bootServer = $bootServer; + + return $this; + } } diff --git a/src/Entity/OrganizationalUnit.php b/src/Entity/OrganizationalUnit.php index 71f05ba..871a68c 100644 --- a/src/Entity/OrganizationalUnit.php +++ b/src/Entity/OrganizationalUnit.php @@ -341,8 +341,9 @@ class OrganizationalUnit extends AbstractEntity foreach ($this->getClients() as $client) { $client->setMenu($networkSettings->getMenu()); $client->setHardwareProfile($networkSettings->getHardwareProfile()); - $client->setOgLive($networkSettings->getOgLive()); $client->setRepository($networkSettings->getRepository()); + $client->setBootServer($networkSettings->getBootServer()); + $client->setOgLive($networkSettings->getOgLive()); $client->setTemplate($networkSettings->getPxeTemplate()); } diff --git a/src/Entity/PxeTemplate.php b/src/Entity/PxeTemplate.php index bfd9745..39efab4 100644 --- a/src/Entity/PxeTemplate.php +++ b/src/Entity/PxeTemplate.php @@ -10,8 +10,8 @@ use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; #[ORM\Entity(repositoryClass: PxeTemplateRepository::class)] -#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_NAME', fields: ['name'])] -#[UniqueEntity(fields: ['name'], message: 'validators.pxe_template.name.unique')] +#[ORM\UniqueConstraint(name: 'UNIQ_PXE_TEMPLATE_NAME_SERVER', fields: ['name', 'bootServer'])] +#[UniqueEntity(fields: ['name', 'bootServer'], message: 'La plantilla ya existe en este servidor')] class PxeTemplate extends AbstractEntity { use NameableTrait; @@ -29,6 +29,10 @@ class PxeTemplate extends AbstractEntity #[ORM\Column(nullable: true)] private ?bool $isDefault = null; + #[ORM\ManyToOne(inversedBy: 'templates')] + #[ORM\JoinColumn(nullable: true)] + private ?BootServer $bootServer = null; + public function __construct() { parent::__construct(); @@ -97,4 +101,16 @@ class PxeTemplate extends AbstractEntity return $this; } + + public function getBootServer(): ?BootServer + { + return $this->bootServer; + } + + public function setBootServer(?BootServer $bootServer): static + { + $this->bootServer = $bootServer; + + return $this; + } } diff --git a/src/EventSubscriber/OrganizationalUnitSubscriber.php b/src/EventSubscriber/OrganizationalUnitSubscriber.php index 60022ed..8441283 100644 --- a/src/EventSubscriber/OrganizationalUnitSubscriber.php +++ b/src/EventSubscriber/OrganizationalUnitSubscriber.php @@ -30,57 +30,6 @@ final readonly class OrganizationalUnitSubscriber implements EventSubscriberInte public static function getSubscribedEvents(): array { - return [ - KernelEvents::VIEW => ['updateNetworkSettings', EventPriorities::POST_WRITE], - ]; - } - - /** - * @throws TransportExceptionInterface - * @throws ServerExceptionInterface - * @throws RedirectionExceptionInterface - * @throws ClientExceptionInterface - */ - public function updateNetworkSettings(ViewEvent $event): void - { - $organizationalUnitOutput = $event->getControllerResult(); - $method = $event->getRequest()->getMethod(); - - if (!$organizationalUnitOutput instanceof OrganizationalUnitOutput || - !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH])) { - return; - } - - /** @var OrganizationalUnit $organizationalUnitEntity */ - $organizationalUnitEntity = $organizationalUnitOutput->getEntity(); - - if ($organizationalUnitEntity->getType() === OrganizationalUnitTypes::CLASSROOM) { - $this->syncOgBoot($organizationalUnitEntity); - } - } - - - /** - * @throws TransportExceptionInterface - * @throws ServerExceptionInterface - * @throws RedirectionExceptionInterface - * @throws ClientExceptionInterface - */ - private function syncOgBoot(OrganizationalUnit $organizationalUnitEntity): void - { - $clients = $this->entityManager->getRepository(Client::class)->findClientsByOrganizationalUnitAndDescendants($organizationalUnitEntity->getId(), []); - - if (empty($clients)) { - return; - } - - /** @var Client $client */ - foreach ($clients as $client) { - if ($client->getTemplate() === null) { - continue; - } - - $this->postAction->__invoke($client, $client->getTemplate()); - } + return []; } } \ No newline at end of file diff --git a/src/Repository/BootServerRepository.php b/src/Repository/BootServerRepository.php new file mode 100644 index 0000000..d53d556 --- /dev/null +++ b/src/Repository/BootServerRepository.php @@ -0,0 +1,23 @@ + + * + * @method BootServer|null find($id, $lockMode = null, $lockVersion = null) + * @method BootServer|null findOneBy(array $criteria, array $orderBy = null) + * @method BootServer[] findAll() + * @method BootServer[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + */ +class BootServerRepository extends AbstractRepository +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, BootServer::class); + } +} diff --git a/src/State/Processor/BootServerProcessor.php b/src/State/Processor/BootServerProcessor.php new file mode 100644 index 0000000..17cd93c --- /dev/null +++ b/src/State/Processor/BootServerProcessor.php @@ -0,0 +1,88 @@ +processDelete($uriVariables); + } + + return $this->processCreateOrUpdate($data, $operation, $uriVariables); + } + + /** + * @throws \Exception + */ + private function processCreateOrUpdate(mixed $data, Operation $operation, array $uriVariables): BootServerOutput + { + if (!($data instanceof BootServerInput)) { + throw new \Exception(sprintf('Data must be an instance of %s', BootServerInput::class)); + } + + $entity = null; + if (isset($uriVariables['uuid'])) { + $entity = $this->bootServerRepository->findOneBy(['uuid' => $uriVariables['uuid']]); + } + + $bootServer = $data->createOrUpdateEntity($entity); + $this->validator->validate($bootServer); + + $isNew = ($bootServer->getId() === null); + + $this->bootServerRepository->save($bootServer); + + // Automatic sync only on creation (POST) + if ($isNew && $operation instanceof Post) { + try { + $this->logger->info(sprintf('Automatic sync triggered for new BootServer: %s', $bootServer->getName())); + $this->pxeSyncAction->__invoke($bootServer); + $this->ogLiveSyncAction->__invoke($bootServer); + } catch (\Exception $e) { + $this->logger->error(sprintf('Automatic sync failed for BootServer %s: %s', $bootServer->getName(), $e->getMessage())); + // We don't want to fail the server creation if sync fails, + // but we might want to notify the user eventually. + } + } + + return new BootServerOutput($bootServer); + } + + private function processDelete(array $uriVariables): null + { + $bootServer = $this->bootServerRepository->findOneBy(['uuid' => $uriVariables['uuid']]); + if ($bootServer) { + $this->bootServerRepository->delete($bootServer); + } + + return null; + } +} diff --git a/src/State/Processor/ClientProcessor.php b/src/State/Processor/ClientProcessor.php index 2bcee18..a1879e3 100644 --- a/src/State/Processor/ClientProcessor.php +++ b/src/State/Processor/ClientProcessor.php @@ -14,6 +14,7 @@ use App\Controller\OgDhcp\Subnet\DeleteHostAction; use App\Dto\Input\ClientInput; use App\Dto\Output\ClientOutput; use App\Repository\ClientRepository; +use App\Repository\BootServerRepository; use App\Repository\MenuRepository; use App\Repository\OgLiveRepository; use App\Repository\PxeTemplateRepository; @@ -27,6 +28,7 @@ readonly class ClientProcessor implements ProcessorInterface { public function __construct( private ClientRepository $clientRepository, + private BootServerRepository $bootServerRepository, private MenuRepository $menuRepository, private PxeTemplateRepository $pxeTemplateRepository, private OgLiveRepository $ogLiveRepository, @@ -86,6 +88,17 @@ readonly class ClientProcessor implements ProcessorInterface $client->setOgLive($defaultPxeOgLive); } + if ($data->bootServer) { + $parts = explode('/', rtrim($data->bootServer, '/')); + $uuid = end($parts); + $bootServer = $this->bootServerRepository->findOneBy(['uuid' => $uuid]); + if ($bootServer) { + $client->setBootServer($bootServer); + } + } elseif ($client->getOrganizationalUnit() && $client->getOrganizationalUnit()->getNetworkSettings() && $client->getOrganizationalUnit()->getNetworkSettings()->getBootServer()) { + $client->setBootServer($client->getOrganizationalUnit()->getNetworkSettings()->getBootServer()); + } + $this->validator->validate($client); $this->clientRepository->save($client); diff --git a/src/State/Processor/OrganizationalUnitProcessor.php b/src/State/Processor/OrganizationalUnitProcessor.php index 794eee6..3a733e2 100644 --- a/src/State/Processor/OrganizationalUnitProcessor.php +++ b/src/State/Processor/OrganizationalUnitProcessor.php @@ -12,12 +12,14 @@ use ApiPlatform\Validator\ValidatorInterface; use App\Dto\Input\OrganizationalUnitInput; use App\Dto\Output\OrganizationalUnitOutput; use App\Repository\OrganizationalUnitRepository; +use App\Repository\BootServerRepository; use App\Service\ChangeClientNetworkSettingsService; readonly class OrganizationalUnitProcessor implements ProcessorInterface { public function __construct( private OrganizationalUnitRepository $organizationalUnitRepository, + private BootServerRepository $bootServerRepository, private ValidatorInterface $validator, private ChangeClientNetworkSettingsService $changeClientNetworkSettingsService, ) @@ -54,6 +56,16 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface } $organizationalUnit = $data->createOrUpdateEntity($entity); + + if ($data->networkSettings && $data->networkSettings->bootServer) { + $parts = explode('/', rtrim($data->networkSettings->bootServer, '/')); + $uuid = end($parts); + $bootServer = $this->bootServerRepository->findOneBy(['uuid' => $uuid]); + if ($bootServer) { + $organizationalUnit->getNetworkSettings()->setBootServer($bootServer); + } + } + $this->validator->validate($organizationalUnit, ['groups' => ['organizational-unit:write']]); $this->organizationalUnitRepository->save($organizationalUnit); diff --git a/src/State/Processor/PxeTemplateProcessor.php b/src/State/Processor/PxeTemplateProcessor.php index 96912a4..c27dc62 100644 --- a/src/State/Processor/PxeTemplateProcessor.php +++ b/src/State/Processor/PxeTemplateProcessor.php @@ -12,6 +12,7 @@ use ApiPlatform\Validator\ValidatorInterface; use App\Controller\OgBoot\PxeTemplate\PostAction; use App\Dto\Input\PxeTemplateInput; use App\Dto\Output\PxeTemplateOutput; +use App\Repository\BootServerRepository; use App\Repository\PxeTemplateRepository; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; @@ -19,6 +20,7 @@ readonly class PxeTemplateProcessor implements ProcessorInterface { public function __construct( private PxeTemplateRepository $pxeTemplateRepository, + private BootServerRepository $bootServerRepository, private ValidatorInterface $validator, private PostAction $postAction, ) @@ -56,6 +58,16 @@ readonly class PxeTemplateProcessor implements ProcessorInterface } $pxeTemplate = $data->createOrUpdateEntity($entity); + + if ($data->bootServer) { + $parts = explode('/', rtrim($data->bootServer, '/')); + $uuid = end($parts); + $bootServer = $this->bootServerRepository->findOneBy(['uuid' => $uuid]); + if ($bootServer) { + $pxeTemplate->setBootServer($bootServer); + } + } + $this->validator->validate($pxeTemplate); if (!$pxeTemplate->getId() ) { diff --git a/src/State/Provider/BootServerProvider.php b/src/State/Provider/BootServerProvider.php new file mode 100644 index 0000000..da6ca84 --- /dev/null +++ b/src/State/Provider/BootServerProvider.php @@ -0,0 +1,61 @@ +provideCollection($operation, $uriVariables, $context); + case $operation instanceof Patch: + case $operation instanceof Put: + return $this->provideItem($operation, $uriVariables, $context); + case $operation instanceof Get: + return $this->provideItem($operation, $uriVariables, $context); + } + + return null; + } + + 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 BootServerOutput($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('Boot Server not found'); + } + + return new BootServerOutput($item); + } +}