From 0acf27c0e1759e7d7c96a91ba4fd6dc897145331 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 7 Jul 2026 13:59:56 +0200 Subject: [PATCH 01/39] feat(user): add language preference field to user profile - Add language column (VARCHAR 10) to User entity - Add language field to UserInput and UserOutput DTOs - Expose language in JWT payload via JWTCreatedListener - Add Doctrine migration Version20260707091500 --- migrations/Version20260707091500.php | 29 ++++++++++++++++++++++++++++ src/Dto/Input/UserInput.php | 9 +++++++++ src/Dto/Output/UserOutput.php | 8 ++++++++ src/Entity/User.php | 15 ++++++++++++++ src/Lexik/JWTCreatedListener.php | 1 + 5 files changed, 62 insertions(+) create mode 100644 migrations/Version20260707091500.php diff --git a/migrations/Version20260707091500.php b/migrations/Version20260707091500.php new file mode 100644 index 0000000..501c1b0 --- /dev/null +++ b/migrations/Version20260707091500.php @@ -0,0 +1,29 @@ +addSql('ALTER TABLE `user` ADD language VARCHAR(10) DEFAULT NULL'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE `user` DROP COLUMN language'); + } +} diff --git a/src/Dto/Input/UserInput.php b/src/Dto/Input/UserInput.php index bb0e1d8..2cec38c 100644 --- a/src/Dto/Input/UserInput.php +++ b/src/Dto/Input/UserInput.php @@ -56,6 +56,13 @@ final class UserInput )] public ?int $clientsPerPage = null; + #[Groups('user:write')] + #[ApiProperty( + description: 'Idioma preferido del usuario', + example: 'es' + )] + public ?string $language = null; + #[Assert\NotNull] #[Groups('user:write')] #[ApiProperty( @@ -113,6 +120,7 @@ final class UserInput $this->enabled= $user->isEnabled(); $this->groupsView = $user->getGroupsView(); $this->clientsPerPage = $user->getClientsPerPage(); + $this->language = $user->getLanguage(); if ($user->getUserGroups()) { foreach ($user->getUserGroups() as $userGroup) { @@ -137,6 +145,7 @@ final class UserInput $user->setEnabled($this->enabled); $user->setGroupsView($this->groupsView); $user->setClientsPerPage($this->clientsPerPage); + $user->setLanguage($this->language); foreach ($this->userGroups as $userGroup) { $userGroupsToAdd[] = $userGroup->getEntity(); diff --git a/src/Dto/Output/UserOutput.php b/src/Dto/Output/UserOutput.php index bbdbb17..3345cc8 100644 --- a/src/Dto/Output/UserOutput.php +++ b/src/Dto/Output/UserOutput.php @@ -61,6 +61,13 @@ final class UserOutput extends AbstractOutput )] public ?int $clientsPerPage = null; + #[Groups(['user:read'])] + #[ApiProperty( + description: 'Idioma preferido del usuario', + example: 'es' + )] + public ?string $language = null; + #[Groups(['user:read'])] #[ApiProperty( description: 'Fecha de creación del usuario', @@ -84,6 +91,7 @@ final class UserOutput extends AbstractOutput $this->enabled = $user->isEnabled(); $this->groupsView = $user->getGroupsView(); $this->clientsPerPage = $user->getClientsPerPage(); + $this->language = $user->getLanguage(); $this->userGroups = $user->getUserGroups()->map( fn(UserGroup $userGroup) => new UserGroupOutput($userGroup) diff --git a/src/Entity/User.php b/src/Entity/User.php index cbbe295..b5eb059 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -57,6 +57,9 @@ class User extends AbstractEntity implements UserInterface, PasswordAuthenticate #[ORM\Column(nullable: true)] private ?int $clientsPerPage = null; + #[ORM\Column(length: 10, nullable: true)] + private ?string $language = null; + public function __construct() { @@ -275,4 +278,16 @@ class User extends AbstractEntity implements UserInterface, PasswordAuthenticate return $this; } + + public function getLanguage(): ?string + { + return $this->language; + } + + public function setLanguage(?string $language): static + { + $this->language = $language; + + return $this; + } } diff --git a/src/Lexik/JWTCreatedListener.php b/src/Lexik/JWTCreatedListener.php index d6f001b..4a804ee 100644 --- a/src/Lexik/JWTCreatedListener.php +++ b/src/Lexik/JWTCreatedListener.php @@ -25,6 +25,7 @@ class JWTCreatedListener $payload['roles'] = $user->getRoles(); $payload['groupsView'] = $user->getGroupsView(); $payload['clientsPerPage'] = $user->getClientsPerPage(); + $payload['language'] = $user->getLanguage(); $event->setData($payload); } -- 2.40.1 From 6b8cd0834b471b87a8f73aa9ea7a1cb7ce217ad8 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 9 Jul 2026 09:50:58 +0200 Subject: [PATCH 02/39] feat(organizational-unit): order children alphabetically by name --- src/Entity/OrganizationalUnit.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Entity/OrganizationalUnit.php b/src/Entity/OrganizationalUnit.php index 2178124..d2be019 100644 --- a/src/Entity/OrganizationalUnit.php +++ b/src/Entity/OrganizationalUnit.php @@ -45,6 +45,7 @@ class OrganizationalUnit extends AbstractEntity * @var Collection */ #[ORM\OneToMany(mappedBy: 'parent', targetEntity: self::class)] + #[ORM\OrderBy(['name' => 'ASC'])] private Collection $organizationalUnits; #[ORM\ManyToOne(targetEntity: NetworkSettings::class, inversedBy: 'organizationalUnits', cascade: ['persist'])] -- 2.40.1 From 92ee730bab067fa9445cb2aaac8fdeb5848f2eaf Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Tue, 7 Jul 2026 17:27:37 +0200 Subject: [PATCH 03/39] ref 2995. Actualizas roles. --- src/State/Processor/ClientProcessor.php | 1 + src/State/Processor/OrganizationalUnitProcessor.php | 1 + 2 files changed, 2 insertions(+) diff --git a/src/State/Processor/ClientProcessor.php b/src/State/Processor/ClientProcessor.php index 9a5bb2a..e7a63d9 100644 --- a/src/State/Processor/ClientProcessor.php +++ b/src/State/Processor/ClientProcessor.php @@ -71,6 +71,7 @@ readonly class ClientProcessor implements ProcessorInterface if ($currentUser instanceof User && !in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $currentUser->getRoles()) && !in_array(UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN, $currentUser->getRoles()) + && !in_array(UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR, $currentUser->getRoles()) ) { throw new AccessDeniedException('You are not allowed to create clients.'); } diff --git a/src/State/Processor/OrganizationalUnitProcessor.php b/src/State/Processor/OrganizationalUnitProcessor.php index c984b4f..5e175a9 100644 --- a/src/State/Processor/OrganizationalUnitProcessor.php +++ b/src/State/Processor/OrganizationalUnitProcessor.php @@ -58,6 +58,7 @@ readonly class OrganizationalUnitProcessor implements ProcessorInterface if ($user instanceof User) { if (!in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $user->getRoles()) && !in_array(UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_ADMIN, $user->getRoles()) + && !in_array(UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR, $user->getRoles()) ) { throw new AccessDeniedException('You are not allowed to create organizational units.'); } -- 2.40.1 From f00e5a12926b014421e37dda56187ccf1c3652d6 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Tue, 7 Jul 2026 17:29:00 +0200 Subject: [PATCH 04/39] ref 2975. Cambio de tipo en bbdd para que queda texto msa grande en los scripts. --- migrations/Version20260703000000.php | 26 ++++++++++++++++++++++++++ src/Entity/CommandTaskScript.php | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 migrations/Version20260703000000.php diff --git a/migrations/Version20260703000000.php b/migrations/Version20260703000000.php new file mode 100644 index 0000000..ab00205 --- /dev/null +++ b/migrations/Version20260703000000.php @@ -0,0 +1,26 @@ +addSql('ALTER TABLE command_task_script CHANGE content content LONGTEXT DEFAULT NULL'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE command_task_script CHANGE content content VARCHAR(255) DEFAULT NULL'); + } +} diff --git a/src/Entity/CommandTaskScript.php b/src/Entity/CommandTaskScript.php index 028e3c5..e8b9eca 100644 --- a/src/Entity/CommandTaskScript.php +++ b/src/Entity/CommandTaskScript.php @@ -9,7 +9,7 @@ use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: CommandTaskScriptRepository::class)] class CommandTaskScript extends AbstractEntity { - #[ORM\Column(length: 255, nullable: true)] + #[ORM\Column(type: Types::TEXT, nullable: true)] private ?string $content = null; #[ORM\Column] -- 2.40.1 From 1bf33e73d1eb15ac31a2a93871cd31c2d3b02bf4 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Tue, 7 Jul 2026 17:29:42 +0200 Subject: [PATCH 05/39] ref 2995. Actualizar roles. --- config/api_platform/Client.yaml | 2 +- config/api_platform/OrganizationalUnit.yaml | 2 +- config/packages/security.yaml | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/config/api_platform/Client.yaml b/config/api_platform/Client.yaml index f3cfc0d..35e9698 100644 --- a/config/api_platform/Client.yaml +++ b/config/api_platform/Client.yaml @@ -25,7 +25,7 @@ resources: validationContext: groups: [ 'client:patch' ] ApiPlatform\Metadata\Post: - security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN")' + security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_OPERATOR")' ApiPlatform\Metadata\Delete: ~ delete_multiple_clients: diff --git a/config/api_platform/OrganizationalUnit.yaml b/config/api_platform/OrganizationalUnit.yaml index 17e304b..f5668c1 100644 --- a/config/api_platform/OrganizationalUnit.yaml +++ b/config/api_platform/OrganizationalUnit.yaml @@ -27,7 +27,7 @@ resources: validationContext: groups: ['organizational-unit:patch' ] ApiPlatform\Metadata\Post: - security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN")' + security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_OPERATOR")' ApiPlatform\Metadata\Delete: security: 'is_granted("ROLE_SUPER_ADMIN") or (is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN") and object.getCreatedBy() == user.getUserIdentifier())' securityMessage: 'You can only delete organizational units you created.' diff --git a/config/packages/security.yaml b/config/packages/security.yaml index c0f8945..e3b317a 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -39,9 +39,9 @@ security: - { path: ^/validate, roles: PUBLIC_ACCESS } - { path: ^/menu-browser, roles: PUBLIC_ACCESS } - { path: ^/menu/, roles: PUBLIC_ACCESS } - # Creación de clientes y OUs: solo super-admin y ou-admin - - { path: ^/clients$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } - - { path: ^/organizational-units$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN] } + # Creación de clientes y OUs: super-admin, ou-admin y ou-operator + - { path: ^/clients$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN, ROLE_ORGANIZATIONAL_UNIT_OPERATOR] } + - { path: ^/organizational-units$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN, ROLE_ORGANIZATIONAL_UNIT_OPERATOR] } # ogLive puede consultar clientes por IP con su API key - { path: ^/clients, methods: [GET], roles: [ROLE_OGCLIENT_API, ROLE_USER] } - { path: ^/, roles: ROLE_USER } -- 2.40.1 From 83078445962f4c1e67075907839fbc4808a8aa64 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Tue, 7 Jul 2026 17:30:15 +0200 Subject: [PATCH 06/39] ref 2994. Propagacion con Hardware profile. --- src/Controller/PropagateNetworkSettingsAction.php | 6 +++++- src/Dto/Output/ClientOutput.php | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Controller/PropagateNetworkSettingsAction.php b/src/Controller/PropagateNetworkSettingsAction.php index 0a41156..aa94df5 100644 --- a/src/Controller/PropagateNetworkSettingsAction.php +++ b/src/Controller/PropagateNetworkSettingsAction.php @@ -43,7 +43,11 @@ class PropagateNetworkSettingsAction extends AbstractController foreach ($organizationalUnit->getClients() as $client) { $client->setMenu($networkSettings->getMenu()); - $client->setHardwareProfile($networkSettings->getHardwareProfile()); + // No se propaga hardwareProfile: Client::$hardwareProfile es un registro 1:1 + // propio de cada cliente (hardware_profile.client_id es NOT NULL), no una + // plantilla compartible como menu/repository/bootServer/ogLive/template. + // Esta llamada además tocaba el lado inverso de la relación de Doctrine y + // nunca llegaba a persistirse. $client->setRepository($networkSettings->getRepository()); $client->setBootServer($networkSettings->getBootServer()); $client->setOgLive($networkSettings->getOgLive()); diff --git a/src/Dto/Output/ClientOutput.php b/src/Dto/Output/ClientOutput.php index 0560e04..2391f60 100644 --- a/src/Dto/Output/ClientOutput.php +++ b/src/Dto/Output/ClientOutput.php @@ -8,6 +8,7 @@ use App\Entity\Client; use App\Entity\Partition; use Symfony\Component\Serializer\Annotation\Groups; use App\Dto\Output\BootServerOutput; +use App\Dto\Output\HardwareProfileOutput; #[Get(shortName: 'Client')] final class ClientOutput extends AbstractOutput @@ -91,6 +92,13 @@ final class ClientOutput extends AbstractOutput )] public ?MenuOutput $menu = null; + #[Groups(['client:read'])] + #[ApiProperty( + description: 'El perfil de hardware propio del cliente (registro 1:1, gestionado desde /hardware-profiles)', + example: null + )] + public ?HardwareProfileOutput $hardwareProfile = null; + #[Groups(['client:read'])] #[ApiProperty( description: 'El repositorio de imágenes asignado al cliente', @@ -210,6 +218,9 @@ final class ClientOutput extends AbstractOutput )->toArray(); $this->menu = $client->getMenu() ? new MenuOutput($client->getMenu()) : null; + $this->hardwareProfile = $client->getHardwareProfile() + ? new HardwareProfileOutput($client->getHardwareProfile(), includeClient: false) + : null; $this->position = $client->getPosition(); $repository = $client->getRepository() -- 2.40.1 From af2fa11d9bb399390c02eb6d70f69ea76c441f8b Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 9 Jul 2026 11:04:17 +0200 Subject: [PATCH 07/39] feat(deploy): remove constraint restricting deployment to clients with different partition sizes --- src/Dto/Input/DeployGitImageInput.php | 2 - src/Dto/Input/DeployImageInput.php | 2 - .../ClientsHaveSamePartitionSize.php | 23 ------ .../ClientsHaveSamePartitionSizeValidator.php | 76 ------------------- 4 files changed, 103 deletions(-) delete mode 100644 src/Validator/Constraints/ClientsHaveSamePartitionSize.php delete mode 100644 src/Validator/Constraints/ClientsHaveSamePartitionSizeValidator.php diff --git a/src/Dto/Input/DeployGitImageInput.php b/src/Dto/Input/DeployGitImageInput.php index 4a0c73e..8726a00 100644 --- a/src/Dto/Input/DeployGitImageInput.php +++ b/src/Dto/Input/DeployGitImageInput.php @@ -6,10 +6,8 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; use App\Dto\Output\ClientOutput; -use App\Validator\Constraints\ClientsHaveSamePartitionSize; use Symfony\Component\Serializer\Annotation\Groups; -#[ClientsHaveSamePartitionSize] class DeployGitImageInput { #[Groups(['git-repository:write'])] diff --git a/src/Dto/Input/DeployImageInput.php b/src/Dto/Input/DeployImageInput.php index 59762fd..26ae6b7 100644 --- a/src/Dto/Input/DeployImageInput.php +++ b/src/Dto/Input/DeployImageInput.php @@ -4,13 +4,11 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; use App\Dto\Output\ClientOutput; -use App\Validator\Constraints\ClientsHaveSamePartitionSize; use App\Validator\Constraints\OrganizationalUnitMulticastMode; use App\Validator\Constraints\OrganizationalUnitMulticastPort; use App\Validator\Constraints\OrganizationalUnitP2PMode; use Symfony\Component\Serializer\Annotation\Groups; -#[ClientsHaveSamePartitionSize] class DeployImageInput { #[Groups(['image-image-repository:write'])] diff --git a/src/Validator/Constraints/ClientsHaveSamePartitionSize.php b/src/Validator/Constraints/ClientsHaveSamePartitionSize.php deleted file mode 100644 index 64b5e19..0000000 --- a/src/Validator/Constraints/ClientsHaveSamePartitionSize.php +++ /dev/null @@ -1,23 +0,0 @@ -message = 'Todos los clientes deben tener el mismo tamaño de partición para la partición seleccionada.'; - } - - public function getTargets(): string - { - return self::CLASS_CONSTRAINT; - } -} \ No newline at end of file diff --git a/src/Validator/Constraints/ClientsHaveSamePartitionSizeValidator.php b/src/Validator/Constraints/ClientsHaveSamePartitionSizeValidator.php deleted file mode 100644 index a0c0264..0000000 --- a/src/Validator/Constraints/ClientsHaveSamePartitionSizeValidator.php +++ /dev/null @@ -1,76 +0,0 @@ -clients) || !is_array($value->clients) || empty($value->clients)) { - return; - } - - if ($value->diskNumber === null || $value->partitionNumber === null) { - return; - } - - $partitionSizes = []; - - foreach ($value->clients as $client) { - $clientEntity = $client->getEntity(); - - if (!$clientEntity instanceof Client) { - continue; - } - - $clientIp = (string) $clientEntity->getIp(); - - $targetPartition = null; - foreach ($clientEntity->getPartitions() as $partition) { - if ($partition->getDiskNumber() === $value->diskNumber && - $partition->getPartitionNumber() === $value->partitionNumber) { - $targetPartition = $partition; - break; - } - } - - if ($targetPartition === null) { - $partitionSizes[$clientIp] = null; - } else { - $partitionSizes[$clientIp] = $targetPartition->getSize(); - } - } - - $validSizes = array_filter($partitionSizes, fn($size) => $size !== null); - - if (count($validSizes) !== count($partitionSizes)) { - $clientsWithoutPartition = array_keys(array_filter($partitionSizes, fn($size) => $size === null)); - $this->context->buildViolation('Algunos clientes no tienen la partición seleccionada (Disco: ' . $value->diskNumber . ', Partición: ' . $value->partitionNumber . '). Clientes sin partición: ' . implode(', ', $clientsWithoutPartition)) - ->addViolation(); - return; - } - - if (count(array_unique($validSizes)) > 1) { - $errorDetails = []; - foreach ($partitionSizes as $clientIp => $partitionSize) { - $errorDetails[] = "Cliente $clientIp tiene tamaño $partitionSize KB."; - } - - $detailedMessage = implode(" ", $errorDetails); - - $this->context->buildViolation($constraint->message . ' Detalles: ' . $detailedMessage) - ->addViolation(); - } - } -} \ No newline at end of file -- 2.40.1 From ec48baebd37fb216380530e627e9da6726a1953e Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Mon, 13 Jul 2026 10:32:15 +0200 Subject: [PATCH 08/39] ref 3005. Fixed command scheldule bug. --- src/Controller/OgAgent/RunScriptAction.php | 42 ++++++---- tests/Functional/RunScriptQueueTest.php | 90 ++++++++++++++++++++++ 2 files changed, 118 insertions(+), 14 deletions(-) create mode 100644 tests/Functional/RunScriptQueueTest.php diff --git a/src/Controller/OgAgent/RunScriptAction.php b/src/Controller/OgAgent/RunScriptAction.php index b48917f..d38f5f3 100644 --- a/src/Controller/OgAgent/RunScriptAction.php +++ b/src/Controller/OgAgent/RunScriptAction.php @@ -38,7 +38,7 @@ class RunScriptAction extends AbstractOgAgentController } $data = $this->buildRequestData($client, $input->script, $input->runAsAdmin); - $response = $this->executeScript($client, $data); + $response = $this->executeScript($client, $data, $input); if (isset($response['code']) && $response['code'] === 409) { continue; @@ -86,7 +86,7 @@ class RunScriptAction extends AbstractOgAgentController return $client->getStatus() === ClientStatus::LINUX_SESSION || $client->getStatus() === ClientStatus::WINDOWS_SESSION; } - private function executeScript(Client $client, array $data): array + private function executeScript(Client $client, array $data, CommandExecuteInput $input): array { $response = $this->createRequest( method: 'POST', @@ -98,18 +98,32 @@ class RunScriptAction extends AbstractOgAgentController ); if (isset($response['code']) && $response['code'] === 409) { - $this->createService->__invoke( - $client, - CommandTypes::RUN_SCRIPT, - TraceStatus::BUSY, - null, - ['script' => $data['script'] ?? $data['scp'] ?? ''], - 'Some job is already running, refusing to launch another one' - ); - - $this->logger->info('Trace created as busy due to 409 response', [ - 'client_ip' => $client->getIp() - ]); + if ($input->queue) { + $this->createService->__invoke( + $client, + CommandTypes::RUN_SCRIPT, + TraceStatus::PENDING, + null, + ['script' => $input->script] + ); + + $this->logger->info('Trace queued (PENDING) due to 409 busy response', [ + 'client_ip' => $client->getIp() + ]); + } else { + $this->createService->__invoke( + $client, + CommandTypes::RUN_SCRIPT, + TraceStatus::BUSY, + null, + ['script' => $input->script], + 'Some job is already running, refusing to launch another one' + ); + + $this->logger->info('Trace created as busy due to 409 response', [ + 'client_ip' => $client->getIp() + ]); + } } return $response; diff --git a/tests/Functional/RunScriptQueueTest.php b/tests/Functional/RunScriptQueueTest.php new file mode 100644 index 0000000..747f77b --- /dev/null +++ b/tests/Functional/RunScriptQueueTest.php @@ -0,0 +1,90 @@ +get(EntityManagerInterface::class), + $httpClient, + $container->get(CreatePartitionService::class), + $container->get(LoggerInterface::class), + $container->get(CreateService::class), + $container->get(CreateRepositoryAction::class), + $container->get(SshKeyAction::class), + 'false', + ); + } + + public function testBusyClientWithQueueCreatesPendingTraceNotBusy(): void + { + /** @var Client $client */ + $client = ClientFactory::createOne(['ip' => '127.0.0.1', 'token' => 'fake-token'])->_real(); + + $mockHttpClient = new MockHttpClient(fn() => new MockResponse('{"message":"busy"}', ['http_code' => 409])); + + $input = new CommandExecuteInput(); + $input->clients = [new ClientOutput($client)]; + $input->script = 'echo hello'; + $input->queue = true; + + $this->buildRunScriptAction($mockHttpClient)->__invoke($input); + + $trace = static::getContainer()->get('doctrine')->getRepository(Trace::class) + ->findOneBy(['client' => $client, 'command' => CommandTypes::RUN_SCRIPT]); + + $this->assertNotNull($trace, 'Debe haberse creado una traza para el script'); + $this->assertSame(TraceStatus::PENDING, $trace->getStatus(), 'Con "encolar" marcado, la traza debe quedar PENDING (para que el reintento la recoja), no BUSY'); + } + + public function testBusyClientWithoutQueueCreatesBusyTrace(): void + { + /** @var Client $client */ + $client = ClientFactory::createOne(['ip' => '127.0.0.1', 'token' => 'fake-token'])->_real(); + + $mockHttpClient = new MockHttpClient(fn() => new MockResponse('{"message":"busy"}', ['http_code' => 409])); + + $input = new CommandExecuteInput(); + $input->clients = [new ClientOutput($client)]; + $input->script = 'echo hello'; + $input->queue = false; + + $this->buildRunScriptAction($mockHttpClient)->__invoke($input); + + $trace = static::getContainer()->get('doctrine')->getRepository(Trace::class) + ->findOneBy(['client' => $client, 'command' => CommandTypes::RUN_SCRIPT]); + + $this->assertNotNull($trace); + $this->assertSame(TraceStatus::BUSY, $trace->getStatus(), 'Sin "encolar", debe mantenerse el comportamiento previo (traza BUSY, sin reintento)'); + } +} -- 2.40.1 From 8b78296a86a26a8d9db7a35c5d99b71905d6b7c3 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Mon, 13 Jul 2026 10:36:01 +0200 Subject: [PATCH 09/39] ref 2994. Hardware profile network settings . --- config/services/api_platform.yaml | 2 +- migrations/Version20260710100654.php | 42 +++++++++++++++++ .../OgAgent/HardwareInventoryAction.php | 30 ++++++++----- .../PropagateNetworkSettingsAction.php | 6 +-- src/Dto/Input/ClientInput.php | 14 +++++- src/Dto/Input/HardwareProfileInput.php | 7 --- src/Dto/Output/HardwareProfileOutput.php | 15 ++++--- src/Entity/Client.php | 3 +- src/Entity/HardwareProfile.php | 34 +++++++++++--- src/Factory/HardwareProfileFactory.php | 1 - tests/Functional/ClientTest.php | 34 ++++++++++++++ tests/Functional/HardwareProfileTest.php | 41 +++++++++++++++-- tests/Functional/OrganizationalUnitTest.php | 45 +++++++++++++++++++ 13 files changed, 229 insertions(+), 45 deletions(-) create mode 100644 migrations/Version20260710100654.php diff --git a/config/services/api_platform.yaml b/config/services/api_platform.yaml index 2553ba1..771501b 100644 --- a/config/services/api_platform.yaml +++ b/config/services/api_platform.yaml @@ -142,7 +142,7 @@ services: api_platform.filter.hardware.search: parent: 'api_platform.doctrine.orm.search_filter' - arguments: [ { 'id': 'exact', 'name': 'partial' } ] + arguments: [ { 'id': 'exact', 'name': 'partial', 'clients.id': 'exact' } ] tags: [ 'api_platform.filter' ] api_platform.filter.menu.order: diff --git a/migrations/Version20260710100654.php b/migrations/Version20260710100654.php new file mode 100644 index 0000000..bc99704 --- /dev/null +++ b/migrations/Version20260710100654.php @@ -0,0 +1,42 @@ + HardwareProfile de OneToOne (perfil propio + * de cada cliente) a OneToMany (un perfil de hardware compartido por varios + * clientes de una misma aula), para permitir asignarlo y propagarlo desde + * la unidad organizativa. + */ +final class Version20260710100654 extends AbstractMigration +{ + public function getDescription(): string + { + return 'Client.hardwareProfile pasa a ser propietario de la relación (N clientes por perfil) en vez de HardwareProfile.client (1 cliente por perfil)'; + } + + public function up(Schema $schema): void + { + $this->addSql('ALTER TABLE client ADD hardware_profile_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE client ADD CONSTRAINT FK_C7440455CFA495C1 FOREIGN KEY (hardware_profile_id) REFERENCES hardware_profile (id) ON DELETE SET NULL'); + $this->addSql('CREATE INDEX IDX_C7440455CFA495C1 ON client (hardware_profile_id)'); + $this->addSql('ALTER TABLE hardware_profile DROP FOREIGN KEY FK_2D9A246019EB6921'); + $this->addSql('DROP INDEX IDX_2D9A246019EB6921 ON hardware_profile'); + $this->addSql('ALTER TABLE hardware_profile DROP client_id'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE hardware_profile ADD client_id INT NOT NULL'); + $this->addSql('ALTER TABLE hardware_profile ADD CONSTRAINT FK_2D9A246019EB6921 FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE CASCADE'); + $this->addSql('CREATE INDEX IDX_2D9A246019EB6921 ON hardware_profile (client_id)'); + $this->addSql('ALTER TABLE client DROP FOREIGN KEY FK_C7440455CFA495C1'); + $this->addSql('DROP INDEX IDX_C7440455CFA495C1 ON client'); + $this->addSql('ALTER TABLE client DROP hardware_profile_id'); + } +} diff --git a/src/Controller/OgAgent/HardwareInventoryAction.php b/src/Controller/OgAgent/HardwareInventoryAction.php index fb95c52..b8f5d39 100644 --- a/src/Controller/OgAgent/HardwareInventoryAction.php +++ b/src/Controller/OgAgent/HardwareInventoryAction.php @@ -167,20 +167,25 @@ class HardwareInventoryAction extends AbstractOgAgentController $hardwareProfile = $client->getHardwareProfile(); $isNewProfile = false; - + $isSharedProfile = $hardwareProfile !== null && $hardwareProfile->getClients()->count() > 1; + if (!$hardwareProfile) { $hardwareProfile = new HardwareProfile(); $hardwareProfile->setDescription('Perfil de hardware generado automáticamente para ' . $client->getIp()); - $hardwareProfile->setClient($client); $this->entityManager->persist($hardwareProfile); $isNewProfile = true; - + $this->logger->info('Nuevo perfil de hardware creado', [ 'client' => $client->getId(), 'client_ip' => $client->getIp() ]); - + $client->setHardwareProfile($hardwareProfile); + } elseif ($isSharedProfile) { + $this->logger->info('Perfil de hardware compartido con otros clientes del aula, no se sobrescribe con el inventario individual', [ + 'client' => $client->getId(), + 'profile_id' => $hardwareProfile->getId() + ]); } else { $this->logger->info('Actualizando perfil de hardware existente', [ 'client' => $client->getId(), @@ -188,16 +193,17 @@ class HardwareInventoryAction extends AbstractOgAgentController ]); } - foreach ($hardwareItems as $hardware) { - $hardwareProfile->addHardwareCollection($hardware); + if (!$isSharedProfile) { + foreach ($hardwareItems as $hardware) { + $hardwareProfile->addHardwareCollection($hardware); + } + + $this->logger->debug('Nuevo hardware añadido al perfil', [ + 'client' => $client->getId(), + 'added_hardware_count' => count($hardwareItems) + ]); } - $this->logger->debug('Nuevo hardware añadido al perfil', [ - 'client' => $client->getId(), - 'added_hardware_count' => count($hardwareItems) - ]); - - $client->setHardwareProfile($hardwareProfile); $this->entityManager->persist($client); $this->entityManager->flush(); diff --git a/src/Controller/PropagateNetworkSettingsAction.php b/src/Controller/PropagateNetworkSettingsAction.php index aa94df5..0a41156 100644 --- a/src/Controller/PropagateNetworkSettingsAction.php +++ b/src/Controller/PropagateNetworkSettingsAction.php @@ -43,11 +43,7 @@ class PropagateNetworkSettingsAction extends AbstractController foreach ($organizationalUnit->getClients() as $client) { $client->setMenu($networkSettings->getMenu()); - // No se propaga hardwareProfile: Client::$hardwareProfile es un registro 1:1 - // propio de cada cliente (hardware_profile.client_id es NOT NULL), no una - // plantilla compartible como menu/repository/bootServer/ogLive/template. - // Esta llamada además tocaba el lado inverso de la relación de Doctrine y - // nunca llegaba a persistirse. + $client->setHardwareProfile($networkSettings->getHardwareProfile()); $client->setRepository($networkSettings->getRepository()); $client->setBootServer($networkSettings->getBootServer()); $client->setOgLive($networkSettings->getOgLive()); diff --git a/src/Dto/Input/ClientInput.php b/src/Dto/Input/ClientInput.php index efa8e84..317a244 100644 --- a/src/Dto/Input/ClientInput.php +++ b/src/Dto/Input/ClientInput.php @@ -86,7 +86,13 @@ final class ClientInput #[ApiProperty( description: 'La plantilla PXE del cliente' )] - public ?PxeTemplateOutput $pxeTemplate = null; + public ?PxeTemplateOutput $pxeTemplate = null; + + #[Groups(['client:write'])] + #[ApiProperty( + description: 'El perfil de hardware del cliente' + )] + public ?HardwareProfileOutput $hardwareProfile = null; #[Groups(['client:write'])] #[ApiProperty( @@ -162,6 +168,10 @@ final class ClientInput $this->pxeTemplate = new PxeTemplateOutput($client->getTemplate()); } + if ($client->getHardwareProfile()) { + $this->hardwareProfile = new HardwareProfileOutput($client->getHardwareProfile(), includeClients: false); + } + if ($client->getRepository()) { $this->repository = new ImageRepositoryOutput($client->getRepository()); } @@ -179,6 +189,7 @@ final class ClientInput $menu = $this->menu?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getMenu(); $ogLive = $this->ogLive?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getOgLive(); + $hardwareProfile = $this->hardwareProfile?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getHardwareProfile(); $repository = $this->repository?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getRepository(); $template = $this->pxeTemplate?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getPxeTemplate(); @@ -191,6 +202,7 @@ final class ClientInput $client->setIp($this->ip); $client->setMenu($menu); $client->setOgLive($ogLive); + $client->setHardwareProfile($hardwareProfile); $client->setRepository($repository); $client->setTemplate($template); $client->setPosition($this->position); diff --git a/src/Dto/Input/HardwareProfileInput.php b/src/Dto/Input/HardwareProfileInput.php index c162328..64aacdd 100644 --- a/src/Dto/Input/HardwareProfileInput.php +++ b/src/Dto/Input/HardwareProfileInput.php @@ -5,7 +5,6 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; use App\Entity\HardwareProfile; use Symfony\Component\Serializer\Annotation\Groups; -use App\Dto\Output\ClientOutput; final class HardwareProfileInput { @@ -17,10 +16,6 @@ final class HardwareProfileInput #[ApiProperty(description: 'Comments of the hardware profile', example: "Hardware 1")] public ?string $comments = null; - #[Groups(['hardware-profile:write'])] - #[ApiProperty(description: 'The client of the hardware profile', readableLink: true)] - public ?ClientOutput $client = null; - public function __construct(?HardwareProfile $hardwareProfile = null) { if (!$hardwareProfile) { @@ -29,7 +24,6 @@ final class HardwareProfileInput $this->description = $hardwareProfile->getDescription(); $this->comments = $hardwareProfile->getComments(); - $this->client = new ClientOutput($hardwareProfile->getClient()); } public function createOrUpdateEntity(?HardwareProfile $hardwareProfile = null): HardwareProfile @@ -40,7 +34,6 @@ final class HardwareProfileInput $hardwareProfile->setDescription($this->description); $hardwareProfile->setComments($this->comments); - $hardwareProfile->setClient($this->client->getEntity()); return $hardwareProfile; } diff --git a/src/Dto/Output/HardwareProfileOutput.php b/src/Dto/Output/HardwareProfileOutput.php index 980d2e4..b67586e 100644 --- a/src/Dto/Output/HardwareProfileOutput.php +++ b/src/Dto/Output/HardwareProfileOutput.php @@ -4,6 +4,7 @@ namespace App\Dto\Output; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\Get; +use App\Entity\Client; use App\Entity\Hardware; use App\Entity\HardwareProfile; use Symfony\Component\Serializer\Annotation\Groups; @@ -27,10 +28,10 @@ final class HardwareProfileOutput extends AbstractOutput #[Groups(['hardware-profile:read'])] #[ApiProperty( - description: 'El cliente asociado a este perfil de hardware', - example: null + description: 'Los clientes que tienen asignado este perfil de hardware', + example: [] )] - public ?ClientOutput $client = null; + public array $clients = []; #[Groups(['hardware-profile:read'])] #[ApiProperty( @@ -53,14 +54,16 @@ final class HardwareProfileOutput extends AbstractOutput )] public ?string $createdBy = null; - public function __construct(HardwareProfile $hardwareProfile, bool $includeClient = true) + public function __construct(HardwareProfile $hardwareProfile, bool $includeClients = true) { parent::__construct($hardwareProfile); $this->description = $hardwareProfile->getDescription(); $this->comments = $hardwareProfile->getComments(); - if($includeClient && $hardwareProfile->getClient()) { - $this->client = new ClientOutput($hardwareProfile->getClient()); + if ($includeClients) { + $this->clients = $hardwareProfile->getClients()->map( + fn(Client $client) => new ClientOutput($client) + )->toArray(); } $this->hardwareCollection = $hardwareProfile->getHardwareCollection()->map( diff --git a/src/Entity/Client.php b/src/Entity/Client.php index 6636720..4f039ab 100644 --- a/src/Entity/Client.php +++ b/src/Entity/Client.php @@ -54,7 +54,8 @@ class Client extends AbstractEntity #[ORM\JoinColumn( onDelete: 'SET NULL')] private ?Menu $menu = null; - #[ORM\OneToOne(mappedBy: 'client', cascade: ['persist', 'remove'])] + #[ORM\ManyToOne(inversedBy: 'clients')] + #[ORM\JoinColumn(onDelete: 'SET NULL')] private ?HardwareProfile $hardwareProfile = null; #[ORM\Column(nullable: true)] diff --git a/src/Entity/HardwareProfile.php b/src/Entity/HardwareProfile.php index 533ff9b..cb40344 100644 --- a/src/Entity/HardwareProfile.php +++ b/src/Entity/HardwareProfile.php @@ -16,9 +16,11 @@ class HardwareProfile extends AbstractEntity #[ORM\Column(length: 255, nullable: true)] private ?string $comments = null; - #[ORM\ManyToOne(targetEntity: Client::class, inversedBy: 'hardwareProfile')] - #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] - private ?Client $client = null; + /** + * @var Collection + */ + #[ORM\OneToMany(mappedBy: 'hardwareProfile', targetEntity: Client::class)] + private Collection $clients; /** * @var Collection @@ -30,6 +32,7 @@ class HardwareProfile extends AbstractEntity { parent::__construct(); + $this->clients = new ArrayCollection(); $this->hardwareCollection = new ArrayCollection(); } @@ -62,14 +65,31 @@ class HardwareProfile extends AbstractEntity return $this; } - public function getClient(): ?Client + /** + * @return Collection + */ + public function getClients(): Collection { - return $this->client; + return $this->clients; } - public function setClient(?Client $client): static + public function addClient(Client $client): static { - $this->client = $client; + if (!$this->clients->contains($client)) { + $this->clients->add($client); + $client->setHardwareProfile($this); + } + + return $this; + } + + public function removeClient(Client $client): static + { + if ($this->clients->removeElement($client)) { + if ($client->getHardwareProfile() === $this) { + $client->setHardwareProfile(null); + } + } return $this; } diff --git a/src/Factory/HardwareProfileFactory.php b/src/Factory/HardwareProfileFactory.php index 13021dc..6d514c9 100644 --- a/src/Factory/HardwareProfileFactory.php +++ b/src/Factory/HardwareProfileFactory.php @@ -38,7 +38,6 @@ final class HardwareProfileFactory extends ModelFactory 'createdAt' => self::faker()->dateTime(), 'updatedAt' => self::faker()->dateTime(), 'description' => self::faker()->text(255), - 'client' => ClientFactory::new(), ]; } diff --git a/tests/Functional/ClientTest.php b/tests/Functional/ClientTest.php index 20efdda..4845bed 100644 --- a/tests/Functional/ClientTest.php +++ b/tests/Functional/ClientTest.php @@ -3,8 +3,10 @@ namespace Functional; use App\Entity\Client; +use App\Entity\HardwareProfile; use App\Entity\OrganizationalUnit; use App\Factory\ClientFactory; +use App\Factory\HardwareProfileFactory; use App\Factory\OrganizationalUnitFactory; use App\Factory\UserFactory; use App\Model\OrganizationalUnitTypes; @@ -108,6 +110,38 @@ class ClientTest extends AbstractTest ]); } + /** + * Verifica que el perfil de hardware de un cliente concreto puede + * modificarse directamente desde su ficha (PATCH), no solo desde el aula. + * + * @throws RedirectionExceptionInterface + * @throws DecodingExceptionInterface + * @throws ClientExceptionInterface + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + */ + public function testPatchClientHardwareProfile(): void + { + UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + $ou = OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); + ClientFactory::createOne(['name' => 'test-client-own-hw-profile', 'organizationalUnit' => $ou]); + HardwareProfileFactory::createOne(['description' => 'test-client-own-hw-profile-description']); + + $clientIri = $this->findIriBy(Client::class, ['name' => 'test-client-own-hw-profile']); + $hardwareProfileIri = $this->findIriBy(HardwareProfile::class, ['description' => 'test-client-own-hw-profile-description']); + + $this->createClientWithCredentials()->request('PATCH', $clientIri, ['json' => [ + 'hardwareProfile' => $hardwareProfileIri, + ]]); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains([ + '@id' => $clientIri, + 'hardwareProfile' => ['@id' => $hardwareProfileIri], + ]); + } + /** * @throws TransportExceptionInterface * @throws ServerExceptionInterface diff --git a/tests/Functional/HardwareProfileTest.php b/tests/Functional/HardwareProfileTest.php index c4833aa..d014775 100644 --- a/tests/Functional/HardwareProfileTest.php +++ b/tests/Functional/HardwareProfileTest.php @@ -5,9 +5,12 @@ namespace Functional; use App\Entity\Client; use App\Entity\HardwareProfile; +use App\Entity\OrganizationalUnit; use App\Factory\ClientFactory; use App\Factory\HardwareProfileFactory; +use App\Factory\OrganizationalUnitFactory; use App\Factory\UserFactory; +use App\Model\OrganizationalUnitTypes; use App\Model\UserGroupPermissions; use Symfony\Component\HttpFoundation\Response; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; @@ -58,12 +61,8 @@ class HardwareProfileTest extends AbstractTest { UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); - ClientFactory::createOne(['name' => 'test-client']); - $clientIri = $this->findIriBy(Client::class, ['name' => 'test-client']); - $this->createClientWithCredentials()->request('POST', '/hardware-profiles',['json' => [ 'description' => self::HW_PROFILE_CREATE, - 'client' => $clientIri ]]); $this->assertResponseStatusCodeSame(201); @@ -100,6 +99,40 @@ class HardwareProfileTest extends AbstractTest ]); } + /** + * @throws RedirectionExceptionInterface + * @throws DecodingExceptionInterface + * @throws ClientExceptionInterface + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + */ + public function testHardwareProfileSharedByMultipleClients(): void + { + UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + $ou = OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); + ClientFactory::createOne(['name' => 'test-client-a', 'organizationalUnit' => $ou]); + ClientFactory::createOne(['name' => 'test-client-b', 'organizationalUnit' => $ou]); + HardwareProfileFactory::createOne(['description' => self::HW_PROFILE_CREATE]); + + $clientAIri = $this->findIriBy(Client::class, ['name' => 'test-client-a']); + $clientBIri = $this->findIriBy(Client::class, ['name' => 'test-client-b']); + $hardwareProfileIri = $this->findIriBy(HardwareProfile::class, ['description' => self::HW_PROFILE_CREATE]); + + $client = $this->createClientWithCredentials(); + + $client->request('PUT', $clientAIri, ['json' => ['name' => 'test-client-a', 'hardwareProfile' => $hardwareProfileIri]]); + $this->assertResponseIsSuccessful(); + + $client->request('PUT', $clientBIri, ['json' => ['name' => 'test-client-b', 'hardwareProfile' => $hardwareProfileIri]]); + $this->assertResponseIsSuccessful(); + + $client->request('GET', $hardwareProfileIri); + $this->assertResponseIsSuccessful(); + $data = $client->getResponse()->toArray(); + $this->assertCount(2, $data['clients']); + } + /** * @throws TransportExceptionInterface * @throws ServerExceptionInterface diff --git a/tests/Functional/OrganizationalUnitTest.php b/tests/Functional/OrganizationalUnitTest.php index c965947..f98dedc 100644 --- a/tests/Functional/OrganizationalUnitTest.php +++ b/tests/Functional/OrganizationalUnitTest.php @@ -2,8 +2,12 @@ namespace Functional; +use App\Entity\Client; +use App\Entity\HardwareProfile; use App\Entity\OrganizationalUnit; use App\Entity\UserGroup; +use App\Factory\ClientFactory; +use App\Factory\HardwareProfileFactory; use App\Factory\OrganizationalUnitFactory; use App\Factory\UserFactory; use App\Model\OrganizationalUnitTypes; @@ -179,4 +183,45 @@ class OrganizationalUnitTest extends AbstractTest static::getContainer()->get('doctrine')->getRepository(UserGroup::class)->findOneBy(['name' => self::ORGANIZATIONAL_UNIT_DELETE]) ); } + + /** + * Verifica que el perfil de hardware asignado en el aula se propaga a todos + * los clientes que tiene por debajo, y que ese perfil queda compartido. + * + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + * @throws RedirectionExceptionInterface + * @throws DecodingExceptionInterface + * @throws ClientExceptionInterface + */ + public function testPropagateHardwareProfileFromOrganizationalUnitToClients(): void + { + UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + $ou = OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); + ClientFactory::createOne(['name' => 'test-propagate-client-a', 'organizationalUnit' => $ou]); + ClientFactory::createOne(['name' => 'test-propagate-client-b', 'organizationalUnit' => $ou]); + HardwareProfileFactory::createOne(['description' => 'test-propagate-hw-profile']); + + $ouIri = $this->findIriBy(OrganizationalUnit::class, ['id' => $ou->getId()]); + $hardwareProfileIri = $this->findIriBy(HardwareProfile::class, ['description' => 'test-propagate-hw-profile']); + $clientAIri = $this->findIriBy(Client::class, ['name' => 'test-propagate-client-a']); + $clientBIri = $this->findIriBy(Client::class, ['name' => 'test-propagate-client-b']); + + $client = $this->createClientWithCredentials(); + + $client->request('PUT', $ouIri, ['json' => [ + 'networkSettings' => ['hardwareProfile' => $hardwareProfileIri], + ]]); + $this->assertResponseIsSuccessful(); + + $client->request('POST', $ouIri . '/propagate-network-settings'); + $this->assertResponseIsSuccessful(); + + $client->request('GET', $clientAIri); + $this->assertJsonContains(['hardwareProfile' => ['@id' => $hardwareProfileIri]]); + + $client->request('GET', $clientBIri); + $this->assertJsonContains(['hardwareProfile' => ['@id' => $hardwareProfileIri]]); + } } \ No newline at end of file -- 2.40.1 From 3390734b100caf19ada5ea4482688cc68c368e82 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Mon, 13 Jul 2026 10:38:22 +0200 Subject: [PATCH 10/39] ref 3007. Updated software profile image entity. --- migrations/Version20260710114751.php | 41 +++++++++ src/Dto/Input/ImageImageRepositoryInput.php | 10 +++ src/Dto/Input/ImageInput.php | 13 --- src/Dto/Output/ClientOutput.php | 4 +- src/Dto/Output/ImageImageRepositoryOutput.php | 11 +++ src/Dto/Output/ImageOutput.php | 8 -- src/Dto/Output/SoftwareProfileOutput.php | 2 +- src/Entity/Image.php | 16 ---- src/Entity/ImageImageRepository.php | 16 ++++ src/Factory/ImageFactory.php | 1 - src/Factory/SoftwareProfileFactory.php | 2 - ...CreateSoftwareProfileFromInventoryTest.php | 86 +++++++++++++++++++ tests/Functional/SoftwareProfileTest.php | 54 ++++++++++-- 13 files changed, 214 insertions(+), 50 deletions(-) create mode 100644 migrations/Version20260710114751.php create mode 100644 tests/Functional/CreateSoftwareProfileFromInventoryTest.php diff --git a/migrations/Version20260710114751.php b/migrations/Version20260710114751.php new file mode 100644 index 0000000..09b7a50 --- /dev/null +++ b/migrations/Version20260710114751.php @@ -0,0 +1,41 @@ +addSql('ALTER TABLE image DROP FOREIGN KEY FK_C53D045FED42A742'); + $this->addSql('DROP INDEX IDX_C53D045FED42A742 ON image'); + $this->addSql('ALTER TABLE image DROP software_profile_id'); + $this->addSql('ALTER TABLE image_image_repository ADD software_profile_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE image_image_repository ADD CONSTRAINT FK_B7851337ED42A742 FOREIGN KEY (software_profile_id) REFERENCES software_profile (id)'); + $this->addSql('CREATE INDEX IDX_B7851337ED42A742 ON image_image_repository (software_profile_id)'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE image_image_repository DROP FOREIGN KEY FK_B7851337ED42A742'); + $this->addSql('DROP INDEX IDX_B7851337ED42A742 ON image_image_repository'); + $this->addSql('ALTER TABLE image_image_repository DROP software_profile_id'); + $this->addSql('ALTER TABLE image ADD software_profile_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE image ADD CONSTRAINT FK_C53D045FED42A742 FOREIGN KEY (software_profile_id) REFERENCES software_profile (id)'); + $this->addSql('CREATE INDEX IDX_C53D045FED42A742 ON image (software_profile_id)'); + } +} diff --git a/src/Dto/Input/ImageImageRepositoryInput.php b/src/Dto/Input/ImageImageRepositoryInput.php index 80303e1..ff8f0b0 100644 --- a/src/Dto/Input/ImageImageRepositoryInput.php +++ b/src/Dto/Input/ImageImageRepositoryInput.php @@ -5,6 +5,7 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; use App\Dto\Output\ImageOutput; use App\Dto\Output\ImageRepositoryOutput; +use App\Dto\Output\SoftwareProfileOutput; use App\Entity\ImageImageRepository; use App\Entity\PxeTemplate; use Symfony\Component\Serializer\Annotation\Groups; @@ -19,6 +20,10 @@ final class ImageImageRepositoryInput #[ApiProperty(description: 'Whether this image is available for Remote PC in this repository', example: false)] public ?bool $remotePc = false; + #[Groups(['image-image-repository:write'])] + #[ApiProperty(description: 'El perfil de software detectado en esta versión de la imagen')] + public ?SoftwareProfileOutput $softwareProfile = null; + public function __construct(?ImageImageRepository $imageImageRepository = null) { if (!$imageImageRepository) { @@ -27,6 +32,10 @@ final class ImageImageRepositoryInput $this->description = $imageImageRepository->getDescription(); $this->remotePc = $imageImageRepository->isRemotePc(); + + if ($imageImageRepository->getSoftwareProfile()) { + $this->softwareProfile = new SoftwareProfileOutput($imageImageRepository->getSoftwareProfile(), false); + } } public function createOrUpdateEntity(?ImageImageRepository $imageImageRepository = null): ImageImageRepository @@ -37,6 +46,7 @@ final class ImageImageRepositoryInput $imageImageRepository->setDescription($this->description); $imageImageRepository->setRemotePc($this->remotePc); + $imageImageRepository->setSoftwareProfile($this->softwareProfile?->getEntity()); return $imageImageRepository; } diff --git a/src/Dto/Input/ImageInput.php b/src/Dto/Input/ImageInput.php index b611f4b..e2807cf 100644 --- a/src/Dto/Input/ImageInput.php +++ b/src/Dto/Input/ImageInput.php @@ -10,7 +10,6 @@ use App\Dto\Output\ImageRepositoryOutput; use App\Dto\Output\OrganizationalUnitOutput; use App\Dto\Output\PartitionOutput; use App\Dto\Output\RemoteCalendarRuleOutput; -use App\Dto\Output\SoftwareProfileOutput; use App\Entity\Image; use App\Entity\ImageImageRepository; use App\Entity\OrganizationalUnit; @@ -33,10 +32,6 @@ final class ImageInput #[ApiProperty(description: 'The optional selected image')] public ?ImageOutput $selectedImage = null; - #[Groups(['image:write'])] - #[ApiProperty(description: 'The software profile of the image')] - public ?SoftwareProfileOutput $softwareProfile = null; - /** * @var ImageRepositoryOutput[] */ @@ -83,10 +78,6 @@ final class ImageInput $this->isGlobal = $image->isGlobal(); $this->version = $image->getVersion(); - if ($image->getSoftwareProfile()) { - $this->softwareProfile = new SoftwareProfileOutput($image->getSoftwareProfile()); - } - if ($image->getClient()) { $this->client = new ClientOutput($image->getClient()); } @@ -109,10 +100,6 @@ final class ImageInput $image->setName($this->name); $image->setType($this->type); - if ($this->softwareProfile) { - $image->setSoftwareProfile($this->softwareProfile->getEntity()); - } - if ($this->client) { $image->setClient($this->client->getEntity()); } diff --git a/src/Dto/Output/ClientOutput.php b/src/Dto/Output/ClientOutput.php index 2391f60..bdf707f 100644 --- a/src/Dto/Output/ClientOutput.php +++ b/src/Dto/Output/ClientOutput.php @@ -94,7 +94,7 @@ final class ClientOutput extends AbstractOutput #[Groups(['client:read'])] #[ApiProperty( - description: 'El perfil de hardware propio del cliente (registro 1:1, gestionado desde /hardware-profiles)', + description: 'El perfil de hardware asignado al cliente, normalmente heredado del aula y compartido con otros clientes de la misma', example: null )] public ?HardwareProfileOutput $hardwareProfile = null; @@ -219,7 +219,7 @@ final class ClientOutput extends AbstractOutput $this->menu = $client->getMenu() ? new MenuOutput($client->getMenu()) : null; $this->hardwareProfile = $client->getHardwareProfile() - ? new HardwareProfileOutput($client->getHardwareProfile(), includeClient: false) + ? new HardwareProfileOutput($client->getHardwareProfile(), includeClients: false) : null; $this->position = $client->getPosition(); diff --git a/src/Dto/Output/ImageImageRepositoryOutput.php b/src/Dto/Output/ImageImageRepositoryOutput.php index a0eda0f..0cbe9d0 100644 --- a/src/Dto/Output/ImageImageRepositoryOutput.php +++ b/src/Dto/Output/ImageImageRepositoryOutput.php @@ -24,6 +24,13 @@ class ImageImageRepositoryOutput extends AbstractOutput )] public ?ImageRepositoryOutput $imageRepository = null; + #[Groups(['image-image-repository:read', 'image:read'])] + #[ApiProperty( + description: 'El perfil de software detectado en esta versión de la imagen', + example: null + )] + public ?SoftwareProfileOutput $softwareProfile = null; + #[Groups(['image-image-repository:read', 'image:read'])] #[ApiProperty( description: 'El estado de la imagen en el repositorio', @@ -115,6 +122,10 @@ class ImageImageRepositoryOutput extends AbstractOutput $this->imageRepository = new ImageRepositoryOutput($imageImageRepository->getRepository()); } + if ($imageImageRepository->getSoftwareProfile()) { + $this->softwareProfile = new SoftwareProfileOutput($imageImageRepository->getSoftwareProfile(), false); + } + $this->name = $imageImageRepository->getName(); $this->version = $imageImageRepository->getVersion(); $this->partitionInfo = json_decode($imageImageRepository->getPartitionInfo(), true); diff --git a/src/Dto/Output/ImageOutput.php b/src/Dto/Output/ImageOutput.php index 48e8284..1c9fb6e 100644 --- a/src/Dto/Output/ImageOutput.php +++ b/src/Dto/Output/ImageOutput.php @@ -34,13 +34,6 @@ final class ImageOutput extends AbstractOutput )] public ?string $type = ''; - #[Groups(['image:read'])] - #[ApiProperty( - description: 'El perfil de software asociado a la imagen', - example: null - )] - public ?SoftwareProfileOutput $softwareProfile = null; - /** * @var ImageRepositoryOutput[]|null */ @@ -84,7 +77,6 @@ final class ImageOutput extends AbstractOutput parent::__construct($image); $this->name = $image->getName(); - $this->softwareProfile = $image->getSoftwareProfile() ? new SoftwareProfileOutput($image->getSoftwareProfile(), false) : null; $this->imageRepositories = $image->getImageImageRepositories()->map( fn(ImageImageRepository $image) => new ImageImageRepositoryOutput($image) diff --git a/src/Dto/Output/SoftwareProfileOutput.php b/src/Dto/Output/SoftwareProfileOutput.php index 715b935..006d854 100644 --- a/src/Dto/Output/SoftwareProfileOutput.php +++ b/src/Dto/Output/SoftwareProfileOutput.php @@ -12,7 +12,7 @@ use Symfony\Component\Serializer\Annotation\Groups; #[Get(shortName: 'SoftwareProfile')] final class SoftwareProfileOutput extends AbstractOutput { - #[Groups(['software-profile:read', 'image:read'])] + #[Groups(['software-profile:read', 'image:read', 'image-image-repository:read'])] #[ApiProperty( description: 'La descripción del perfil de software', example: 'Perfil estándar para aula de informática' diff --git a/src/Entity/Image.php b/src/Entity/Image.php index 09e51fe..332ecdb 100644 --- a/src/Entity/Image.php +++ b/src/Entity/Image.php @@ -15,10 +15,6 @@ class Image extends AbstractEntity { use NameableTrait; - #[ORM\ManyToOne] - #[ORM\JoinColumn(nullable: true)] - private ?SoftwareProfile $softwareProfile = null; - #[ORM\Column(length: 255, nullable: true)] private ?string $partitionInfo = null; @@ -50,18 +46,6 @@ class Image extends AbstractEntity $this->imageImageRepositories = new ArrayCollection(); } - public function getSoftwareProfile(): ?SoftwareProfile - { - return $this->softwareProfile; - } - - public function setSoftwareProfile(?SoftwareProfile $softwareProfile): static - { - $this->softwareProfile = $softwareProfile; - - return $this; - } - public function getPartitionInfo(): ?string { return $this->partitionInfo; diff --git a/src/Entity/ImageImageRepository.php b/src/Entity/ImageImageRepository.php index ea6fc2d..a238b75 100644 --- a/src/Entity/ImageImageRepository.php +++ b/src/Entity/ImageImageRepository.php @@ -17,6 +17,10 @@ class ImageImageRepository extends AbstractEntity #[ORM\JoinColumn(nullable: false)] private ?ImageRepository $repository = null; + #[ORM\ManyToOne] + #[ORM\JoinColumn(nullable: true)] + private ?SoftwareProfile $softwareProfile = null; + #[ORM\Column(length: 255)] private ?string $status = null; @@ -71,6 +75,18 @@ class ImageImageRepository extends AbstractEntity return $this; } + public function getSoftwareProfile(): ?SoftwareProfile + { + return $this->softwareProfile; + } + + public function setSoftwareProfile(?SoftwareProfile $softwareProfile): static + { + $this->softwareProfile = $softwareProfile; + + return $this; + } + public function getStatus(): ?string { return $this->status; diff --git a/src/Factory/ImageFactory.php b/src/Factory/ImageFactory.php index 9a2e2d4..c3d20f0 100644 --- a/src/Factory/ImageFactory.php +++ b/src/Factory/ImageFactory.php @@ -35,7 +35,6 @@ final class ImageFactory extends ModelFactory return [ 'createdAt' => self::faker()->dateTime(), 'name' => self::faker()->text(255), - 'softwareProfile' => SoftwareProfileFactory::new(), 'updatedAt' => self::faker()->dateTime(), 'type' => 'monolithic', 'isGlobal' => false, diff --git a/src/Factory/SoftwareProfileFactory.php b/src/Factory/SoftwareProfileFactory.php index 2f368a8..43b4655 100644 --- a/src/Factory/SoftwareProfileFactory.php +++ b/src/Factory/SoftwareProfileFactory.php @@ -3,7 +3,6 @@ namespace App\Factory; use App\Entity\SoftwareProfile; -use App\Factory\ImageFactory; use App\Repository\SoftwareProfileRepository; use Zenstruck\Foundry\ModelFactory; use Zenstruck\Foundry\Persistence\PersistentProxyObjectFactory; @@ -37,7 +36,6 @@ final class SoftwareProfileFactory extends ModelFactory 'description' => self::faker()->text(255), 'updatedAt' => self::faker()->dateTime(), 'operativeSystem' => OperativeSystemFactory::createOne()->_save(), - 'image' => ImageFactory::createOne()->_save(), ]; } diff --git a/tests/Functional/CreateSoftwareProfileFromInventoryTest.php b/tests/Functional/CreateSoftwareProfileFromInventoryTest.php new file mode 100644 index 0000000..85b7e11 --- /dev/null +++ b/tests/Functional/CreateSoftwareProfileFromInventoryTest.php @@ -0,0 +1,86 @@ + 'ogadmin', 'roles' => [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + SoftwareFactory::createOne(['name' => 'Firefox']); + + /** @var ImageImageRepository $imageImageRepository */ + $imageImageRepository = ImageImageRepositoryFactory::new([ + 'image' => ImageFactory::new(['client' => ClientFactory::new()]), + ])->create()->_real(); + + $base64Inventory = base64_encode("Firefox\nChrome\n"); + + $statusController = static::getContainer()->get(StatusController::class); + $statusController->createSoftwareProfile($base64Inventory, $imageImageRepository); + + static::getContainer()->get('doctrine')->getManager()->refresh($imageImageRepository); + + $softwareProfile = $imageImageRepository->getSoftwareProfile(); + $this->assertNotNull($softwareProfile, 'El perfil de software debe quedar asignado a la versión (ImageImageRepository)'); + + $softwareNames = $softwareProfile->getSoftwareCollection()->map(fn($software) => $software->getName())->toArray(); + sort($softwareNames); + $this->assertSame(['Chrome', 'Firefox'], $softwareNames); + } + + /** + * Cubre una regresión concreta: al listar /image-image-repositories, el + * softwareProfile embebido debe incluir "description" (el frontend lo + * usa para mostrar el perfil asignado). Se perdía porque la propiedad no + * estaba etiquetada con el grupo de serialización image-image-repository:read. + * + * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface + * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface + * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface + * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface + * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface + */ + public function testSoftwareProfileDescriptionIsVisibleWhenListingImageImageRepositories(): void + { + UserFactory::createOne(['username' => 'ogadmin', 'roles' => [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + SoftwareFactory::createOne(['name' => 'Firefox']); + + /** @var ImageImageRepository $imageImageRepository */ + $imageImageRepository = ImageImageRepositoryFactory::new([ + 'image' => ImageFactory::new(['client' => ClientFactory::new()]), + ])->create()->_real(); + + $statusController = static::getContainer()->get(StatusController::class); + $statusController->createSoftwareProfile(base64_encode("Firefox\n"), $imageImageRepository); + + $iri = $this->findIriBy(ImageImageRepository::class, ['id' => $imageImageRepository->getId()]); + + $client = $this->createClientWithCredentials(); + $client->request('GET', '/image-image-repositories'); + + $this->assertResponseIsSuccessful(); + $data = $client->getResponse()->toArray(); + $member = current(array_filter($data['hydra:member'], fn($item) => $item['@id'] === $iri)); + + $this->assertNotFalse($member, 'La versión creada debe aparecer en el listado'); + $this->assertNotEmpty($member['softwareProfile']['description'] ?? null, 'El listado debe incluir la descripción del perfil de software asignado'); + } +} diff --git a/tests/Functional/SoftwareProfileTest.php b/tests/Functional/SoftwareProfileTest.php index 8d2ac62..f228cac 100644 --- a/tests/Functional/SoftwareProfileTest.php +++ b/tests/Functional/SoftwareProfileTest.php @@ -3,12 +3,11 @@ namespace Functional; -use App\Entity\OrganizationalUnit; +use App\Entity\Software; use App\Entity\SoftwareProfile; -use App\Factory\OrganizationalUnitFactory; +use App\Factory\SoftwareFactory; use App\Factory\SoftwareProfileFactory; use App\Factory\UserFactory; -use App\Model\OrganizationalUnitTypes; use App\Model\UserGroupPermissions; use Symfony\Component\HttpFoundation\Response; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; @@ -59,12 +58,8 @@ class SoftwareProfileTest extends AbstractTest { UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); - OrganizationalUnitFactory::createOne(['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); - $ouIri = $this->findIriBy(OrganizationalUnit::class, ['type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]); - $this->createClientWithCredentials()->request('POST', '/software-profiles',['json' => [ 'description' => self::SW_PROFILE_CREATE, - 'organizationalUnit' => $ouIri ]]); $this->assertResponseStatusCodeSame(201); @@ -76,6 +71,51 @@ class SoftwareProfileTest extends AbstractTest ]); } + /** + * Verifica que el software seleccionado en el formulario se persiste + * (softwareCollection) y que se puede añadir y quitar software después. + * + * @throws RedirectionExceptionInterface + * @throws DecodingExceptionInterface + * @throws ClientExceptionInterface + * @throws TransportExceptionInterface + * @throws ServerExceptionInterface + */ + public function testSoftwareProfileSoftwareCollectionIsPersisted(): void + { + UserFactory::createOne(['username' => self::USER_ADMIN, 'roles'=> [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + + SoftwareFactory::createOne(['name' => 'test-software-a']); + SoftwareFactory::createOne(['name' => 'test-software-b']); + $softwareAIri = $this->findIriBy(Software::class, ['name' => 'test-software-a']); + $softwareBIri = $this->findIriBy(Software::class, ['name' => 'test-software-b']); + + $client = $this->createClientWithCredentials(); + + $client->request('POST', '/software-profiles', ['json' => [ + 'description' => 'test-sw-profile-collection', + 'softwareCollection' => [$softwareAIri, $softwareBIri], + ]]); + $this->assertResponseStatusCodeSame(201); + $iri = $client->getResponse()->toArray()['@id']; + + $client->request('GET', $iri); + $this->assertResponseIsSuccessful(); + $data = $client->getResponse()->toArray(); + $this->assertCount(2, $data['softwareCollection']); + + $client->request('PUT', $iri, ['json' => [ + 'description' => 'test-sw-profile-collection', + 'softwareCollection' => [$softwareAIri], + ]]); + $this->assertResponseIsSuccessful(); + + $client->request('GET', $iri); + $data = $client->getResponse()->toArray(); + $this->assertCount(1, $data['softwareCollection']); + $this->assertSame($softwareAIri, $data['softwareCollection'][0]['@id']); + } + /** * @throws RedirectionExceptionInterface * @throws DecodingExceptionInterface -- 2.40.1 From b4907bc5e63f67c0a297d2b1d719657e34b1e603 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Mon, 13 Jul 2026 10:38:56 +0200 Subject: [PATCH 11/39] ref 3006. Updated creation software profile bug. --- .../OgAgent/Webhook/StatusController.php | 7 +++--- src/Dto/Input/SoftwareProfileInput.php | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 7942d15..2214629 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -440,11 +440,13 @@ class StatusController extends AbstractController $existingNames = array_map(fn($software) => $software->getName(), $existingSoftware); $newSoftwareNames = array_diff($softwareList, $existingNames); + $newSoftware = []; foreach ($newSoftwareNames as $software) { $softwareEntity = new Software(); $softwareEntity->setName($software); $softwareEntity->setType(SoftwareTypes::APPLICATION); $this->entityManager->persist($softwareEntity); + $newSoftware[] = $softwareEntity; } $image = $imageImageRepository?->getImage(); @@ -452,13 +454,12 @@ class StatusController extends AbstractController $softwareProfile = new SoftwareProfile(); $softwareProfile->setDescription('SW Profile - ' . $image->getClient()->getName()); - foreach ($existingSoftware as $softwareEntity) { + foreach ([...$existingSoftware, ...$newSoftware] as $softwareEntity) { $softwareEntity->addSoftwareProfile($softwareProfile); } - $image->setSoftwareProfile($softwareProfile); + $imageImageRepository->setSoftwareProfile($softwareProfile); - $this->entityManager->persist($image); $this->entityManager->persist($imageImageRepository); $this->entityManager->persist($softwareProfile); $this->entityManager->flush(); diff --git a/src/Dto/Input/SoftwareProfileInput.php b/src/Dto/Input/SoftwareProfileInput.php index 79331fe..dba162f 100644 --- a/src/Dto/Input/SoftwareProfileInput.php +++ b/src/Dto/Input/SoftwareProfileInput.php @@ -5,6 +5,8 @@ namespace App\Dto\Input; use ApiPlatform\Metadata\ApiProperty; use App\Dto\Output\ImageOutput; use App\Dto\Output\OperativeSystemOutput; +use App\Dto\Output\SoftwareOutput; +use App\Entity\Software; use App\Entity\SoftwareProfile; use Symfony\Component\Serializer\Annotation\Groups; @@ -26,6 +28,12 @@ final class SoftwareProfileInput #[ApiProperty(description: 'The operative system of the software profile')] public ?OperativeSystemOutput $operativeSystem = null; + /** + * @var SoftwareOutput[] + */ + #[Groups(['software-profile:write'])] + #[ApiProperty(description: 'The software collection of the software profile', readableLink: true)] + public array $softwareCollection = []; public function __construct(?SoftwareProfile $softwareProfile = null) { @@ -42,6 +50,11 @@ final class SoftwareProfileInput if($softwareProfile->getOperativeSystem()) { $this->operativeSystem = new OperativeSystemOutput($softwareProfile->getOperativeSystem()); } + + $this->softwareCollection = array_map( + fn(Software $software) => new SoftwareOutput($software), + $softwareProfile->getSoftwareCollection()->toArray() + ); } public function createOrUpdateEntity(?SoftwareProfile $softwareProfile = null): SoftwareProfile @@ -58,6 +71,18 @@ final class SoftwareProfileInput $softwareProfile->setOperativeSystem($this->operativeSystem->getEntity()); } + $selectedSoftware = array_map(fn(SoftwareOutput $software) => $software->getEntity(), $this->softwareCollection); + + foreach ($softwareProfile->getSoftwareCollection()->toArray() as $existingSoftware) { + if (!in_array($existingSoftware, $selectedSoftware, true)) { + $softwareProfile->removeSoftwareCollection($existingSoftware); + } + } + + foreach ($selectedSoftware as $software) { + $softwareProfile->addSoftwareCollection($software); + } + return $softwareProfile; } } \ No newline at end of file -- 2.40.1 From 22947fd44d39012df0c602cb54e235cadbbf8bab Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Wed, 15 Jul 2026 11:18:36 +0200 Subject: [PATCH 12/39] ref 3009. Execute task right now --- config/api_platform/CommandTask.yaml | 7 + .../RunScheduledCommandTasksCommand.php | 140 ++--------------- src/Controller/CommandTaskExecuteAction.php | 32 ++++ src/Dto/Input/CommandTaskExecuteInput.php | 22 +++ src/Service/CommandTaskTraceCreator.php | 148 ++++++++++++++++++ 5 files changed, 218 insertions(+), 131 deletions(-) create mode 100644 src/Controller/CommandTaskExecuteAction.php create mode 100644 src/Dto/Input/CommandTaskExecuteInput.php create mode 100644 src/Service/CommandTaskTraceCreator.php diff --git a/config/api_platform/CommandTask.yaml b/config/api_platform/CommandTask.yaml index d008252..9832433 100644 --- a/config/api_platform/CommandTask.yaml +++ b/config/api_platform/CommandTask.yaml @@ -24,6 +24,13 @@ resources: ApiPlatform\Metadata\Post: ~ ApiPlatform\Metadata\Delete: ~ + command_task_execute: + class: ApiPlatform\Metadata\Post + method: POST + input: App\Dto\Input\CommandTaskExecuteInput + uriTemplate: /command-tasks/{uuid}/execute + controller: App\Controller\CommandTaskExecuteAction + properties: App\Entity\CommandTask: id: diff --git a/src/Command/RunScheduledCommandTasksCommand.php b/src/Command/RunScheduledCommandTasksCommand.php index 675d0a9..c3b58b4 100644 --- a/src/Command/RunScheduledCommandTasksCommand.php +++ b/src/Command/RunScheduledCommandTasksCommand.php @@ -17,12 +17,10 @@ use App\Entity\CommandTask; use App\Entity\Image; use App\Entity\ImageImageRepository; use App\Entity\Partition; -use App\Entity\Trace; use App\Model\ClientStatus; -use App\Model\CommandTypes; -use App\Model\TraceStatus; use App\Repository\ClientRepository; use App\Repository\CommandTaskRepository; +use App\Service\CommandTaskTraceCreator; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; @@ -41,6 +39,7 @@ class RunScheduledCommandTasksCommand extends Command private readonly DeployImageAction $deployImageAction, private readonly CreateImageAction $createImageAction, private readonly PartitionAssistantAction $partitionAssistantAction, + private readonly CommandTaskTraceCreator $commandTaskTraceCreator, ) { parent::__construct(); @@ -78,15 +77,15 @@ class RunScheduledCommandTasksCommand extends Command if ($isDue && $notYetExecuted) { $output->writeln("Ejecutando tarea: " . $task->getName()); - $scripts = $task->getCommandTaskScripts()->toArray(); - usort($scripts, fn($a, $b) => $a->getExecutionOrder() <=> $b->getExecutionOrder()); - - foreach ($scripts as $script) { - $output->writeln(" - Creando traza para script de tipo {$script->getType()} con orden {$script->getExecutionOrder()}"); - - $this->createTraceForScript($script, $task, $output); + if ($task->getScope() !== 'clients') { + $ou = $task->getOrganizationalUnit(); + $clients = $ou ? $this->clientRepository->findClientsByOrganizationalUnitAndDescendants($ou->getId()) : []; + } else { + $clients = $task->getClients(); } + $this->commandTaskTraceCreator->createPendingTraces($task, $clients); + $task->setLastExecution(new \DateTimeImmutable('now', new \DateTimeZone('UTC'))); $task->setNextExecution($task->calculateNextExecutionDate()); @@ -98,127 +97,6 @@ class RunScheduledCommandTasksCommand extends Command return Command::SUCCESS; } - private function createTraceForScript($script, CommandTask $task, OutputInterface $output): void - { - $scriptParameters = $script->getParameters(); - - if ($task->getScope() !== 'clients') { - $ou = $task->getOrganizationalUnit(); - $clients = $ou ? $this->clientRepository->findClientsByOrganizationalUnitAndDescendants($ou->getId()) : []; - } else { - $clients = $task->getClients(); - } - - foreach ($clients as $client) { - $trace = new Trace(); - $trace->setClient($client); - $trace->setStatus(TraceStatus::PENDING); - $trace->setExecutedAt(new \DateTime()); - - switch ($script->getType()) { - case 'run-script': - $trace->setCommand(CommandTypes::RUN_SCRIPT); - $trace->setInput([ - 'script' => $script->getContent() - ]); - break; - - case 'deploy-image': - $trace->setCommand(CommandTypes::DEPLOY_IMAGE); - - $input = [ - 'imageImageRepository' => $scriptParameters['imageUuid'] - ]; - - if (isset($scriptParameters['method'])) { - $input['method'] = $scriptParameters['method']; - } - if (isset($scriptParameters['type'])) { - $input['type'] = $scriptParameters['type']; - } - if (isset($scriptParameters['diskNumber'])) { - $input['diskNumber'] = $scriptParameters['diskNumber']; - } - if (isset($scriptParameters['partitionNumber'])) { - $input['partitionNumber'] = $scriptParameters['partitionNumber']; - } - if (isset($scriptParameters['mcastMode'])) { - $input['mcastMode'] = $scriptParameters['mcastMode']; - } - if (isset($scriptParameters['mcastSpeed'])) { - $input['mcastSpeed'] = $scriptParameters['mcastSpeed']; - } - if (isset($scriptParameters['mcastPort'])) { - $input['mcastPort'] = $scriptParameters['mcastPort']; - } - if (isset($scriptParameters['mcastIp'])) { - $input['mcastIp'] = $scriptParameters['mcastIp']; - } - if (isset($scriptParameters['maxClients'])) { - $input['maxClients'] = $scriptParameters['maxClients']; - } - if (isset($scriptParameters['maxTime'])) { - $input['maxTime'] = $scriptParameters['maxTime']; - } - if (isset($scriptParameters['p2pMode'])) { - $input['p2pMode'] = $scriptParameters['p2pMode']; - } - if (isset($scriptParameters['p2pTime'])) { - $input['p2pTime'] = $scriptParameters['p2pTime']; - } - - $trace->setInput($input); - break; - - case 'create-image': - $trace->setCommand(CommandTypes::CREATE_IMAGE); - $trace->setInput([ - 'type' => $scriptParameters['type'], - 'imageName' => $scriptParameters['imageName'], - 'imageUuid' => $scriptParameters['imageUuid'] ?? null, - 'diskNumber' => $scriptParameters['diskNumber'] ?? null, - 'partitionNumber' => $scriptParameters['partitionNumber'] ?? null, - 'gitRepositoryName' => $scriptParameters['gitRepositoryName'] ?? null, - 'action' => $scriptParameters['action'] ?? 'create' - ]); - break; - - case 'partition-assistant': - $trace->setCommand(CommandTypes::PARTITION_AND_FORMAT); - $trace->setInput($scriptParameters); - break; - - case 'power-on': - $trace->setCommand(CommandTypes::POWER_ON); - $trace->setInput($scriptParameters ?? []); - break; - - case 'reboot': - $trace->setCommand(CommandTypes::REBOOT); - $trace->setInput($scriptParameters ?? []); - break; - - case 'shutdown': - $trace->setCommand(CommandTypes::SHUTDOWN); - $trace->setInput($scriptParameters ?? []); - break; - - case 'login': - $trace->setCommand(CommandTypes::LOGIN); - $trace->setInput($scriptParameters ?? []); - break; - - default: - $output->writeln(" - Tipo de script no soportado: {$script->getType()}"); - continue 2; - } - - $this->entityManager->persist($trace); - $output->writeln(" - Traza creada para cliente {$client->getUuid()} con comando {$trace->getCommand()}"); - } - } - - private function executePartitionAssistant($script, CommandTask $task, OutputInterface $output): void { $scriptParameters = $script->getParameters(); diff --git a/src/Controller/CommandTaskExecuteAction.php b/src/Controller/CommandTaskExecuteAction.php new file mode 100644 index 0000000..7650f08 --- /dev/null +++ b/src/Controller/CommandTaskExecuteAction.php @@ -0,0 +1,32 @@ + $client->getEntity(), $input->clients); + + $this->commandTaskTraceCreator->createPendingTraces($commandTask, $clients); + + $this->entityManager->flush(); + + return new JsonResponse(data: 'Command task executed successfully', status: Response::HTTP_OK); + } +} diff --git a/src/Dto/Input/CommandTaskExecuteInput.php b/src/Dto/Input/CommandTaskExecuteInput.php new file mode 100644 index 0000000..fc4aa58 --- /dev/null +++ b/src/Dto/Input/CommandTaskExecuteInput.php @@ -0,0 +1,22 @@ +getCommandTaskScripts()->toArray(); + usort($scripts, fn($a, $b) => $a->getExecutionOrder() <=> $b->getExecutionOrder()); + + foreach ($scripts as $script) { + foreach ($clients as $client) { + $this->createTraceForScript($script, $client); + } + } + } + + private function createTraceForScript($script, $client): void + { + $scriptParameters = $script->getParameters(); + + $trace = new Trace(); + $trace->setClient($client); + $trace->setStatus(TraceStatus::PENDING); + $trace->setExecutedAt(new \DateTime()); + + switch ($script->getType()) { + case 'run-script': + $trace->setCommand(CommandTypes::RUN_SCRIPT); + $trace->setInput([ + 'script' => $script->getContent() + ]); + break; + + case 'deploy-image': + $trace->setCommand(CommandTypes::DEPLOY_IMAGE); + + $input = [ + 'imageImageRepository' => $scriptParameters['imageUuid'] + ]; + + if (isset($scriptParameters['method'])) { + $input['method'] = $scriptParameters['method']; + } + if (isset($scriptParameters['type'])) { + $input['type'] = $scriptParameters['type']; + } + if (isset($scriptParameters['diskNumber'])) { + $input['diskNumber'] = $scriptParameters['diskNumber']; + } + if (isset($scriptParameters['partitionNumber'])) { + $input['partitionNumber'] = $scriptParameters['partitionNumber']; + } + if (isset($scriptParameters['mcastMode'])) { + $input['mcastMode'] = $scriptParameters['mcastMode']; + } + if (isset($scriptParameters['mcastSpeed'])) { + $input['mcastSpeed'] = $scriptParameters['mcastSpeed']; + } + if (isset($scriptParameters['mcastPort'])) { + $input['mcastPort'] = $scriptParameters['mcastPort']; + } + if (isset($scriptParameters['mcastIp'])) { + $input['mcastIp'] = $scriptParameters['mcastIp']; + } + if (isset($scriptParameters['maxClients'])) { + $input['maxClients'] = $scriptParameters['maxClients']; + } + if (isset($scriptParameters['maxTime'])) { + $input['maxTime'] = $scriptParameters['maxTime']; + } + if (isset($scriptParameters['p2pMode'])) { + $input['p2pMode'] = $scriptParameters['p2pMode']; + } + if (isset($scriptParameters['p2pTime'])) { + $input['p2pTime'] = $scriptParameters['p2pTime']; + } + + $trace->setInput($input); + break; + + case 'create-image': + $trace->setCommand(CommandTypes::CREATE_IMAGE); + $trace->setInput([ + 'type' => $scriptParameters['type'], + 'imageName' => $scriptParameters['imageName'], + 'imageUuid' => $scriptParameters['imageUuid'] ?? null, + 'diskNumber' => $scriptParameters['diskNumber'] ?? null, + 'partitionNumber' => $scriptParameters['partitionNumber'] ?? null, + 'gitRepositoryName' => $scriptParameters['gitRepositoryName'] ?? null, + 'action' => $scriptParameters['action'] ?? 'create' + ]); + break; + + case 'partition-assistant': + $trace->setCommand(CommandTypes::PARTITION_AND_FORMAT); + $trace->setInput($scriptParameters); + break; + + case 'power-on': + $trace->setCommand(CommandTypes::POWER_ON); + $trace->setInput($scriptParameters ?? []); + break; + + case 'reboot': + $trace->setCommand(CommandTypes::REBOOT); + $trace->setInput($scriptParameters ?? []); + break; + + case 'shutdown': + $trace->setCommand(CommandTypes::SHUTDOWN); + $trace->setInput($scriptParameters ?? []); + break; + + case 'login': + $trace->setCommand(CommandTypes::LOGIN); + $trace->setInput($scriptParameters ?? []); + break; + + default: + return; + } + + $this->entityManager->persist($trace); + } +} -- 2.40.1 From 170ff14bd9d8e69d2626ca95d0ea437dbb8a82b9 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 16 Jul 2026 10:48:52 +0200 Subject: [PATCH 13/39] feat(webhook): procesar cfg en respuestas de EjecutarScript MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Permite que la configuración de particiones y caché se actualice automáticamente en la BBDD cuando termina la ejecución de un script en el cliente, evitando tener que encadenar refrescos manuales. --- src/Controller/OgAgent/Webhook/StatusController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 2214629..65099f1 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -368,7 +368,7 @@ class StatusController extends AbstractController } } - if (isset($data['nfn']) && $data['nfn'] === self::REFRESH) { + if (isset($data['nfn']) && ($data['nfn'] === self::REFRESH || $data['nfn'] === self::RUN_SCRIPT)) { $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id'] ?? '']); if ($trace) { $client = $trace->getClient(); @@ -386,7 +386,7 @@ class StatusController extends AbstractController if (isset($data['cfg'])) { $this->createPartitionService->__invoke($data, $client); - $this->logger->info('Partition configuration updated via RESPUESTA_Actualizar', ['job_id' => $data['job_id'] ?? 'none']); + $this->logger->info('Partition configuration updated via ' . $data['nfn'], ['job_id' => $data['job_id'] ?? 'none']); } } $this->entityManager->flush(); -- 2.40.1 From 1b24414c0ce731b7354c6037616c7fed6b8cb6f2 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Fri, 17 Jul 2026 10:54:52 +0200 Subject: [PATCH 14/39] docs: actualizar CHANGELOG para la version 1.9.1 --- CHANGELOG.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fcb24f5..cd65937 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## [1.9.1] - 2026-07-17 + +### Added +- Webhook (`StatusController`): Procesa la configuración de discos, particiones y caché en la respuesta del payload de la tarea `EjecutarScript`, guardándola automáticamente en base de datos. +- Perfil de usuario: Añadido campo de preferencia de idioma (`language`). +- Unidades organizativas: Ordenar hijos alfabéticamente por nombre. + +### Fixed +- Tareas programadas (`Schedule`): Corregido bug en ejecución inmediata de comandos (Execute task right now). +- Despliegue de imágenes: Eliminada restricción que impedía el despliegue en clientes con distintos tamaños de partición. +- Perfiles de software: Corregido bug en la creación del perfil de software y actualizada entidad de imagen asociada. +- Perfiles de hardware: Ajustes en los settings de red y propagación de perfiles. +- Scripts: Aumentado el tamaño del campo de texto en base de datos para almacenar scripts más largos. +- Roles: Actualización menor de permisos. + ## [1.9.0] - 2026-06-16 ### Added -- 2.40.1 From 52515633afa06b8a399041e696dca6536974bdeb Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Fri, 17 Jul 2026 11:44:30 +0200 Subject: [PATCH 15/39] ref 3016. Updated ogRepository sync --- src/Controller/OgRepository/Image/SyncAction.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/Controller/OgRepository/Image/SyncAction.php b/src/Controller/OgRepository/Image/SyncAction.php index e224af7..4183353 100644 --- a/src/Controller/OgRepository/Image/SyncAction.php +++ b/src/Controller/OgRepository/Image/SyncAction.php @@ -80,6 +80,18 @@ class SyncAction extends AbstractOgRepositoryController $this->entityManager->flush(); + $orphanImages = $imageRepo->createQueryBuilder('i') + ->leftJoin('i.imageImageRepositories', 'iir') + ->andWhere('iir.id IS NULL') + ->getQuery() + ->getResult(); + + foreach ($orphanImages as $orphanImage) { + $this->entityManager->remove($orphanImage); + } + + $this->entityManager->flush(); + return new JsonResponse(data: $content, status: Response::HTTP_OK); } -- 2.40.1 From cc0e45eae97c0afa87016cb33aaa2fd244ba5650 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Fri, 17 Jul 2026 11:56:39 +0200 Subject: [PATCH 16/39] ref 3017. Fixed bug EjecutarScript webhook --- src/Controller/OgAgent/Webhook/StatusController.php | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 65099f1..70e5824 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -320,16 +320,21 @@ class StatusController extends AbstractController if (isset($data['nfn']) && $data['nfn'] === self::RUN_SCRIPT) { $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); if ($trace) { - $trace->setStatus(TraceStatus::SUCCESS); + if ($data['res'] === 1) { + $trace->setStatus(TraceStatus::SUCCESS); + } else { + $trace->setStatus(TraceStatus::FAILED); + $trace->setOutput($data['der']); + } $trace->setFinishedAt(new \DateTime()); $this->entityManager->persist($trace); - + $client = $trace->getClient(); if ($client && $client->getStatus() === ClientStatus::BUSY) { $client->setStatus(ClientStatus::OG_LIVE); $this->entityManager->persist($client); } - + $this->entityManager->flush(); } } @@ -368,7 +373,7 @@ class StatusController extends AbstractController } } - if (isset($data['nfn']) && ($data['nfn'] === self::REFRESH || $data['nfn'] === self::RUN_SCRIPT)) { + if (isset($data['nfn']) && $data['nfn'] === self::REFRESH) { $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id'] ?? '']); if ($trace) { $client = $trace->getClient(); -- 2.40.1 From 17c5c603f1799b909157f44e954afa03cd10baf6 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Sat, 18 Jul 2026 01:30:37 +0200 Subject: [PATCH 17/39] fix(webhook): restaurar parseo de particiones en EjecutarScript borrado accidentalmente --- src/Controller/OgAgent/Webhook/StatusController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 70e5824..d1397f1 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -373,7 +373,7 @@ class StatusController extends AbstractController } } - if (isset($data['nfn']) && $data['nfn'] === self::REFRESH) { + if (isset($data['nfn']) && ($data['nfn'] === self::REFRESH || $data['nfn'] === self::RUN_SCRIPT)) { $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id'] ?? '']); if ($trace) { $client = $trace->getClient(); -- 2.40.1 From d2cbc513368bc530fa10d916c17dffa8dd284424 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Sat, 18 Jul 2026 01:41:08 +0200 Subject: [PATCH 18/39] refactor(webhook): consolidar procesamiento de comandos en un bloque switch --- .../OgAgent/Webhook/StatusController.php | 564 +++++++++--------- 1 file changed, 271 insertions(+), 293 deletions(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index d1397f1..d57c0a8 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -112,324 +112,302 @@ class StatusController extends AbstractController $this->entityManager->flush(); } - if (isset($data['nfn']) && $data['nfn'] === 'START_SCRIPT') { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - if (!$trace) { + $nfn = $data['nfn'] ?? null; + if (!$nfn) { + return new JsonResponse(data: 'Webhook finished', status: Response::HTTP_OK); + } + + switch ($nfn) { + case 'START_SCRIPT': + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + if (!$trace) { + $clientIp = $data['iph'] ?? $request->getClientIp(); + $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]); + if ($client) { + $this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, TraceStatus::IN_PROGRESS, $data['job_id'], ['script' => $data['command'] ?? 'Local script']); + $this->logger->info('Trace automatically created for local script', ['job_id' => $data['job_id']]); + $client->setStatus(ClientStatus::BUSY); + $this->entityManager->persist($client); + $this->entityManager->flush(); + } + } + break; + + case 'REBOOT': + case 'POWEROFF': $clientIp = $data['iph'] ?? $request->getClientIp(); $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]); if ($client) { - $this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, TraceStatus::IN_PROGRESS, $data['job_id'], ['script' => $data['command'] ?? 'Local script']); - $this->logger->info('Trace automatically created for local script', ['job_id' => $data['job_id']]); - $client->setStatus(ClientStatus::BUSY); - $this->entityManager->persist($client); + $traces = $this->entityManager->getRepository(Trace::class)->findBy(['client' => $client, 'status' => TraceStatus::IN_PROGRESS]); + foreach ($traces as $trace) { + $trace->setStatus(TraceStatus::SUCCESS); + $trace->setFinishedAt(new \DateTime()); + $this->entityManager->persist($trace); + } + + $previousStatus = $client->getStatus(); + if ($previousStatus === ClientStatus::BUSY) { + $newStatus = ($nfn === 'REBOOT') ? ClientStatus::INITIALIZING : ClientStatus::TURNING_OFF; + $client->setStatus($newStatus); + $this->entityManager->persist($client); + $this->logger->info('Reboot/Poweroff received while client was busy, changing status', [ + 'ip' => $clientIp, 'nfn' => $nfn, 'previous_status' => $previousStatus, 'new_status' => $newStatus, + ]); + } else { + $this->logger->info('Reboot/Poweroff received but client was not busy, status unchanged', [ + 'ip' => $clientIp, 'nfn' => $nfn, 'current_status' => $previousStatus, + ]); + } + $this->entityManager->flush(); + $this->logger->info('Reboot/Poweroff webhook received. Automatically resolved in-progress traces.', ['num_traces' => count($traces), 'nfn' => $nfn]); } - } - } - - if (isset($data['nfn']) && in_array($data['nfn'], ['REBOOT', 'POWEROFF'], true)) { - $clientIp = $data['iph'] ?? $request->getClientIp(); - $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]); - if ($client) { - $traces = $this->entityManager->getRepository(Trace::class)->findBy(['client' => $client, 'status' => TraceStatus::IN_PROGRESS]); - foreach ($traces as $trace) { + break; + + case self::CREATE_IMAGE_GIT: + case self::UPDATE_IMAGE_GIT: + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + + if (!$trace) { + $this->logger->error('Trace not found', $data); + return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND); + } + + if ($data['res'] === 1) { + $trace->setStatus(TraceStatus::SUCCESS); + $trace->setFinishedAt(new \DateTime()); + } else { + $trace->setStatus(TraceStatus::FAILED); + $trace->setFinishedAt(new \DateTime()); + $trace->setOutput($data['der']); + } + + $client = $trace->getClient(); + $client->setStatus(ClientStatus::OG_LIVE); + $this->entityManager->persist($client); + $this->entityManager->persist($trace); + $this->entityManager->flush(); + + $msg = $nfn === self::CREATE_IMAGE_GIT ? 'Git image creation completed.' : 'Git image update completed.'; + $this->logger->info($msg, ['job_id' => $data['job_id'], 'success' => $data['res'] === 1]); + break; + + case self::CREATE_IMAGE: + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + /** @var ImageImageRepository $imageImageRepository */ + $imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $data['idi']]); + + if (!$imageImageRepository) { + $this->logger->error('Image not found', $data); + return new JsonResponse(['message' => 'Image not found'], Response::HTTP_NOT_FOUND); + } + + if (!$trace) { + $this->logger->error('Trace not found', $data); + return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND); + } + + if ($data['res'] === 1) { + $trace->setStatus(TraceStatus::SUCCESS); + $trace->setFinishedAt(new \DateTime()); + $imageImageRepository->setStatus(ImageStatus::AUX_FILES_PENDING); + $imageImageRepository->setCreated(true); + $this->entityManager->persist($imageImageRepository); + + $this->logger->info('Start partition creation. ', ['image' => (string) $imageImageRepository->getUuid()]); + if (isset($data['cfg'])) { + $this->createPartitionService->__invoke($data, $imageImageRepository->getImage()->getClient()); + } + $this->logger->info('Starting software profile creation. ', ['image' => (string) $imageImageRepository->getUuid()]); + $this->createSoftwareProfile($data['inv_sft'], $imageImageRepository); + $this->logger->info('Start aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]); + + try { + $this->createAuxFilesAction->__invoke($imageImageRepository); + } catch (\Exception $e) { + $this->logger->error('Error creating aux files', ['image' => (string) $imageImageRepository->getUuid(), 'error' => $e->getMessage()]); + } + + $this->logger->info('End aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]); + } else { + $trace->setStatus(TraceStatus::FAILED); + $trace->setFinishedAt(new \DateTime()); + $trace->setOutput($data['der']); + $imageImageRepository->setCreated(false); + $imageImageRepository->setStatus(ImageStatus::FAILED); + $this->logger->error('Image updated failed', $data); + } + + $this->entityManager->persist($imageImageRepository); + $client = $trace->getClient(); + $client->setStatus(ClientStatus::OG_LIVE); + $this->entityManager->persist($client); + $this->entityManager->persist($trace); + $this->entityManager->flush(); + $this->logger->info('Image updated. Success.', ['image' => (string) $imageImageRepository->getUuid()]); + break; + + case self::RESTORE_IMAGE: + case self::CONFIGURE_IMAGE: + case self::RESTORE_IMAGE_GIT: + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + + if (!$trace) { + $this->logger->error('Trace not found', $data); + return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND); + } + + $client = $trace->getClient(); + + if ($data['res'] === 1) { + $trace->setStatus(TraceStatus::SUCCESS); + $trace->setFinishedAt(new \DateTime()); + if (isset($data['cfg'])) { + $this->createPartitionService->__invoke($data,$client); + } + } else { + $trace->setStatus(TraceStatus::FAILED); + $trace->setFinishedAt(new \DateTime()); + $trace->setOutput($data['der']); + } + + $client->setStatus(ClientStatus::OG_LIVE); + $this->entityManager->persist($client); + $this->entityManager->persist($trace); + + if ($nfn === self::RESTORE_IMAGE) { + $partitionData = json_decode(json_encode($trace->getInput()), true); + + $numDisk = (int) ($partitionData['numDisk'] ?? null); + $numPartition = (int) ($partitionData['numPartition'] ?? null); + + $imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $partitionData['image']]); + + $partition = $this->entityManager->getRepository(Partition::class) + ->findOneBy(['diskNumber' => $numDisk, 'partitionNumber' => $numPartition, 'client' => $client]); + + if ($partition) { + $partition->setImage($imageImageRepository); + $this->entityManager->persist($partition); + } + } + + $this->entityManager->flush(); + break; + + case self::RUN_SCRIPT: + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + if ($trace) { + $client = $trace->getClient(); + if ($data['res'] === 1) { + $trace->setStatus(TraceStatus::SUCCESS); + } else { + $trace->setStatus(TraceStatus::FAILED); + $trace->setOutput($data['der'] ?? ''); + } + $trace->setFinishedAt(new \DateTime()); + $this->entityManager->persist($trace); + } else { + $clientIp = $data['iph'] ?? $request->getClientIp(); + $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]); + } + + if ($client) { + if ($client->getStatus() === ClientStatus::BUSY) { + $client->setStatus(ClientStatus::OG_LIVE); + } + $this->entityManager->persist($client); + + if (isset($data['cfg'])) { + $this->createPartitionService->__invoke($data, $client); + $this->logger->info('Partition configuration updated via RUN_SCRIPT', ['job_id' => $data['job_id'] ?? 'none']); + } + } + $this->entityManager->flush(); + break; + + case self::HARDWARE_INVENTORY: + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + if ($trace) { $trace->setStatus(TraceStatus::SUCCESS); $trace->setFinishedAt(new \DateTime()); $this->entityManager->persist($trace); + $this->entityManager->flush(); } - - $previousStatus = $client->getStatus(); - if ($previousStatus === ClientStatus::BUSY) { - $newStatus = ($data['nfn'] === 'REBOOT') ? ClientStatus::INITIALIZING : ClientStatus::TURNING_OFF; - $client->setStatus($newStatus); - $this->entityManager->persist($client); - $this->logger->info('Reboot/Poweroff received while client was busy, changing status', [ - 'ip' => $clientIp, 'nfn' => $data['nfn'], 'previous_status' => $previousStatus, 'new_status' => $newStatus, - ]); - } else { - $this->logger->info('Reboot/Poweroff received but client was not busy, status unchanged', [ - 'ip' => $clientIp, 'nfn' => $data['nfn'], 'current_status' => $previousStatus, - ]); - } - - $this->entityManager->flush(); - $this->logger->info('Reboot/Poweroff webhook received. Automatically resolved in-progress traces.', ['num_traces' => count($traces), 'nfn' => $data['nfn']]); - } - } + break; - if (isset($data['progress'])){ - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - if ($trace){ - $trace->setProgress((int)($data['progress'] * 100)); - $this->entityManager->persist($trace); - $this->entityManager->flush(); - } - } - - if (isset($data['nfn']) && $data['nfn'] === self::CREATE_IMAGE_GIT) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + case self::SOFTWARE_INVENTORY: + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + if ($trace) { + $client = $trace->getClient(); + $dataInput = json_decode(json_encode($trace->getInput()), true); + $imageUuid = $dataInput['image'] ?? null; - if (!$trace) { - $this->logger->error('Trace not found', $data); - return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND); - } - - if ($data['res'] === 1) { - $trace->setStatus(TraceStatus::SUCCESS); - $trace->setFinishedAt(new \DateTime()); - } else { - $trace->setStatus(TraceStatus::FAILED); - $trace->setFinishedAt(new \DateTime()); - $trace->setOutput($data['der']); - } - - $client = $trace->getClient(); - $client->setStatus(ClientStatus::OG_LIVE); - $this->entityManager->persist($client); - $this->entityManager->persist($trace); - $this->entityManager->flush(); - $this->logger->info('Git image creation completed.', ['job_id' => $data['job_id'], 'success' => $data['res'] === 1]); - } - - if (isset($data['nfn']) && $data['nfn'] === self::UPDATE_IMAGE_GIT) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - - if (!$trace) { - $this->logger->error('Trace not found', $data); - return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND); - } - - if ($data['res'] === 1) { - $trace->setStatus(TraceStatus::SUCCESS); - $trace->setFinishedAt(new \DateTime()); - } else { - $trace->setStatus(TraceStatus::FAILED); - $trace->setFinishedAt(new \DateTime()); - $trace->setOutput($data['der']); - } - - $client = $trace->getClient(); - $client->setStatus(ClientStatus::OG_LIVE); - $this->entityManager->persist($client); - $this->entityManager->persist($trace); - $this->entityManager->flush(); - $this->logger->info('Git image update completed.', ['job_id' => $data['job_id'], 'success' => $data['res'] === 1]); - } - - if (isset($data['nfn']) && $data['nfn'] === self::CREATE_IMAGE) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - /** @var ImageImageRepository $imageImageRepository */ - $imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $data['idi']]); - - if (!$imageImageRepository) { - $this->logger->error('Image not found', $data); - return new JsonResponse(['message' => 'Image not found'], Response::HTTP_NOT_FOUND); - } - - if (!$trace) { - $this->logger->error('Trace not found', $data); - return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND); - } - - if ($data['res'] === 1) { - $trace->setStatus(TraceStatus::SUCCESS); - $trace->setFinishedAt(new \DateTime()); - $imageImageRepository->setStatus(ImageStatus::AUX_FILES_PENDING); - $imageImageRepository->setCreated(true); - $this->entityManager->persist($imageImageRepository); - - $this->logger->info('Start partition creation. ', ['image' => (string) $imageImageRepository->getUuid()]); - if (isset($data['cfg'])) { - $this->createPartitionService->__invoke($data, $imageImageRepository->getImage()->getClient()); - } - $this->logger->info('Starting software profile creation. ', ['image' => (string) $imageImageRepository->getUuid()]); - $this->createSoftwareProfile($data['inv_sft'], $imageImageRepository); - $this->logger->info('Start aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]); - - try { - $this->createAuxFilesAction->__invoke($imageImageRepository); - } catch (\Exception $e) { - $this->logger->error('Error creating aux files', ['image' => (string) $imageImageRepository->getUuid(), 'error' => $e->getMessage()]); - } - - $this->logger->info('End aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]); - } else { - $trace->setStatus(TraceStatus::FAILED); - $trace->setFinishedAt(new \DateTime()); - $trace->setOutput($data['der']); - $imageImageRepository->setCreated(false); - $imageImageRepository->setStatus(ImageStatus::FAILED); - $this->logger->error('Image updated failed', $data); - } - - $this->entityManager->persist($imageImageRepository); - $client = $trace->getClient(); - $client->setStatus(ClientStatus::OG_LIVE); - $this->entityManager->persist($client); - $this->entityManager->persist($trace); - $this->entityManager->flush(); - $this->logger->info('Image updated. Success.', ['image' => (string) $imageImageRepository->getUuid()]); - } - - if (isset($data['nfn']) && ($data['nfn'] === self::RESTORE_IMAGE || $data['nfn'] === self::CONFIGURE_IMAGE || $data['nfn'] === self::RESTORE_IMAGE_GIT)) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - - if (!$trace) { - $this->logger->error('Trace not found', $data); - return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND); - } - - $client = $trace->getClient(); - - if ($data['res'] === 1) { - $trace->setStatus(TraceStatus::SUCCESS); - $trace->setFinishedAt(new \DateTime()); - if (isset($data['cfg'])) { - $this->createPartitionService->__invoke($data,$client); - } - } else { - $trace->setStatus(TraceStatus::FAILED); - $trace->setFinishedAt(new \DateTime()); - $trace->setOutput($data['der']); - } - - $client->setStatus(ClientStatus::OG_LIVE); - $this->entityManager->persist($client); - $this->entityManager->persist($trace); - - if ($data['nfn'] === self::RESTORE_IMAGE) { - $partitionData = json_decode(json_encode($trace->getInput()), true); - - $numDisk = (int) $partitionData['numDisk'] ?? null; - $numPartition = (int) $partitionData['numPartition'] ?? null; - - $imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $partitionData['image']]); - - $partition = $this->entityManager->getRepository(Partition::class) - ->findOneBy(['diskNumber' => $numDisk, 'partitionNumber' => $numPartition, 'client' => $client]); - - if ($partition) { - $partition->setImage($imageImageRepository); - $this->entityManager->persist($partition); - } - } - - $this->entityManager->flush(); - } - - if (isset($data['nfn']) && $data['nfn'] === self::RUN_SCRIPT) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - if ($trace) { - if ($data['res'] === 1) { $trace->setStatus(TraceStatus::SUCCESS); - } else { - $trace->setStatus(TraceStatus::FAILED); - $trace->setOutput($data['der']); - } - $trace->setFinishedAt(new \DateTime()); - $this->entityManager->persist($trace); + $trace->setFinishedAt(new \DateTime()); + $this->entityManager->persist($trace); - $client = $trace->getClient(); - if ($client && $client->getStatus() === ClientStatus::BUSY) { + $image = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $imageUuid]); + $this->createSoftwareProfile($data['contents'], $image); + + $this->entityManager->flush(); + } + break; + + case self::REFRESH: + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id'] ?? '']); + if ($trace) { + $client = $trace->getClient(); + $trace->setStatus(TraceStatus::SUCCESS); + $trace->setFinishedAt(new \DateTime()); + $this->entityManager->persist($trace); + } else { + $clientIp = $data['iph'] ?? $request->getClientIp(); + $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]); + } + + if ($client) { $client->setStatus(ClientStatus::OG_LIVE); $this->entityManager->persist($client); + + if (isset($data['cfg'])) { + $this->createPartitionService->__invoke($data, $client); + $this->logger->info('Partition configuration updated via REFRESH', ['job_id' => $data['job_id'] ?? 'none']); + } } - $this->entityManager->flush(); - } - } + break; - if (isset($data['nfn']) && $data['nfn'] === self::HARDWARE_INVENTORY) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - if ($trace) { - $client = $trace->getClient(); - - $trace->setStatus(TraceStatus::SUCCESS); - $trace->setFinishedAt(new \DateTime()); - $this->entityManager->persist($trace); - - //$client->setHardwareProfile(); - - $this->entityManager->flush(); - } - } - - if (isset($data['nfn']) && $data['nfn'] === self::SOFTWARE_INVENTORY) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); - - if ($trace) { - $client = $trace->getClient(); - $dataInput = json_decode(json_encode($trace->getInput()), true); - $imageUuid = $dataInput['image'] ?? null; - - $trace->setStatus(TraceStatus::SUCCESS); - $trace->setFinishedAt(new \DateTime()); - $this->entityManager->persist($trace); - - $image = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $imageUuid]); - $this->createSoftwareProfile($data['contents'], $image); - - $this->entityManager->flush(); - } - } - - if (isset($data['nfn']) && ($data['nfn'] === self::REFRESH || $data['nfn'] === self::RUN_SCRIPT)) { - $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id'] ?? '']); - if ($trace) { - $client = $trace->getClient(); - $trace->setStatus(TraceStatus::SUCCESS); - $trace->setFinishedAt(new \DateTime()); - $this->entityManager->persist($trace); - } else { + case self::INICIAR_SESION: $clientIp = $data['iph'] ?? $request->getClientIp(); $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]); - } - if ($client) { - $client->setStatus(ClientStatus::OG_LIVE); - $this->entityManager->persist($client); - - if (isset($data['cfg'])) { - $this->createPartitionService->__invoke($data, $client); - $this->logger->info('Partition configuration updated via ' . $data['nfn'], ['job_id' => $data['job_id'] ?? 'none']); - } - } - $this->entityManager->flush(); - } + if ($client) { + $res = isset($data['res']) ? (int) $data['res'] : null; - if (isset($data['nfn']) && $data['nfn'] === self::INICIAR_SESION) { - $clientIp = $data['iph'] ?? $request->getClientIp(); - $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]); - - if ($client) { - $res = isset($data['res']) ? (int) $data['res'] : null; - - if ($res === 1) { - // IniciarSesion acknowledged by OGLive agent: machine is booting to Windows. - // Call urlLogin early so UDS doesn't timeout (~21s) waiting for the real loggedin. - // agentLoggedIn will call urlLogin again once the user actually logs into Windows. - $remotePC = $client->getRemotePC(); - if ($remotePC && $remotePC->isReservedActive() && $remotePC->getUrlLogin()) { - try { - $url = str_starts_with($remotePC->getUrlLogin(), 'http://') ? 'https://' . substr($remotePC->getUrlLogin(), 7) : $remotePC->getUrlLogin(); - $status = $this->httpClient->request('GET', $url, [ - 'verify_peer' => false, - 'verify_host' => false, - ])->getStatusCode(); - $this->logger->info('RemotePC: early urlLogin called after IniciarSesion ack', ['ip' => $clientIp, 'status' => $status]); - } catch (\Throwable $e) { - $this->logger->warning('RemotePC: early urlLogin failed', ['ip' => $clientIp, 'error' => $e->getMessage()]); + if ($res === 1) { + $remotePC = $client->getRemotePC(); + if ($remotePC && $remotePC->isReservedActive() && $remotePC->getUrlLogin()) { + try { + $url = str_starts_with($remotePC->getUrlLogin(), 'http://') ? 'https://' . substr($remotePC->getUrlLogin(), 7) : $remotePC->getUrlLogin(); + $status = $this->httpClient->request('GET', $url, [ + 'verify_peer' => false, + 'verify_host' => false, + ])->getStatusCode(); + $this->logger->info('RemotePC: early urlLogin called after IniciarSesion ack', ['ip' => $clientIp, 'status' => $status]); + } catch (\Throwable $e) { + $this->logger->warning('RemotePC: early urlLogin failed', ['ip' => $clientIp, 'error' => $e->getMessage()]); + } } + } else { + $this->logger->warning('RESPUESTA_IniciarSesion: agent reported failure', [ + 'ip' => $clientIp, + 'job_id' => $data['job_id'] ?? null, + 'res' => $res, + ]); } - } else { - // IniciarSesion failed — log it; the PENDING trace will retry on next cron run - $this->logger->warning('RESPUESTA_IniciarSesion: agent reported failure', [ - 'ip' => $clientIp, - 'job_id' => $data['job_id'] ?? null, - 'res' => $res, - ]); } - } + break; } return new JsonResponse(data: 'Webhook finished', status: Response::HTTP_OK); -- 2.40.1 From f2566bb9c999513f97646c127484d43606cf450c Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Sun, 19 Jul 2026 17:35:15 +0200 Subject: [PATCH 19/39] ref 3018. Cancel multiple task --- src/Controller/CancelMultipleTracesAction.php | 38 ++++++-- src/Controller/OgAgent/KillJobAction.php | 65 +++---------- src/Service/Trace/KillJobService.php | 91 +++++++++++++++++++ 3 files changed, 135 insertions(+), 59 deletions(-) create mode 100644 src/Service/Trace/KillJobService.php diff --git a/src/Controller/CancelMultipleTracesAction.php b/src/Controller/CancelMultipleTracesAction.php index 3fc55e1..417fcd2 100644 --- a/src/Controller/CancelMultipleTracesAction.php +++ b/src/Controller/CancelMultipleTracesAction.php @@ -5,7 +5,9 @@ namespace App\Controller; use App\Dto\Input\CancelMultipleTracesInput; use App\Entity\Trace; use App\Model\TraceStatus; +use App\Service\Trace\KillJobService; use Doctrine\ORM\EntityManagerInterface; +use Psr\Log\LoggerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; @@ -14,22 +16,44 @@ class CancelMultipleTracesAction extends AbstractController { public function __construct( private readonly EntityManagerInterface $entityManager, + private readonly KillJobService $killJobService, + private readonly LoggerInterface $logger, ) { } public function __invoke(CancelMultipleTracesInput $input): JsonResponse { - foreach ($input->traces as $trace) { - /** @var Trace $trace */ - $trace = $trace->getEntity(); + $cancelled = []; + $failed = []; - $trace->setStatus(TraceStatus::CANCELLED); - $this->entityManager->persist($trace); + foreach ($input->traces as $traceOutput) { + /** @var Trace $trace */ + $trace = $traceOutput->getEntity(); + + try { + if ($trace->getStatus() === TraceStatus::IN_PROGRESS) { + $this->killJobService->kill($trace, (string) $trace->getJobId()); + } elseif ($trace->getStatus() === TraceStatus::PENDING) { + $trace->setStatus(TraceStatus::CANCELLED); + $this->entityManager->persist($trace); + } else { + $failed[] = ['trace' => $trace->getUuid(), 'reason' => 'not cancellable']; + continue; + } + + $cancelled[] = $trace->getUuid(); + } catch (\Throwable $e) { + $this->logger->error(sprintf('Error cancelling trace %s: %s', $trace->getUuid(), $e->getMessage())); + $failed[] = ['trace' => $trace->getUuid(), 'reason' => $e->getMessage()]; + } } $this->entityManager->flush(); - return new JsonResponse(data: 'Traces cancelled successfully', status: Response::HTTP_OK); + return new JsonResponse( + data: ['cancelled' => $cancelled, 'failed' => $failed], + status: Response::HTTP_OK + ); } -} \ No newline at end of file +} diff --git a/src/Controller/OgAgent/KillJobAction.php b/src/Controller/OgAgent/KillJobAction.php index c218c47..5268a07 100644 --- a/src/Controller/OgAgent/KillJobAction.php +++ b/src/Controller/OgAgent/KillJobAction.php @@ -6,66 +6,27 @@ namespace App\Controller\OgAgent; use App\Dto\Input\KillJobInput; use App\Entity\Trace; -use App\Model\ClientStatus; -use App\Model\CommandTypes; -use App\Model\TraceStatus; -use App\Service\Trace\CreateService; +use App\Service\Trace\KillJobService; +use Doctrine\ORM\EntityManagerInterface; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; -use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; -use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; -use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; -use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; +use Symfony\Component\HttpKernel\Attribute\AsController; -class KillJobAction extends AbstractOgAgentController +#[AsController] +class KillJobAction extends AbstractController { - /** - * @throws TransportExceptionInterface - * @throws ServerExceptionInterface - * @throws RedirectionExceptionInterface - * @throws ClientExceptionInterface - */ + public function __construct( + private readonly EntityManagerInterface $entityManager, + private readonly KillJobService $killJobService, + ) { + } + public function __invoke(Trace $trace, KillJobInput $input): JsonResponse { - $client = $trace->getClient(); - - if (!$client->getIp()) { - throw new BadRequestHttpException('IP is required'); - } - - $data = [ - 'job_id' => $input->jobId - ]; - - $response = $this->createRequest( - method: 'POST', - url: 'https://'.$client->getIp().':8000/opengnsys/KillJob', - params: [ - 'json' => $data, - ], - token: $client->getToken(), - ); - - if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { - throw new BadRequestHttpException('Error killing job: '.$response['error']); - } - - $this->logger->info('Killing job', ['client' => $client->getId(), 'job_id' => $input->jobId]); - - $trace->setStatus(TraceStatus::CANCELLED); - $this->entityManager->persist($trace); + $this->killJobService->kill($trace, $input->jobId); $this->entityManager->flush(); - $inputData = [ - 'job_id' => $input->jobId, - 'client' => $client->getId(), - 'trace' => $trace->getUuid(), - 'command' => $trace->getCommand(), - ]; - - //$this->createService->__invoke($client, CommandTypes::KILL_JOB, TraceStatus::CANCELLED, $input->jobId, $inputData); - return new JsonResponse(data: $trace, status: Response::HTTP_OK); } } diff --git a/src/Service/Trace/KillJobService.php b/src/Service/Trace/KillJobService.php new file mode 100644 index 0000000..54328d1 --- /dev/null +++ b/src/Service/Trace/KillJobService.php @@ -0,0 +1,91 @@ +getClient(); + + if (!$client || !$client->getIp()) { + throw new BadRequestHttpException('IP is required'); + } + + try { + $response = $this->httpClient->request( + 'POST', + 'https://'.$client->getIp().':8000/opengnsys/KillJob', + $this->buildRequestOptions(['json' => ['job_id' => $jobId]], $client->getToken()) + ); + $result = json_decode($response->getContent(), true); + } catch (ClientExceptionInterface|ServerExceptionInterface|TransportExceptionInterface $e) { + $this->logger->error(sprintf('Error killing job on client %s: %s', $client->getIp(), $e->getMessage())); + throw new BadRequestHttpException('Error killing job: '.$e->getMessage()); + } + + if (isset($result['error']) && ($result['code'] ?? null) === Response::HTTP_INTERNAL_SERVER_ERROR) { + throw new BadRequestHttpException('Error killing job: '.$result['error']); + } + + $this->logger->info('Killing job', ['client' => $client->getId(), 'job_id' => $jobId]); + + $trace->setStatus(TraceStatus::CANCELLED); + $this->entityManager->persist($trace); + } + + private function buildRequestOptions(array $params, ?string $token): array + { + $options = array_merge($params, [ + 'headers' => [ + 'accept' => 'application/json', + 'Content-Type' => 'application/json', + 'Authorization' => $token, + ], + 'verify_peer' => false, + 'verify_host' => false, + 'timeout' => 10, + ]); + + if ($this->sslEnabled === 'true') { + $options['verify_peer'] = true; + $options['verify_host'] = false; + $options['cafile'] = '/opt/opengnsys/ogcore/etc/certificates/ca.crt'; + $options['local_cert'] = '/opt/opengnsys/ogcore/etc/certificates/ogcore.crt'; + $options['local_pk'] = '/opt/opengnsys/ogcore/etc/certificates/ogcore.key'; + } + + return $options; + } +} -- 2.40.1 From f08f3f6ff96405d6e7ed654976212d8b39c1de53 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Mon, 20 Jul 2026 11:25:50 +0200 Subject: [PATCH 20/39] fix(webhook): restaurar gestion de progreso y corregir error de sintaxis --- .../OgAgent/Webhook/StatusController.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index d57c0a8..99fea5b 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -112,12 +112,18 @@ class StatusController extends AbstractController $this->entityManager->flush(); } - $nfn = $data['nfn'] ?? null; - if (!$nfn) { - return new JsonResponse(data: 'Webhook finished', status: Response::HTTP_OK); + if (isset($data['progress'])){ + $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); + if ($trace){ + $trace->setProgress((int)($data['progress'] * 100)); + $this->entityManager->persist($trace); + $this->entityManager->flush(); + } } - switch ($nfn) { + $nfn = $data['nfn'] ?? null; + if ($nfn) { + switch ($nfn) { case 'START_SCRIPT': $trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]); if (!$trace) { @@ -408,6 +414,7 @@ class StatusController extends AbstractController } } break; + } } return new JsonResponse(data: 'Webhook finished', status: Response::HTTP_OK); -- 2.40.1 From a9228b00479bb77929f8c238f9ea5cad922dda81 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 21 Jul 2026 14:40:54 +0200 Subject: [PATCH 21/39] Fix: save script output for successful ExecScript webhooks --- src/Controller/OgAgent/Webhook/StatusController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 99fea5b..06a20c6 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -309,8 +309,8 @@ class StatusController extends AbstractController $trace->setStatus(TraceStatus::SUCCESS); } else { $trace->setStatus(TraceStatus::FAILED); - $trace->setOutput($data['der'] ?? ''); } + $trace->setOutput($data['der'] ?? ''); $trace->setFinishedAt(new \DateTime()); $this->entityManager->persist($trace); } else { -- 2.40.1 From 5144aed0dfe1f8433663f33aead39344c9ff33f4 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 21 Jul 2026 14:42:33 +0200 Subject: [PATCH 22/39] Fix: avoid hardcoding OG_LIVE status on REFRESH and RUN_SCRIPT completion --- src/Controller/OgAgent/Webhook/StatusController.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 06a20c6..ebd387c 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -319,9 +319,6 @@ class StatusController extends AbstractController } if ($client) { - if ($client->getStatus() === ClientStatus::BUSY) { - $client->setStatus(ClientStatus::OG_LIVE); - } $this->entityManager->persist($client); if (isset($data['cfg'])) { @@ -373,7 +370,6 @@ class StatusController extends AbstractController } if ($client) { - $client->setStatus(ClientStatus::OG_LIVE); $this->entityManager->persist($client); if (isset($data['cfg'])) { -- 2.40.1 From 2bebae09c147e76adce2214fe0f5c378ae99d1d2 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Wed, 22 Jul 2026 09:34:19 +0200 Subject: [PATCH 23/39] Fix: unconditionally update client status on ping if it doesn't match --- .../OgAgent/Webhook/StatusController.php | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index ebd387c..236b897 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -89,7 +89,7 @@ class StatusController extends AbstractController $this->logger->info('Heartbeat: client marked as busy', [ 'ip' => $data['iph'], 'previous_status' => $previousStatus, 'st' => $data['st'] ?? null, ]); - } elseif ($data['busy'] === false && $previousStatus === ClientStatus::BUSY) { + } elseif ($data['busy'] === false) { $idleStatusMap = [ 'OGL' => ClientStatus::OG_LIVE, 'LNX' => ClientStatus::LINUX, @@ -97,14 +97,17 @@ class StatusController extends AbstractController 'OSX' => ClientStatus::MACOS, ]; $newStatus = $idleStatusMap[$data['st'] ?? ''] ?? ClientStatus::OG_LIVE; - $client->setStatus($newStatus); - $this->logger->info('Heartbeat: client no longer busy', [ - 'ip' => $data['iph'], 'previous_status' => $previousStatus, 'new_status' => $newStatus, 'st' => $data['st'] ?? null, - ]); - } else { - $this->logger->info('Heartbeat: no status change', [ - 'ip' => $data['iph'], 'current_status' => $previousStatus, 'busy' => $data['busy'], 'st' => $data['st'] ?? null, - ]); + + if ($previousStatus !== $newStatus) { + $client->setStatus($newStatus); + $this->logger->info('Heartbeat: client status updated based on ping OS', [ + 'ip' => $data['iph'], 'previous_status' => $previousStatus, 'new_status' => $newStatus, 'st' => $data['st'] ?? null, + ]); + } else { + $this->logger->info('Heartbeat: no status change', [ + 'ip' => $data['iph'], 'current_status' => $previousStatus, 'busy' => $data['busy'], 'st' => $data['st'] ?? null, + ]); + } } } -- 2.40.1 From f87ebe5c9a5fd92f1b3a4eabb6b6a227602617f2 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Wed, 22 Jul 2026 10:32:13 +0200 Subject: [PATCH 24/39] Fix: support mapping agent loggedin status to OS session status --- src/Controller/OgAgent/Webhook/StatusController.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 236b897..60e76c2 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -96,6 +96,16 @@ class StatusController extends AbstractController 'WIN' => ClientStatus::WINDOWS, 'OSX' => ClientStatus::MACOS, ]; + + if (isset($data['loggedin']) && $data['loggedin'] === true) { + $idleStatusMap = [ + 'OGL' => ClientStatus::OG_LIVE, + 'LNX' => ClientStatus::LINUX_SESSION, + 'WIN' => ClientStatus::WINDOWS_SESSION, + 'OSX' => ClientStatus::MACOS_SESSION, + ]; + } + $newStatus = $idleStatusMap[$data['st'] ?? ''] ?? ClientStatus::OG_LIVE; if ($previousStatus !== $newStatus) { -- 2.40.1 From 4c2e43940a921ea7a646532c0edc013fea910fc0 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Wed, 22 Jul 2026 10:59:48 +0200 Subject: [PATCH 25/39] Fix: change Trace output column to LONGTEXT to avoid 500 errors on large output --- migrations/Version20260722100000.php | 26 ++++++++++++++++++++++++++ src/Entity/Trace.php | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 migrations/Version20260722100000.php diff --git a/migrations/Version20260722100000.php b/migrations/Version20260722100000.php new file mode 100644 index 0000000..21cdc13 --- /dev/null +++ b/migrations/Version20260722100000.php @@ -0,0 +1,26 @@ +addSql('ALTER TABLE trace CHANGE output output LONGTEXT DEFAULT NULL'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE trace CHANGE output output VARCHAR(255) DEFAULT NULL'); + } +} diff --git a/src/Entity/Trace.php b/src/Entity/Trace.php index 205b37b..7af4ac8 100644 --- a/src/Entity/Trace.php +++ b/src/Entity/Trace.php @@ -19,7 +19,7 @@ class Trace extends AbstractEntity #[ORM\Column(length: 255)] private ?string $status = null; - #[ORM\Column(length: 255, nullable: true)] + #[ORM\Column(type: Types::TEXT, nullable: true)] private ?string $output = null; #[ORM\Column(type: Types::DATETIME_MUTABLE)] -- 2.40.1 From 55ec37d02420a0bc0d93473d7e7f60428bd2f7cf Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Wed, 22 Jul 2026 13:13:17 +0200 Subject: [PATCH 26/39] Docs(CHANGELOG): document Trace output length fix --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd65937..d122785 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - Unidades organizativas: Ordenar hijos alfabéticamente por nombre. ### Fixed +- Base de datos (`Trace`): Ampliado el tipo de columna de `output` de string a TEXT para evitar errores HTTP 500 al recibir y almacenar salidas de comandos muy largas de los agentes de sistema operativos (OGAgent). - Tareas programadas (`Schedule`): Corregido bug en ejecución inmediata de comandos (Execute task right now). - Despliegue de imágenes: Eliminada restricción que impedía el despliegue en clientes con distintos tamaños de partición. - Perfiles de software: Corregido bug en la creación del perfil de software y actualizada entidad de imagen asociada. -- 2.40.1 From e2d1483134b42bb1619e6de5688386bda5d642a8 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 23 Jul 2026 14:08:19 +0200 Subject: [PATCH 27/39] Fix(agent-api): prevent duplicate traces due to webhook race condition for START_SCRIPT --- CHANGELOG.md | 6 +++++- src/Controller/OgAgent/RunScriptAction.php | 20 +++++++++++++++---- .../OgAgent/Webhook/StatusController.php | 6 ++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d122785..bfc3919 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,11 @@ # Changelog -## [1.9.1] - 2026-07-17 +## [1.9.2] - 2026-07-23 +### Fixed +- Webhook (`StatusController` y `RunScriptAction`): Solucionado un problema de condición de carrera al ejecutar scripts de forma no administrativa que creaba trazas duplicadas (una con estado Enviado y otra exitosa). El webhook `START_SCRIPT` ahora avanza correctamente el estado de la traza a `IN_PROGRESS` evitando conflictos con el proceso síncrono. + +## [1.9.1] - 2026-07-17 ### Added - Webhook (`StatusController`): Procesa la configuración de discos, particiones y caché en la respuesta del payload de la tarea `EjecutarScript`, guardándola automáticamente en base de datos. - Perfil de usuario: Añadido campo de preferencia de idioma (`language`). diff --git a/src/Controller/OgAgent/RunScriptAction.php b/src/Controller/OgAgent/RunScriptAction.php index d38f5f3..07a6a41 100644 --- a/src/Controller/OgAgent/RunScriptAction.php +++ b/src/Controller/OgAgent/RunScriptAction.php @@ -161,11 +161,23 @@ class RunScriptAction extends AbstractOgAgentController $this->entityManager->persist($client); $this->entityManager->flush(); - if ($existingTrace) { - $this->updateExistingTrace($existingTrace, $jobId, $inputData, $client); + // Check if START_SCRIPT webhook already created a trace for this job + $webhookTrace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $jobId]); + + if ($webhookTrace) { + $webhookTrace->setInput($inputData); + $this->entityManager->persist($webhookTrace); + if ($existingTrace && $existingTrace->getId() !== $webhookTrace->getId()) { + $this->entityManager->remove($existingTrace); + } + $this->entityManager->flush(); } else { - $status = ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) ? TraceStatus::SENT : TraceStatus::IN_PROGRESS; - $this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, $status, $jobId, $inputData); + if ($existingTrace) { + $this->updateExistingTrace($existingTrace, $jobId, $inputData, $client); + } else { + $status = ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) ? TraceStatus::SENT : TraceStatus::IN_PROGRESS; + $this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, $status, $jobId, $inputData); + } } } diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 60e76c2..b356c27 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -149,6 +149,12 @@ class StatusController extends AbstractController $this->entityManager->persist($client); $this->entityManager->flush(); } + } else { + if ($trace->getStatus() !== TraceStatus::SUCCESS && $trace->getStatus() !== TraceStatus::ERROR) { + $trace->setStatus(TraceStatus::IN_PROGRESS); + $this->entityManager->persist($trace); + $this->entityManager->flush(); + } } break; -- 2.40.1 From ddeea59173fc8fc1efac07bf3e58f39ad5e357aa Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Mon, 27 Jul 2026 18:52:06 +0200 Subject: [PATCH 28/39] Fix(RunScriptAction): default trace status to IN_PROGRESS for Windows/Linux to prevent duplicate traces in combination with ogagent --- src/Controller/OgAgent/RunScriptAction.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/OgAgent/RunScriptAction.php b/src/Controller/OgAgent/RunScriptAction.php index 07a6a41..cad400a 100644 --- a/src/Controller/OgAgent/RunScriptAction.php +++ b/src/Controller/OgAgent/RunScriptAction.php @@ -175,7 +175,7 @@ class RunScriptAction extends AbstractOgAgentController if ($existingTrace) { $this->updateExistingTrace($existingTrace, $jobId, $inputData, $client); } else { - $status = ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) ? TraceStatus::SENT : TraceStatus::IN_PROGRESS; + $status = TraceStatus::IN_PROGRESS; $this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, $status, $jobId, $inputData); } } -- 2.40.1 From f2f0e4117914cd1ec2688efefb1521bf899f2178 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 28 Jul 2026 00:32:15 +0200 Subject: [PATCH 29/39] Feat(OgBoot): prioritize client subnet over OU network settings for router and netmask extraction --- src/Controller/OgBoot/PxeBootFile/PostAction.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controller/OgBoot/PxeBootFile/PostAction.php b/src/Controller/OgBoot/PxeBootFile/PostAction.php index 6ed0b09..670419e 100644 --- a/src/Controller/OgBoot/PxeBootFile/PostAction.php +++ b/src/Controller/OgBoot/PxeBootFile/PostAction.php @@ -47,8 +47,8 @@ class PostAction extends AbstractOgBootController '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', + 'router' => $client->getSubnet()?->getRouter() ?? $client->getOrganizationalUnit()->getNetworkSettings()?->getRouter() ?? '', + 'netmask' => $client->getSubnet()?->getNetmask() ?? $client->getOrganizationalUnit()->getNetworkSettings()?->getNetmask() ?? '255.255.255.0', 'computer_name' => $client->getName(), 'netiface' => $client->getNetiface() ? $client->getNetiface() : $client->getOrganizationalUnit()->getNetworkSettings()?->getNetiface(), 'group' => $client->getOrganizationalUnit()->getName(), -- 2.40.1 From 7df739c17f3a94cc31cd05a1378dc95cfa3ce98b Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 28 Jul 2026 00:34:17 +0200 Subject: [PATCH 30/39] Docs: update CHANGELOG for OgBoot router extraction logic and trace race condition fix --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfc3919..e069495 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ ## [1.9.2] - 2026-07-23 ### Fixed -- Webhook (`StatusController` y `RunScriptAction`): Solucionado un problema de condición de carrera al ejecutar scripts de forma no administrativa que creaba trazas duplicadas (una con estado Enviado y otra exitosa). El webhook `START_SCRIPT` ahora avanza correctamente el estado de la traza a `IN_PROGRESS` evitando conflictos con el proceso síncrono. +- Webhook (`StatusController` y `RunScriptAction`): Solucionado el problema de condición de carrera que creaba trazas duplicadas al ejecutar scripts. Ahora se establece el estado a `IN_PROGRESS` de forma síncrona en `RunScriptAction` al enviar el script a clientes Windows/Linux, prescindiendo del problemático webhook asíncrono `START_SCRIPT`. +- OgBoot (`PostAction`): El enrutador y la máscara de red ahora se extraen prioritariamente de las propiedades de la Subred (Subnet) asociada al cliente, antes de consultar la configuración de red de la Unidad Organizativa, o usar los valores por defecto (vacío y `255.255.255.0`). ## [1.9.1] - 2026-07-17 ### Added -- 2.40.1 From cd1f7c0f237e642785080b6ecf3bc425a26904fb Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 28 Jul 2026 11:02:37 +0200 Subject: [PATCH 31/39] Fix(OgRepository): fix repo deletion payload mismatch and error handling --- src/Controller/OgRepository/Git/DeleteAction.php | 10 +++++++--- src/Dto/Input/DeleteRepositoryInput.php | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Controller/OgRepository/Git/DeleteAction.php b/src/Controller/OgRepository/Git/DeleteAction.php index 2d77207..ae9ce13 100644 --- a/src/Controller/OgRepository/Git/DeleteAction.php +++ b/src/Controller/OgRepository/Git/DeleteAction.php @@ -15,11 +15,15 @@ class DeleteAction extends AbstractOgRepositoryController { public function __invoke(ImageRepository $repository, DeleteRepositoryInput $input): JsonResponse { - $content = $this->createRequest('DELETE', 'http://'.$repository->getIp().':8006/ogrepository/v1/git/repositories/'.$input->repository, [ + if (empty($input->repositoryName)) { + throw new BadRequestHttpException('Repository name is required'); + } + + $content = $this->createRequest('DELETE', 'http://'.$repository->getIp().':8006/ogrepository/v1/git/repositories/'.$input->repositoryName, [ ]); - if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { - throw new BadRequestHttpException('Error deleting repository'); + if (isset($content['error'])) { + throw new BadRequestHttpException($content['details'] ?? $content['error']); } return new JsonResponse(data: [], status: Response::HTTP_OK); diff --git a/src/Dto/Input/DeleteRepositoryInput.php b/src/Dto/Input/DeleteRepositoryInput.php index 3ff1a48..fdd9992 100644 --- a/src/Dto/Input/DeleteRepositoryInput.php +++ b/src/Dto/Input/DeleteRepositoryInput.php @@ -9,5 +9,5 @@ final class DeleteRepositoryInput { #[Groups(['image-image-repository:write'])] #[ApiProperty(description: 'The repository name', example: "")] - public ?string $repository = null; + public ?string $repositoryName = null; } \ No newline at end of file -- 2.40.1 From 59be9044e4cf10ea67d12eedc4ddf1e0da83f7d3 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 28 Jul 2026 12:28:44 +0200 Subject: [PATCH 32/39] Fix(OgRepository): fix serialization group in DeleteRepositoryInput --- src/Dto/Input/DeleteRepositoryInput.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Dto/Input/DeleteRepositoryInput.php b/src/Dto/Input/DeleteRepositoryInput.php index fdd9992..f6a6459 100644 --- a/src/Dto/Input/DeleteRepositoryInput.php +++ b/src/Dto/Input/DeleteRepositoryInput.php @@ -7,7 +7,7 @@ use Symfony\Component\Serializer\Annotation\Groups; final class DeleteRepositoryInput { - #[Groups(['image-image-repository:write'])] + #[Groups(['repository:write'])] #[ApiProperty(description: 'The repository name', example: "")] public ?string $repositoryName = null; } \ No newline at end of file -- 2.40.1 From 3ced3ced8bbefcba69b73f83e660dd51e4814d4e Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Tue, 28 Jul 2026 12:32:41 +0200 Subject: [PATCH 33/39] Docs: update CHANGELOG for git repository deletion fix --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e069495..664cf2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixed - Webhook (`StatusController` y `RunScriptAction`): Solucionado el problema de condición de carrera que creaba trazas duplicadas al ejecutar scripts. Ahora se establece el estado a `IN_PROGRESS` de forma síncrona en `RunScriptAction` al enviar el script a clientes Windows/Linux, prescindiendo del problemático webhook asíncrono `START_SCRIPT`. - OgBoot (`PostAction`): El enrutador y la máscara de red ahora se extraen prioritariamente de las propiedades de la Subred (Subnet) asociada al cliente, antes de consultar la configuración de red de la Unidad Organizativa, o usar los valores por defecto (vacío y `255.255.255.0`). +- Repositorios Git (`DeleteAction` y `DeleteRepositoryInput`): Corregido el mapeo del payload de Angular aplicando el grupo de serialización correcto (`repository:write`), permitiendo recibir el nombre del repositorio a borrar. Además, se ha blindado el control de errores para capturar e informar correctamente de cualquier código de error (como 404) devuelto por `ogrepository`. ## [1.9.1] - 2026-07-17 ### Added -- 2.40.1 From 09eadaaad5a465db85aef0d6cac7a0998eb9f86b Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Wed, 29 Jul 2026 00:03:56 +0200 Subject: [PATCH 34/39] Updated mercure fields. Added finished_at --- src/EventListener/TraceStatusProgressNotifier.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/EventListener/TraceStatusProgressNotifier.php b/src/EventListener/TraceStatusProgressNotifier.php index 9737c46..efdb677 100644 --- a/src/EventListener/TraceStatusProgressNotifier.php +++ b/src/EventListener/TraceStatusProgressNotifier.php @@ -42,7 +42,12 @@ class TraceStatusProgressNotifier { $update = new Update( 'traces', - json_encode(['@id' => '/traces/' . $trace->getUuid(), 'status' => $trace->getStatus(), 'progress' => $trace->getProgress()]) + json_encode([ + '@id' => '/traces/' . $trace->getUuid(), + 'status' => $trace->getStatus(), + 'progress' => $trace->getProgress(), + 'finishedAt' => $trace->getFinishedAt()?->format(\DateTimeInterface::ATOM), + ]) ); $this->hub->publish($update); -- 2.40.1 From e5d6f468e31b96a795ff997399c11f13d35c2c09 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Wed, 29 Jul 2026 21:23:01 +0200 Subject: [PATCH 35/39] Updated Trace role view --- src/Controller/DeployImageAction.php | 87 ++++++-- ...UserAllowedOrganizationalUnitExtension.php | 61 +++++- tests/Functional/TraceVisibilityTest.php | 197 ++++++++++++++++++ 3 files changed, 317 insertions(+), 28 deletions(-) create mode 100644 tests/Functional/TraceVisibilityTest.php diff --git a/src/Controller/DeployImageAction.php b/src/Controller/DeployImageAction.php index 3cb0ca0..43d916c 100644 --- a/src/Controller/DeployImageAction.php +++ b/src/Controller/DeployImageAction.php @@ -28,6 +28,8 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; class DeployImageAction extends AbstractController { + private const NO_REPOSITORY = '__no_repository__'; + public function __construct( protected readonly EntityManagerInterface $entityManager, protected readonly HttpClientInterface $httpClient, @@ -118,28 +120,29 @@ class DeployImageAction extends AbstractController private function handleMulticastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array { $clientJobs = []; + $repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'multicast'); foreach ($input->clients as $client) { try { $inputData = $this->createMulticastInputData($input, $image, $client->getEntity()); - - try { - $this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity()); - } catch (\Exception $e) { + + $repositoryError = $repositoryErrors[$this->getRepositoryKey($client->getEntity())] ?? null; + + if ($repositoryError !== null) { $this->logger->warning('Error with OgRepository for client (multicast)', [ 'client_uuid' => $client->getEntity()->getUuid(), - 'error' => $e->getMessage() + 'error' => $repositoryError ]); - + if ($input->queue) { $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); } - + continue; } $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::MULTICAST, $trace); - + if ($jobId) { $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId; } @@ -164,32 +167,29 @@ class DeployImageAction extends AbstractController private function handleTorrentDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array { $clientJobs = []; + $repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'torrent'); foreach ($input->clients as $client) { try { $inputData = $this->createTorrentInputData($input, $image, $client->getEntity()); - - try { - $response = $this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity(), $this->httpClient); - - if (is_array($response) && isset($response['code']) && $response['code'] === 500) { - throw new \Exception('Error del servidor OgRepository: ' . ($response['error'] ?? 'Error desconocido') . ' - ' . ($response['details'] ?? '')); - } - } catch (\Exception $e) { + + $repositoryError = $repositoryErrors[$this->getRepositoryKey($client->getEntity())] ?? null; + + if ($repositoryError !== null) { $this->logger->warning('Error with OgRepository for client (torrent)', [ 'client_uuid' => $client->getEntity()->getUuid(), - 'error' => $e->getMessage() + 'error' => $repositoryError ]); - + if ($input->queue) { $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); } - + continue; } $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::TORRENT, $trace); - + if ($jobId) { $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId; } @@ -211,6 +211,53 @@ class DeployImageAction extends AbstractController return $clientJobs; } + /** + * La transmisión (multicast/torrent) se levanta en el ogRepository una sola vez, no por cliente. + * Como cada cliente puede resolver a un repositorio distinto, se agrupan por repositorio y se + * lanza una única petición por repositorio implicado. + * + * @return array error por clave de repositorio; sin entrada = transmisión creada + */ + private function prepareRepositoryTransmissions(DeployImageInput $input, ImageImageRepository $image, string $methodLabel): array + { + $clientsByRepository = []; + + foreach ($input->clients as $client) { + $clientsByRepository[$this->getRepositoryKey($client->getEntity())][] = $client; + } + + $errors = []; + + foreach ($clientsByRepository as $repositoryKey => $clients) { + if ($repositoryKey === self::NO_REPOSITORY) { + $errors[$repositoryKey] = 'Client has no repository assigned'; + continue; + } + + try { + $this->deployImageOgRepositoryAction->__invoke($input, $image, $clients[0]->getEntity()); + } catch (\Exception $e) { + $errors[$repositoryKey] = $e->getMessage(); + + $this->logger->warning('Error creating transmission in OgRepository', [ + 'method' => $methodLabel, + 'repository' => $repositoryKey, + 'affected_clients' => count($clients), + 'error' => $e->getMessage() + ]); + } + } + + return $errors; + } + + private function getRepositoryKey($client): string + { + $repository = $client->getRepository(); + + return $repository ? (string) $repository->getUuid() : self::NO_REPOSITORY; + } + private function processDeployment($client, DeployImageInput $input, ImageImageRepository $image, array $inputData, string $deployType, ?Trace $trace = null): ?string { $agentJobId = $this->deployImageOgAgentAction->__invoke($image, $input, $client, $deployType); diff --git a/src/Doctrine/UserAllowedOrganizationalUnitExtension.php b/src/Doctrine/UserAllowedOrganizationalUnitExtension.php index 54f081e..d1f9d7c 100644 --- a/src/Doctrine/UserAllowedOrganizationalUnitExtension.php +++ b/src/Doctrine/UserAllowedOrganizationalUnitExtension.php @@ -7,7 +7,9 @@ use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface; use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface; use ApiPlatform\Metadata\Operation; use App\Entity\OrganizationalUnit; +use App\Entity\Trace; use App\Entity\User; +use App\Model\UserGroupPermissions; use Doctrine\ORM\QueryBuilder; use Symfony\Bundle\SecurityBundle\Security; @@ -20,31 +22,74 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection } public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void { - $this->addWhere($queryBuilder, $resourceClass); + $this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass); } public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void { - $this->addWhere($queryBuilder, $resourceClass); + $this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass); } - private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void + private function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass): void { /** @var User $user */ $user = $this->security->getUser(); - if (OrganizationalUnit::class !== $resourceClass || null === $user || in_array('ROLE_SUPER_ADMIN', $user->getRoles())) { + if (null === $user || in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $user->getRoles())) { return; } + switch ($resourceClass) { + case OrganizationalUnit::class: + $this->addOrganizationalUnitWhere($queryBuilder, $user); + break; + case Trace::class: + $this->addTraceWhere($queryBuilder, $queryNameGenerator, $user); + break; + } + } + + private function addOrganizationalUnitWhere(QueryBuilder $queryBuilder, User $user): void + { + $rootAlias = $queryBuilder->getRootAliases()[0]; + $queryBuilder->andWhere(sprintf('%s.id in (:ou)', $rootAlias)); + $queryBuilder->setParameter('ou', $this->getAllowedOrganizationalUnitIds($user)); + } + + /** + * Una traza pertenece a un cliente, y el cliente a una unidad organizativa: el usuario solo puede + * ver las trazas de los equipos de las unidades organizativas que tiene asignadas (y sus hijas). + */ + private function addTraceWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, User $user): void + { + $rootAlias = $queryBuilder->getRootAliases()[0]; + $organizationalUnitIds = $this->getAllowedOrganizationalUnitIds($user); + + if (empty($organizationalUnitIds)) { + $queryBuilder->andWhere('1 = 0'); + + return; + } + + $clientAlias = $queryNameGenerator->generateJoinAlias('client'); + + $queryBuilder->innerJoin(sprintf('%s.client', $rootAlias), $clientAlias); + $queryBuilder->andWhere(sprintf('%s.organizationalUnit in (:trace_ou)', $clientAlias)); + $queryBuilder->setParameter('trace_ou', $organizationalUnitIds); + } + + /** + * @return int[] + */ + private function getAllowedOrganizationalUnitIds(User $user): array + { $organizationalUnitIds = []; + foreach ($user->getAllowedOrganizationalUnits() as $allowedOrganizationalUnit) { $this->addOrganizationalUnitAndChildrenIds($allowedOrganizationalUnit, $organizationalUnitIds); } - $rootAlias = $queryBuilder->getRootAliases()[0]; - $queryBuilder->andWhere(sprintf('%s.id in (:ou)', $rootAlias)); - $queryBuilder->setParameter('ou', $organizationalUnitIds); + return $organizationalUnitIds; } private function addOrganizationalUnitAndChildrenIds(OrganizationalUnit $organizationalUnit, array &$organizationalUnitIds): void @@ -58,4 +103,4 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection } } -} \ No newline at end of file +} diff --git a/tests/Functional/TraceVisibilityTest.php b/tests/Functional/TraceVisibilityTest.php new file mode 100644 index 0000000..1b2374f --- /dev/null +++ b/tests/Functional/TraceVisibilityTest.php @@ -0,0 +1,197 @@ + $username, 'roles' => [$role]]); + + return $this->getToken([ + 'username' => $username, + 'password' => UserFactory::PLAIN_PASSWORD, + ]); + } + + private function as(string $token): ApiClient + { + return $this->createClientWithCredentials($token); + } + + private function getEntityManager(): EntityManagerInterface + { + return static::getContainer()->get('doctrine')->getManager(); + } + + private function createOrganizationalUnit(string $name, ?OrganizationalUnit $parent = null): OrganizationalUnit + { + $organizationalUnit = new OrganizationalUnit(); + $organizationalUnit->setName($name); + $organizationalUnit->setType(OrganizationalUnitTypes::CLASSROOM); + $organizationalUnit->setParent($parent); + + $this->getEntityManager()->persist($organizationalUnit); + + return $organizationalUnit; + } + + /** Crea una traza asociada a un cliente de la OU indicada y devuelve su uuid. */ + private function createTrace(?OrganizationalUnit $organizationalUnit, string $command): string + { + $entityManager = $this->getEntityManager(); + + $trace = new Trace(); + $trace->setCommand($command); + $trace->setStatus(TraceStatus::SUCCESS); + $trace->setExecutedAt(new \DateTime()); + + if ($organizationalUnit !== null) { + $client = new Client(); + $client->setName('client-'.$command); + $client->setMaintenance(false); + $client->setOrganizationalUnit($organizationalUnit); + $entityManager->persist($client); + + $trace->setClient($client); + } + + $entityManager->persist($trace); + + return (string) $trace->getUuid(); + } + + /** + * Escenario común: una OU permitida con una OU hija, y otra OU ajena al usuario. + * + * @return array{allowed: string, child: string, foreign: string, orphan: string} + */ + private function createScenario(string $username): array + { + $entityManager = $this->getEntityManager(); + + $allowedOrganizationalUnit = $this->createOrganizationalUnit('trace-allowed-ou'); + $childOrganizationalUnit = $this->createOrganizationalUnit('trace-child-ou', $allowedOrganizationalUnit); + $foreignOrganizationalUnit = $this->createOrganizationalUnit('trace-foreign-ou'); + + $traces = [ + 'allowed' => $this->createTrace($allowedOrganizationalUnit, 'allowed'), + 'child' => $this->createTrace($childOrganizationalUnit, 'child'), + 'foreign' => $this->createTrace($foreignOrganizationalUnit, 'foreign'), + 'orphan' => $this->createTrace(null, 'orphan'), + ]; + + /** @var User $user */ + $user = $entityManager->getRepository(User::class)->findOneBy(['username' => $username]); + $user->addAllowedOrganizationalUnit($allowedOrganizationalUnit); + $entityManager->persist($user); + + $entityManager->flush(); + + return $traces; + } + + /** @return string[] uuids devueltos por GET /traces */ + private function getTraceUuids(string $token): array + { + $response = $this->as($token)->request('GET', '/traces'); + $this->assertResponseIsSuccessful(); + + return array_map( + static fn (array $trace): string => $trace['uuid'], + $response->toArray()['hydra:member'] + ); + } + + /** El super-admin sigue viendo todas las trazas, incluidas las que no tienen cliente. */ + public function testSuperAdminSeesEveryTrace(): void + { + $token = $this->tokenFor(self::SA_USER, UserGroupPermissions::ROLE_SUPER_ADMIN); + $traces = $this->createScenario(self::SA_USER); + + $uuids = $this->getTraceUuids($token); + + $this->assertContains($traces['allowed'], $uuids); + $this->assertContains($traces['child'], $uuids); + $this->assertContains($traces['foreign'], $uuids); + $this->assertContains($traces['orphan'], $uuids); + } + + /** El resto de roles solo ven las trazas de sus OUs permitidas y de las hijas de éstas. */ + public function testOperatorOnlySeesTracesOfAllowedOrganizationalUnits(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $traces = $this->createScenario(self::OP_USER); + + $uuids = $this->getTraceUuids($token); + + $this->assertContains($traces['allowed'], $uuids, 'Debe ver las trazas de su OU'); + $this->assertContains($traces['child'], $uuids, 'Debe ver las trazas de las OUs hijas'); + $this->assertNotContains($traces['foreign'], $uuids, 'No debe ver las trazas de otras OUs'); + $this->assertNotContains($traces['orphan'], $uuids, 'No debe ver trazas sin cliente'); + } + + /** El filtro también se aplica al item: una traza ajena no es accesible por uuid. */ + public function testOperatorCannotFetchForeignTraceItem(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $traces = $this->createScenario(self::OP_USER); + + $this->as($token)->request('GET', '/traces/'.$traces['allowed']); + $this->assertResponseIsSuccessful(); + + $this->as($token)->request('GET', '/traces/'.$traces['foreign']); + $this->assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND); + } + + /** Filtrar por un cliente ajeno no permite saltarse la restricción. */ + public function testOperatorCannotBypassFilterWithClientFilter(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + $traces = $this->createScenario(self::OP_USER); + + $foreignTrace = $this->getEntityManager()->getRepository(Trace::class) + ->findOneBy(['uuid' => $traces['foreign']]); + + $response = $this->as($token)->request('GET', '/traces', [ + 'query' => ['client.id' => $foreignTrace->getClient()->getId()], + ]); + $this->assertResponseIsSuccessful(); + + $this->assertSame([], $response->toArray()['hydra:member']); + } + + /** Un usuario sin ninguna OU asignada no ve ninguna traza. */ + public function testUserWithoutOrganizationalUnitsSeesNoTraces(): void + { + $token = $this->tokenFor(self::OP_USER, UserGroupPermissions::ROLE_ORGANIZATIONAL_UNIT_OPERATOR); + + $this->createTrace($this->createOrganizationalUnit('trace-unassigned-ou'), 'unassigned'); + $this->getEntityManager()->flush(); + + $this->assertSame([], $this->getTraceUuids($token)); + } +} -- 2.40.1 From bca1f4392f6af9d7c046f0438e3425299ef1deca Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 30 Jul 2026 09:48:51 +0200 Subject: [PATCH 36/39] Fix(browser): run bootOs silently by changing command+output to command --- CHANGELOG.md | 1 + templates/browser/main.html.twig | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 664cf2a..48cf3a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## [1.9.2] - 2026-07-23 ### Fixed +- Menú del navegador (`main.html.twig`): Modificada la acción por defecto para el arranque de sistemas operativos. Se ha cambiado de `command+output:` a `command:` para evitar que se abra la ventana emergente de salida de comandos, ofreciendo una experiencia de arranque más limpia. - Webhook (`StatusController` y `RunScriptAction`): Solucionado el problema de condición de carrera que creaba trazas duplicadas al ejecutar scripts. Ahora se establece el estado a `IN_PROGRESS` de forma síncrona en `RunScriptAction` al enviar el script a clientes Windows/Linux, prescindiendo del problemático webhook asíncrono `START_SCRIPT`. - OgBoot (`PostAction`): El enrutador y la máscara de red ahora se extraen prioritariamente de las propiedades de la Subred (Subnet) asociada al cliente, antes de consultar la configuración de red de la Unidad Organizativa, o usar los valores por defecto (vacío y `255.255.255.0`). - Repositorios Git (`DeleteAction` y `DeleteRepositoryInput`): Corregido el mapeo del payload de Angular aplicando el grupo de serialización correcto (`repository:write`), permitiendo recibir el nombre del repositorio a borrar. Además, se ha blindado el control de errores para capturar e informar correctamente de cualquier código de error (como 404) devuelto por `ogrepository`. diff --git a/templates/browser/main.html.twig b/templates/browser/main.html.twig index 69ac50f..8a53e41 100644 --- a/templates/browser/main.html.twig +++ b/templates/browser/main.html.twig @@ -575,7 +575,7 @@ {% if partition.operativeSystem %} - Arrancar {{ partition.operativeSystem.name }} -- 2.40.1 From c29af77466caac3f5c34018d77cd1b0e9ec64143 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 30 Jul 2026 11:10:42 +0200 Subject: [PATCH 37/39] Feat(mercure): broadcast output and finishedAt in trace events for real-time logs --- CHANGELOG.md | 3 +++ src/EventListener/TraceStatusProgressNotifier.php | 3 +++ 2 files changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48cf3a5..2bbcc00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## [1.9.2] - 2026-07-23 +### Added +- Mercure (`TraceStatusProgressNotifier`): Publish `output` and `finishedAt` fields in Mercure traces event for real-time log updates without page reload. + ### Fixed - Menú del navegador (`main.html.twig`): Modificada la acción por defecto para el arranque de sistemas operativos. Se ha cambiado de `command+output:` a `command:` para evitar que se abra la ventana emergente de salida de comandos, ofreciendo una experiencia de arranque más limpia. - Webhook (`StatusController` y `RunScriptAction`): Solucionado el problema de condición de carrera que creaba trazas duplicadas al ejecutar scripts. Ahora se establece el estado a `IN_PROGRESS` de forma síncrona en `RunScriptAction` al enviar el script a clientes Windows/Linux, prescindiendo del problemático webhook asíncrono `START_SCRIPT`. diff --git a/src/EventListener/TraceStatusProgressNotifier.php b/src/EventListener/TraceStatusProgressNotifier.php index efdb677..8c97011 100644 --- a/src/EventListener/TraceStatusProgressNotifier.php +++ b/src/EventListener/TraceStatusProgressNotifier.php @@ -47,6 +47,7 @@ class TraceStatusProgressNotifier 'status' => $trace->getStatus(), 'progress' => $trace->getProgress(), 'finishedAt' => $trace->getFinishedAt()?->format(\DateTimeInterface::ATOM), + 'output' => $trace->getOutput() ]) ); $this->hub->publish($update); @@ -55,6 +56,8 @@ class TraceStatusProgressNotifier 'client' => $trace->getUuid(), 'status' => $trace->getStatus(), 'progress' => $trace->getProgress(), + 'finishedAt' => $trace->getFinishedAt()?->format(\DateTimeInterface::ATOM), + 'output' => $trace->getOutput() ? substr($trace->getOutput(), 0, 200) . '...' : null, ]); } } \ No newline at end of file -- 2.40.1 From 6dd428412fd8e9a5d0e87d5a2ed43a9fa12aa507 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Thu, 30 Jul 2026 12:59:53 +0200 Subject: [PATCH 38/39] Updated deploy torrent. Refactor. --- src/Controller/DeployImageAction.php | 258 +++++++------- .../OgAgent/AbstractOgAgentController.php | 21 ++ src/Controller/OgAgent/DeployImageAction.php | 51 ++- tests/Functional/DeployImageTorrentTest.php | 317 ++++++++++++++++++ 4 files changed, 501 insertions(+), 146 deletions(-) create mode 100644 tests/Functional/DeployImageTorrentTest.php diff --git a/src/Controller/DeployImageAction.php b/src/Controller/DeployImageAction.php index 43d916c..d1cfe13 100644 --- a/src/Controller/DeployImageAction.php +++ b/src/Controller/DeployImageAction.php @@ -89,126 +89,152 @@ class DeployImageAction extends AbstractController private function handleUnicastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array { - $clientJobs = []; - - foreach ($input->clients as $client) { - try { - $inputData = $this->createInputData($input, $image, $client->getEntity()); - $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::UNICAST, $trace); - - if ($jobId) { - $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId; - } - } catch (\Exception $e) { - $this->logger->warning('Error deploying to client (unicast)', [ - 'client_uuid' => $client->getEntity()->getUuid(), - 'error' => $e->getMessage() - ]); - - if ($input->queue) { - $inputData = $this->createInputData($input, $image, $client->getEntity()); - $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); - } - - continue; - } - } - - return $clientJobs; + return $this->processDeployments($input, $image, [], 'unicast', $trace); } private function handleMulticastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array { - $clientJobs = []; $repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'multicast'); - foreach ($input->clients as $client) { + return $this->processDeployments($input, $image, $repositoryErrors, 'multicast', $trace); + } + + private function handleTorrentDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array + { + $repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'torrent'); + + return $this->processDeployments($input, $image, $repositoryErrors, 'torrent', $trace); + } + + /** + * Reparte la orden de despliegue entre todos los equipos en dos fases: primero se lanzan todas + * las peticiones a los ogAgent (que viajan en paralelo, porque el HttpClient de Symfony no + * bloquea hasta que se lee la respuesta) y después se recogen los resultados. + * + * Antes se hacía equipo por equipo, así que el tiempo total era la suma de todos y cada equipo + * apagado se comía su timeout completo antes de pasar al siguiente. + * + * @param array $repositoryErrors error de transmisión por clave de repositorio + */ + private function processDeployments( + DeployImageInput $input, + ImageImageRepository $image, + array $repositoryErrors, + string $methodLabel, + ?Trace $trace = null + ): array { + $clientJobs = []; + $pending = []; + + // Fase 1: lanzar la orden a todos los ogAgent sin esperar su respuesta. + foreach ($input->clients as $clientOutput) { + $client = $clientOutput->getEntity(); + $inputData = $this->createInputDataForMethod($input, $image, $client); + + $repositoryError = $repositoryErrors[$this->getRepositoryKey($client)] ?? null; + + if ($repositoryError !== null) { + $this->logger->warning(sprintf('Error with OgRepository for client (%s)', $methodLabel), [ + 'client_uuid' => $client->getUuid(), + 'error' => $repositoryError + ]); + + $this->queueDeployment($client, $input, $inputData); + + continue; + } + try { - $inputData = $this->createMulticastInputData($input, $image, $client->getEntity()); - - $repositoryError = $repositoryErrors[$this->getRepositoryKey($client->getEntity())] ?? null; - - if ($repositoryError !== null) { - $this->logger->warning('Error with OgRepository for client (multicast)', [ - 'client_uuid' => $client->getEntity()->getUuid(), - 'error' => $repositoryError - ]); - - if ($input->queue) { - $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); - } - - continue; - } - - $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::MULTICAST, $trace); - - if ($jobId) { - $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId; - } + $pending[] = [ + 'client' => $client, + 'inputData' => $inputData, + 'response' => $this->deployImageOgAgentAction->startDeploy($image, $input, $client), + ]; } catch (\Exception $e) { - $this->logger->warning('Error deploying to client (multicast)', [ - 'client_uuid' => $client->getEntity()->getUuid(), + $this->logger->warning(sprintf('Error deploying to client (%s)', $methodLabel), [ + 'client_uuid' => $client->getUuid(), 'error' => $e->getMessage() ]); - - if ($input->queue) { - $inputData = $this->createMulticastInputData($input, $image, $client->getEntity()); - $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); - } - + + $this->queueDeployment($client, $input, $inputData); + } + } + + // Fase 2: recoger las respuestas, que han ido avanzando en paralelo. + foreach ($pending as ['client' => $client, 'inputData' => $inputData, 'response' => $response]) { + try { + $jobId = $this->deployImageOgAgentAction->completeDeploy($response, $client); + } catch (\Exception $e) { + $this->logger->warning(sprintf('Error deploying to client (%s)', $methodLabel), [ + 'client_uuid' => $client->getUuid(), + 'error' => $e->getMessage() + ]); + + $this->queueDeployment($client, $input, $inputData); + continue; } + + $this->registerDeployment($client, $input, $inputData, $jobId, $trace); + + if ($jobId) { + $clientJobs[(string) '/clients/' . $client->getUuid()] = $jobId; + } } return $clientJobs; } - private function handleTorrentDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array + /** Deja el despliegue en cola para que lo reintente ExecutePendingTracesCommand. */ + private function queueDeployment($client, DeployImageInput $input, array $inputData): void { - $clientJobs = []; - $repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'torrent'); - - foreach ($input->clients as $client) { - try { - $inputData = $this->createTorrentInputData($input, $image, $client->getEntity()); - - $repositoryError = $repositoryErrors[$this->getRepositoryKey($client->getEntity())] ?? null; - - if ($repositoryError !== null) { - $this->logger->warning('Error with OgRepository for client (torrent)', [ - 'client_uuid' => $client->getEntity()->getUuid(), - 'error' => $repositoryError - ]); - - if ($input->queue) { - $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); - } - - continue; - } - - $jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::TORRENT, $trace); - - if ($jobId) { - $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId; - } - } catch (\Exception $e) { - $this->logger->warning('Error deploying to client (torrent)', [ - 'client_uuid' => $client->getEntity()->getUuid(), - 'error' => $e->getMessage() - ]); - - if ($input->queue) { - $inputData = $this->createTorrentInputData($input, $image, $client->getEntity()); - $this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); - } - - continue; - } + if (!$input->queue) { + return; } - return $clientJobs; + $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); + } + + /** Anota la traza del despliegue: en curso si el ogAgent aceptó la orden, en cola si no. */ + private function registerDeployment($client, DeployImageInput $input, array $inputData, ?string $jobId, ?Trace $trace = null): void + { + if (!$jobId) { + if (!$input->queue) { + return; + } + + if ($trace) { + $trace->setStatus(TraceStatus::PENDING); + $trace->setJobId(null); + $trace->setInput($inputData); + $this->entityManager->persist($trace); + $this->entityManager->flush(); + } else { + $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); + } + + return; + } + + if ($trace) { + $trace->setStatus(TraceStatus::IN_PROGRESS); + $trace->setJobId($jobId); + $trace->setInput($inputData); + $this->entityManager->persist($trace); + $this->entityManager->flush(); + } else { + $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $jobId, $inputData); + } + } + + private function createInputDataForMethod(DeployImageInput $input, ImageImageRepository $image, $client): array + { + return match ($input->method) { + DeployMethodTypes::MULTICAST, DeployMethodTypes::MULTICAST_UFTP, DeployMethodTypes::MULTICAST_UFTP_DIRECT, + DeployMethodTypes::MULTICAST_UDPCAST, DeployMethodTypes::MULTICAST_UDPCAST_DIRECT => $this->createMulticastInputData($input, $image, $client), + DeployMethodTypes::TORRENT => $this->createTorrentInputData($input, $image, $client), + default => $this->createInputData($input, $image, $client), + }; } /** @@ -258,38 +284,6 @@ class DeployImageAction extends AbstractController return $repository ? (string) $repository->getUuid() : self::NO_REPOSITORY; } - private function processDeployment($client, DeployImageInput $input, ImageImageRepository $image, array $inputData, string $deployType, ?Trace $trace = null): ?string - { - $agentJobId = $this->deployImageOgAgentAction->__invoke($image, $input, $client, $deployType); - - if (!$agentJobId) { - if ($input->queue) { - if ($trace) { - $trace->setStatus(TraceStatus::PENDING); - $trace->setJobId(null); - $trace->setInput($inputData); - $this->entityManager->persist($trace); - $this->entityManager->flush(); - } else { - $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData); - } - } - return null; - } - - if ($trace) { - $trace->setStatus(TraceStatus::IN_PROGRESS); - $trace->setJobId($agentJobId); - $trace->setInput($inputData); - $this->entityManager->persist($trace); - $this->entityManager->flush(); - } else { - $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $agentJobId, $inputData); - } - - return $agentJobId; - } - private function createInputData(DeployImageInput $input, ImageImageRepository $image, $client): array { return [ diff --git a/src/Controller/OgAgent/AbstractOgAgentController.php b/src/Controller/OgAgent/AbstractOgAgentController.php index 92aab6a..166b708 100644 --- a/src/Controller/OgAgent/AbstractOgAgentController.php +++ b/src/Controller/OgAgent/AbstractOgAgentController.php @@ -17,6 +17,7 @@ use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; +use Symfony\Contracts\HttpClient\ResponseInterface; #[AsController] abstract class AbstractOgAgentController extends AbstractController @@ -71,6 +72,26 @@ abstract class AbstractOgAgentController extends AbstractController try { $response = $this->httpClient->request($method, $url, $params); + } catch (TransportExceptionInterface $e) { + $this->logger->error(sprintf('Transport error in request to %s: %s', $url, $e->getMessage())); + + return [ + 'code' => Response::HTTP_INTERNAL_SERVER_ERROR, + 'error' => 'Transport error', + 'details' => $e->getMessage(), + ]; + } + + return $this->readResponse($response, $url); + } + + /** + * Interpreta la respuesta del ogAgent. Está separado de createRequest() para poder lanzar + * varias peticiones a la vez y leerlas después, en vez de esperar a cada una por turno. + */ + public function readResponse(ResponseInterface $response, string $url): array + { + try { return json_decode($response->getContent(), true); } catch (ClientExceptionInterface | ServerExceptionInterface $e) { if ($e->getResponse() && $e->getResponse()->getStatusCode() === 409) { diff --git a/src/Controller/OgAgent/DeployImageAction.php b/src/Controller/OgAgent/DeployImageAction.php index 9677a38..4814a27 100644 --- a/src/Controller/OgAgent/DeployImageAction.php +++ b/src/Controller/OgAgent/DeployImageAction.php @@ -14,7 +14,8 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; -use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; +use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; +use Symfony\Contracts\HttpClient\ResponseInterface; class DeployImageAction extends AbstractOgAgentController { @@ -25,6 +26,22 @@ class DeployImageAction extends AbstractOgAgentController * @throws ServerExceptionInterface */ public function __invoke(ImageImageRepository $imageImageRepository, DeployImageInput $input, Client $client, ?string $method = null) + { + return $this->completeDeploy( + $this->startDeploy($imageImageRepository, $input, $client), + $client + ); + } + + /** + * Envía la orden al ogAgent sin esperar la respuesta. El HttpClient de Symfony gestiona las + * peticiones de forma concurrente mientras no se lea su contenido, así que lanzando primero + * todas las de un despliegue el coste total pasa de ser la suma de todos los equipos a ser + * el del equipo más lento. + * + * @throws TransportExceptionInterface + */ + public function startDeploy(ImageImageRepository $imageImageRepository, DeployImageInput $input, Client $client): ResponseInterface { $image = $imageImageRepository->getImage(); @@ -77,26 +94,32 @@ class DeployImageAction extends AbstractOgAgentController $url = 'https://'.$client->getIp().':8000/opengnsys/RestaurarImagen'; - $response = $this->createRequest( - method: 'POST', - url: $url, - params: [ - 'json' => $data, - ], - token: $client->getToken(), - ); - - $this->logger->info('Deploying image', [ - 'image' => $imageImageRepository->getName(), + $this->logger->info('Deploying image', [ + 'image' => $imageImageRepository->getName(), 'repository' => $repository->getIp(), 'client' => $client->getIp() ]); - if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { + return $this->httpClient->request( + method: 'POST', + url: $url, + options: $this->buildRequestOptions(['json' => $data], $client->getToken()), + ); + } + + /** + * Lee la respuesta de un ogAgent y devuelve su job_id, o null si el equipo no ha aceptado la + * orden (por ejemplo un 409 porque ya está ocupado). + */ + public function completeDeploy(ResponseInterface $response, Client $client): ?string + { + $content = $this->readResponse($response, (string) $response->getInfo('url')); + + if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { throw new BadRequestHttpException('Error deploying image'); } - $jobId = $response['job_id']; + $jobId = $content['job_id'] ?? null; $client->setStatus(ClientStatus::BUSY); $this->entityManager->persist($client); diff --git a/tests/Functional/DeployImageTorrentTest.php b/tests/Functional/DeployImageTorrentTest.php new file mode 100644 index 0000000..25c3fd0 --- /dev/null +++ b/tests/Functional/DeployImageTorrentTest.php @@ -0,0 +1,317 @@ +get('doctrine')->getManager(); + } + + /** + * Sustituye el cliente HTTP por un mock que registra cada URL invocada, para poder contar + * cuántas peticiones se hacen al ogRepository y cuántas a los ogAgent. + */ + private function mockHttpClient(): void + { + $this->requestedUrls = []; + + $mock = new MockHttpClient(function (string $method, string $url): MockResponse { + $this->requestedUrls[] = $url; + + if (str_contains($url, '/ogrepository/v1/')) { + return new MockResponse( + json_encode(['success' => true, 'details' => 'Tracker and Seeder serving image correctly']), + ['response_headers' => ['content-type' => 'application/json']] + ); + } + + return new MockResponse( + json_encode(['job_id' => 'RestaurarImagen-'.substr(md5($url.count($this->requestedUrls)), 0, 8)]), + ['response_headers' => ['content-type' => 'application/json']] + ); + }); + + static::getContainer()->set('http_client', $mock); + } + + /** + * Igual que mockHttpClient(), pero además anota el orden en que se crean las peticiones y en + * que se leen sus respuestas. El cuerpo se entrega con un generador, que MockHttpClient sólo + * consume cuando alguien lee la respuesta: así se distingue "lanzada" de "leída". + */ + private function mockHttpClientTrackingOrder(): void + { + $this->requestedUrls = []; + $this->callOrder = []; + + $mock = new MockHttpClient(function (string $method, string $url): MockResponse { + $this->requestedUrls[] = $url; + + $isAgent = str_contains($url, '/opengnsys/RestaurarImagen'); + + if ($isAgent) { + $this->callOrder[] = 'start:'.$url; + } + + $body = function () use ($url, $isAgent): \Generator { + if ($isAgent) { + $this->callOrder[] = 'read:'.$url; + + yield json_encode(['job_id' => 'job-'.substr(md5($url), 0, 8)]); + + return; + } + + yield json_encode(['success' => true, 'details' => 'Tracker and Seeder serving image correctly']); + }; + + return new MockResponse($body(), ['response_headers' => ['content-type' => 'application/json']]); + }); + + static::getContainer()->set('http_client', $mock); + } + + /** @return array{image: ImageImageRepository, clients: Client[]} */ + private function createDeployScenario(int $numberOfClients, ?ImageRepository $repository = null): array + { + $entityManager = $this->getEntityManager(); + + $organizationalUnit = new OrganizationalUnit(); + $organizationalUnit->setName('deploy-ou-'.uniqid()); + $organizationalUnit->setType(OrganizationalUnitTypes::CLASSROOM); + $entityManager->persist($organizationalUnit); + + if ($repository === null) { + $repository = new ImageRepository(); + $repository->setName('repo-'.uniqid()); + $repository->setIp('10.200.0.'.(++$this->repositoryIpCounter)); + $entityManager->persist($repository); + } + + $image = new Image(); + $image->setName('image-'.uniqid()); + $image->setType('monolithic'); + $image->setIsGlobal(false); + $entityManager->persist($image); + + $imageImageRepository = new ImageImageRepository(); + $imageImageRepository->setImage($image); + $imageImageRepository->setRepository($repository); + $imageImageRepository->setName($image->getName()); + $imageImageRepository->setStatus(ImageStatus::SUCCESS); + $imageImageRepository->setImageFullsum(md5($image->getName())); + $entityManager->persist($imageImageRepository); + + $clients = []; + for ($i = 0; $i < $numberOfClients; $i++) { + $client = new Client(); + $client->setName('deploy-client-'.$i.'-'.uniqid()); + $client->setMaintenance(false); + $client->setOrganizationalUnit($organizationalUnit); + $client->setIp('10.'.intdiv($this->clientIpCounter, 254).'.1.'.(($this->clientIpCounter++ % 254) + 1)); + $client->setToken('token-'.$i); + $client->setRepository($repository); + $entityManager->persist($client); + + $clients[] = $client; + } + + $entityManager->flush(); + + return ['image' => $imageImageRepository, 'clients' => $clients]; + } + + /** Lanza el despliegue torrent y devuelve el código de respuesta. */ + private function deployTorrent(ImageImageRepository $image, array $clients): int + { + if ($this->adminToken === null) { + UserFactory::createOne(['username' => self::ADMIN_USER, 'roles' => [UserGroupPermissions::ROLE_SUPER_ADMIN]]); + $this->adminToken = $this->getToken([ + 'username' => self::ADMIN_USER, + 'password' => UserFactory::PLAIN_PASSWORD, + ]); + } + + $token = $this->adminToken; + + $clientIris = array_map( + static fn (Client $client): string => '/clients/'.$client->getUuid(), + $clients + ); + + $imageUuid = (string) $image->getUuid(); + + // El mock debe instalarse sobre el kernel que atenderá la petición: createClient() lo reinicia. + $apiClient = $this->createClientWithCredentials($token); + + if ($this->trackCallOrder) { + $this->mockHttpClientTrackingOrder(); + } else { + $this->mockHttpClient(); + } + + $apiClient->request('POST', '/image-image-repositories/'.$imageUuid.'/deploy-image', [ + 'json' => [ + 'type' => 'monolithic', + 'method' => DeployMethodTypes::TORRENT, + 'clients' => $clientIris, + 'diskNumber' => 1, + 'partitionNumber' => 1, + 'p2pMode' => OrganizationalUnitP2PModes::P2P_MODE_PEER, + 'p2pTime' => 0, + ], + ]); + + return $apiClient->getResponse()->getStatusCode(); + } + + /** @return string[] */ + private function repositoryRequests(): array + { + return array_values(array_filter( + $this->requestedUrls, + static fn (string $url): bool => str_contains($url, '/ogrepository/v1/') + )); + } + + /** @return string[] */ + private function agentRequests(): array + { + return array_values(array_filter( + $this->requestedUrls, + static fn (string $url): bool => str_contains($url, '/opengnsys/RestaurarImagen') + )); + } + + /** Con 10 equipos solo debe crearse la transmisión una vez, y avisarse a los 10 ogAgent. */ + public function testTorrentDeploymentCallsRepositoryOncePerDeployment(): void + { + $scenario = $this->createDeployScenario(10); + + $statusCode = $this->deployTorrent($scenario['image'], $scenario['clients']); + $this->assertSame(200, $statusCode); + + $this->assertCount( + 1, + $this->repositoryRequests(), + 'La transmisión p2p debe crearse una sola vez, no una por equipo' + ); + $this->assertStringContainsString('/ogrepository/v1/p2p', $this->repositoryRequests()[0]); + $this->assertCount(10, $this->agentRequests(), 'Cada equipo debe recibir su orden de despliegue'); + } + + /** El número de llamadas al ogRepository no debe crecer con el número de equipos. */ + public function testRepositoryCallsDoNotGrowWithClientCount(): void + { + $scenario = $this->createDeployScenario(3); + $this->deployTorrent($scenario['image'], $scenario['clients']); + $repositoryCallsWithThreeClients = count($this->repositoryRequests()); + + $scenario = $this->createDeployScenario(30); + $this->deployTorrent($scenario['image'], $scenario['clients']); + $repositoryCallsWithThirtyClients = count($this->repositoryRequests()); + + $this->assertSame(1, $repositoryCallsWithThreeClients); + $this->assertSame( + $repositoryCallsWithThreeClients, + $repositoryCallsWithThirtyClients, + 'El coste en ogRepository debe ser constante, no proporcional al nº de equipos' + ); + } + + /** Si los equipos resuelven a repositorios distintos, se crea una transmisión en cada uno. */ + public function testOneRepositoryCallPerDistinctRepository(): void + { + $entityManager = $this->getEntityManager(); + + $firstScenario = $this->createDeployScenario(4); + + $secondRepository = new ImageRepository(); + $secondRepository->setName('repo-second-'.uniqid()); + $secondRepository->setIp('10.0.0.2'); + $entityManager->persist($secondRepository); + $entityManager->flush(); + + // Cuatro equipos más, apuntando al segundo repositorio, sobre la misma imagen. + $secondScenario = $this->createDeployScenario(4, $secondRepository); + + $clients = array_merge($firstScenario['clients'], $secondScenario['clients']); + + $this->deployTorrent($firstScenario['image'], $clients); + + $this->assertCount(2, $this->repositoryRequests(), 'Una transmisión por repositorio distinto'); + $this->assertCount(8, $this->agentRequests()); + } + + /** + * Las N peticiones a los ogAgent deben lanzarse todas antes de leer la primera respuesta: es lo + * que permite que viajen en paralelo. Si se procesaran de una en una, el orden sería + * start/read/start/read... y el tiempo total la suma de todos los equipos. + */ + public function testAgentRequestsAreAllStartedBeforeReadingAnyResponse(): void + { + $this->trackCallOrder = true; + $scenario = $this->createDeployScenario(12); + + $this->assertSame(200, $this->deployTorrent($scenario['image'], $scenario['clients'])); + + $starts = array_keys(array_filter( + $this->callOrder, + static fn (string $entry): bool => str_starts_with($entry, 'start:') + )); + $reads = array_keys(array_filter( + $this->callOrder, + static fn (string $entry): bool => str_starts_with($entry, 'read:') + )); + + $this->assertCount(12, $starts); + $this->assertCount(12, $reads); + $this->assertLessThan( + min($reads), + max($starts), + 'Todas las peticiones deben estar lanzadas antes de leer la primera respuesta' + ); + } +} -- 2.40.1 From 5abf8b9335be6290e065a5b1c8ef68fed85679c8 Mon Sep 17 00:00:00 2001 From: jmbardallo Date: Thu, 30 Jul 2026 13:09:50 +0200 Subject: [PATCH 39/39] Fix(image): correct property path in repository filter --- CHANGELOG.md | 1 + src/Filter/ImageSearchRepositoryFilter.php | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bbcc00..8415661 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Mercure (`TraceStatusProgressNotifier`): Publish `output` and `finishedAt` fields in Mercure traces event for real-time log updates without page reload. ### Fixed +- Filtro de imágenes (`ImageSearchRepositoryFilter`): Corregida la propiedad `repositories` a `imageImageRepositories` en el `QueryBuilder` de Doctrine para evitar un error 500 al filtrar imágenes por repositorio. - Menú del navegador (`main.html.twig`): Modificada la acción por defecto para el arranque de sistemas operativos. Se ha cambiado de `command+output:` a `command:` para evitar que se abra la ventana emergente de salida de comandos, ofreciendo una experiencia de arranque más limpia. - Webhook (`StatusController` y `RunScriptAction`): Solucionado el problema de condición de carrera que creaba trazas duplicadas al ejecutar scripts. Ahora se establece el estado a `IN_PROGRESS` de forma síncrona en `RunScriptAction` al enviar el script a clientes Windows/Linux, prescindiendo del problemático webhook asíncrono `START_SCRIPT`. - OgBoot (`PostAction`): El enrutador y la máscara de red ahora se extraen prioritariamente de las propiedades de la Subred (Subnet) asociada al cliente, antes de consultar la configuración de red de la Unidad Organizativa, o usar los valores por defecto (vacío y `255.255.255.0`). diff --git a/src/Filter/ImageSearchRepositoryFilter.php b/src/Filter/ImageSearchRepositoryFilter.php index 56e5672..6478792 100644 --- a/src/Filter/ImageSearchRepositoryFilter.php +++ b/src/Filter/ImageSearchRepositoryFilter.php @@ -24,7 +24,8 @@ class ImageSearchRepositoryFilter extends AbstractFilter $joinAlias = $queryNameGenerator->generateJoinAlias('repositoryId'); $queryBuilder - ->innerJoin(sprintf('%s.repositories', $alias), $joinAlias) + ->innerJoin(sprintf('%s.imageImageRepositories', $alias), 'iir') + ->innerJoin('iir.repository', $joinAlias) ->andWhere(sprintf('%s.id = :repositoryId', $joinAlias)) ->setParameter('repositoryId', $value); } -- 2.40.1