multiple-ogboot #92

Merged
jmbardallo merged 3 commits from multiple-ogboot into main 2026-04-23 14:15:57 +02:00
48 changed files with 1120 additions and 176 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,76 @@
<?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 Version20260420123904 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->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');
}
}

View File

@ -0,0 +1,37 @@
<?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 Version20260421091127 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->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)');
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,34 @@
<?php
namespace App\Controller\OgBoot;
use App\Entity\BootServer;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
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;
#[AsController]
class StatusAction extends AbstractOgBootController
{
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __invoke(BootServer $data): JsonResponse
{
$content = $this->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);
}
}

View File

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

View File

@ -0,0 +1,64 @@
<?php
namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Entity\BootServer;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
final class BootServerInput
{
#[Assert\NotBlank(message: 'El nombre es obligatorio')]
#[Groups(['boot-server:write'])]
#[ApiProperty(description: 'The name of the boot server', example: "Servidor Boot 1")]
public ?string $name = null;
#[Assert\NotBlank(message: 'La IP es obligatoria')]
#[Assert\Ip(message: 'La IP no es válida')]
#[Groups(['boot-server:write'])]
#[ApiProperty(description: 'The IP address of the boot server', example: "192.168.1.10")]
public ?string $ip = null;
#[Assert\NotBlank(message: 'El puerto API es obligatorio')]
#[Groups(['boot-server:write'])]
#[ApiProperty(description: 'The API port of the boot server', example: 8082)]
public ?int $apiPort = 8082;
#[Assert\NotBlank(message: 'El puerto PXE es obligatorio')]
#[Groups(['boot-server:write'])]
#[ApiProperty(description: 'The PXE port of the boot server', example: 8082)]
public ?int $pxePort = 8082;
#[Groups(['boot-server:write'])]
#[ApiProperty(description: 'Comments or description for the boot server', example: "Servidor principal")]
public ?string $comments = null;
public function __construct(?BootServer $bootServer = null)
{
if (!$bootServer) {
return;
}
$this->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;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,66 @@
<?php
namespace App\Dto\Output;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Get;
use App\Entity\BootServer;
use Symfony\Component\Serializer\Annotation\Groups;
#[Get(shortName: 'BootServer')]
class BootServerOutput extends AbstractOutput
{
#[Groups(['boot-server:read', 'client:read', 'organizational-unit:read'])]
#[ApiProperty(
description: 'El nombre del servidor OgBoot',
example: 'Servidor OgBoot Principal'
)]
public ?string $name = '';
#[Groups(['boot-server:read', 'client:read', 'organizational-unit:read'])]
#[ApiProperty(
description: 'La dirección IP del servidor OgBoot',
example: '192.168.1.50'
)]
public ?string $ip = '';
#[Groups(['boot-server:read'])]
#[ApiProperty(
description: 'Puerto de la API OgBoot',
example: 8082
)]
public ?int $apiPort = 8082;
#[Groups(['boot-server:read'])]
#[ApiProperty(
description: 'Puerto PXE del servidor OgBoot',
example: 8082
)]
public ?int $pxePort = 8082;
#[Groups(['boot-server:read'])]
#[ApiProperty(
description: 'Comentarios sobre el servidor',
example: 'Servidor principal de arranque'
)]
public ?string $comments = '';
#[Groups(['boot-server:read'])]
public \DateTime $createdAt;
#[Groups(['boot-server:read'])]
public ?string $createdBy = null;
public function __construct(BootServer $bootServer)
{
parent::__construct($bootServer);
$this->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();
}
}

View File

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

View File

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

View File

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

View File

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

176
src/Entity/BootServer.php Normal file
View File

@ -0,0 +1,176 @@
<?php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use App\Repository\BootServerRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups;
#[ORM\Entity(repositoryClass: BootServerRepository::class)]
#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_IP', fields: ['ip'])]
#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_NAME', fields: ['name'])]
#[UniqueEntity(fields: ['name'], message: 'There is already a boot server with this name')]
#[UniqueEntity(fields: ['ip'], message: 'There is already a boot server with this IP')]
class BootServer extends AbstractEntity
{
#[ORM\Column(length: 255)]
#[Groups(['boot-server:read', 'boot-server:write'])]
private ?string $name = null;
#[ORM\Column(length: 255)]
#[Groups(['boot-server:read', 'boot-server:write'])]
private ?string $ip = null;
#[ORM\Column(type: 'integer', options: ['default' => 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<int, OgLive>
*/
#[ORM\OneToMany(mappedBy: 'bootServer', targetEntity: OgLive::class, cascade: ['persist', 'remove'])]
private Collection $oglives;
/**
* @var Collection<int, PxeTemplate>
*/
#[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<int, OgLive>
*/
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<int, PxeTemplate>
*/
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;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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 [];
}
}

View File

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

View File

@ -0,0 +1,88 @@
<?php
namespace App\State\Processor;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Validator\ValidatorInterface;
use App\Controller\OgBoot\OgLive\SyncAction as OgLiveSyncAction;
use App\Controller\OgBoot\PxeTemplate\SyncAction as PxeSyncAction;
use App\Dto\Input\BootServerInput;
use App\Dto\Output\BootServerOutput;
use App\Repository\BootServerRepository;
use Psr\Log\LoggerInterface;
readonly class BootServerProcessor implements ProcessorInterface
{
public function __construct(
private BootServerRepository $bootServerRepository,
private ValidatorInterface $validator,
private PxeSyncAction $pxeSyncAction,
private OgLiveSyncAction $ogLiveSyncAction,
private LoggerInterface $logger
) {
}
/**
* @throws \Exception
*/
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
{
if ($operation instanceof Delete) {
return $this->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;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,61 @@
<?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\Output\BootServerOutput;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
readonly class BootServerProvider 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->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);
}
}