Minor version, several changes. New release. #125

Merged
maranda merged 41 commits from devel into main 2026-07-30 13:31:13 +02:00
70 changed files with 2254 additions and 871 deletions

View File

@ -1,5 +1,32 @@
# Changelog
## [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
- 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`).
- 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
- 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
- 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.
- 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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260703000000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Change command_task_script.content from VARCHAR(255) to LONGTEXT';
}
public function up(Schema $schema): void
{
$this->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');
}
}

View File

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Add language column to user table for storing preferred language.
*/
final class Version20260707091500 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add language column to user table';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE `user` ADD language VARCHAR(10) DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE `user` DROP COLUMN language');
}
}

View File

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Invierte la relación Client <-> 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');
}
}

View File

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Mueve el perfil de software de Image (entidad lógica) a ImageImageRepository
* (la versión/copia concreta de la imagen en un repositorio), para poder
* conservar y editar el perfil de software por versión.
*/
final class Version20260710114751 extends AbstractMigration
{
public function getDescription(): string
{
return 'Mueve software_profile_id de image a image_image_repository';
}
public function up(Schema $schema): void
{
$this->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)');
}
}

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260722100000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Change trace output column type to TEXT to support long output';
}
public function up(Schema $schema): void
{
$this->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');
}
}

View File

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

View File

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

View File

@ -0,0 +1,32 @@
<?php
namespace App\Controller;
use App\Dto\Input\CommandTaskExecuteInput;
use App\Entity\CommandTask;
use App\Service\CommandTaskTraceCreator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class CommandTaskExecuteAction extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly CommandTaskTraceCreator $commandTaskTraceCreator,
)
{
}
public function __invoke(CommandTaskExecuteInput $input, CommandTask $commandTask): JsonResponse
{
$clients = array_map(fn($client) => $client->getEntity(), $input->clients);
$this->commandTaskTraceCreator->createPendingTraces($commandTask, $clients);
$this->entityManager->flush();
return new JsonResponse(data: 'Command task executed successfully', status: Response::HTTP_OK);
}
}

View File

@ -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,
@ -87,160 +89,199 @@ 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) {
try {
$inputData = $this->createMulticastInputData($input, $image, $client->getEntity());
try {
$this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity());
} catch (\Exception $e) {
$this->logger->warning('Error with OgRepository for client (multicast)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
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;
}
} catch (\Exception $e) {
$this->logger->warning('Error deploying to client (multicast)', [
'client_uuid' => $client->getEntity()->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);
}
continue;
}
}
return $clientJobs;
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<string, string> $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;
}
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) {
$this->logger->warning('Error with OgRepository for client (torrent)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
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;
}
$pending[] = [
'client' => $client,
'inputData' => $inputData,
'response' => $this->deployImageOgAgentAction->startDeploy($image, $input, $client),
];
} catch (\Exception $e) {
$this->logger->warning('Error deploying to client (torrent)', [
'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->createTorrentInputData($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 processDeployment($client, DeployImageInput $input, ImageImageRepository $image, array $inputData, string $deployType, ?Trace $trace = null): ?string
/** Deja el despliegue en cola para que lo reintente ExecutePendingTracesCommand. */
private function queueDeployment($client, DeployImageInput $input, array $inputData): void
{
$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);
}
if (!$input->queue) {
return;
}
$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;
}
return null;
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($agentJobId);
$trace->setJobId($jobId);
$trace->setInput($inputData);
$this->entityManager->persist($trace);
$this->entityManager->flush();
} else {
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $agentJobId, $inputData);
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $jobId, $inputData);
}
return $agentJobId;
}
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),
};
}
/**
* 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<string, string> 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 createInputData(DeployImageInput $input, ImageImageRepository $image, $client): array

View File

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

View File

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

View File

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

View File

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

View File

@ -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;
@ -147,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 = TraceStatus::IN_PROGRESS;
$this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, $status, $jobId, $inputData);
}
}
}

View File

@ -89,22 +89,35 @@ 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,
'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;
$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,
]);
}
}
}
@ -112,51 +125,6 @@ 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) {
$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();
}
}
}
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) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
}
$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']]);
}
}
if (isset($data['progress'])){
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace){
@ -165,265 +133,302 @@ class StatusController extends AbstractController
$this->entityManager->flush();
}
}
if (isset($data['nfn']) && $data['nfn'] === self::CREATE_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 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) {
$trace->setStatus(TraceStatus::SUCCESS);
$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();
}
}
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) {
$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 RESPUESTA_Actualizar', ['job_id' => $data['job_id'] ?? 'none']);
}
}
$this->entityManager->flush();
}
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()]);
}
$nfn = $data['nfn'] ?? null;
if ($nfn) {
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();
}
} 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,
]);
if ($trace->getStatus() !== TraceStatus::SUCCESS && $trace->getStatus() !== TraceStatus::ERROR) {
$trace->setStatus(TraceStatus::IN_PROGRESS);
$this->entityManager->persist($trace);
$this->entityManager->flush();
}
}
break;
case 'REBOOT':
case 'POWEROFF':
$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) {
$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]);
}
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) {
$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();
}
break;
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;
$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();
}
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) {
$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;
case 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) {
$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,
]);
}
}
break;
}
}
@ -440,11 +445,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 +459,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();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,22 @@
<?php
namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\ClientOutput;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
final class CommandTaskExecuteInput
{
/**
* @var ClientOutput[]
*/
#[Assert\NotNull]
#[Groups(['command-task:write'])]
#[ApiProperty(
description: 'Los clientes donde ejecutar la tarea',
example: []
)]
public array $clients = [];
}

View File

@ -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 $repository = null;
public ?string $repositoryName = null;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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 asignado al cliente, normalmente heredado del aula y compartido con otros clientes de la misma',
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(), includeClients: false)
: null;
$this->position = $client->getPosition();
$repository = $client->getRepository()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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<int, Client>
*/
#[ORM\OneToMany(mappedBy: 'hardwareProfile', targetEntity: Client::class)]
private Collection $clients;
/**
* @var Collection<int, Hardware>
@ -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<int, Client>
*/
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;
}

View File

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

View File

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

View File

@ -45,6 +45,7 @@ class OrganizationalUnit extends AbstractEntity
* @var Collection<int, self>
*/
#[ORM\OneToMany(mappedBy: 'parent', targetEntity: self::class)]
#[ORM\OrderBy(['name' => 'ASC'])]
private Collection $organizationalUnits;
#[ORM\ManyToOne(targetEntity: NetworkSettings::class, inversedBy: 'organizationalUnits', cascade: ['persist'])]

View File

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

View File

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

View File

@ -42,7 +42,13 @@ 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),
'output' => $trace->getOutput()
])
);
$this->hub->publish($update);
@ -50,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,
]);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Entity\CommandTask;
use App\Entity\Trace;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use Doctrine\ORM\EntityManagerInterface;
final readonly class CommandTaskTraceCreator
{
public function __construct(
private EntityManagerInterface $entityManager,
)
{
}
/**
* Crea una Trace en estado PENDING por cada script de la tarea y cliente indicado,
* sin tener en cuenta el scope/organizationalUnit/clients propios de la CommandTask.
* No hace flush(): lo decide quien la invoque.
*
* @param array $clients
*/
public function createPendingTraces(CommandTask $task, array $clients): void
{
$scripts = $task->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);
}
}

View File

@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace App\Service\Trace;
use App\Entity\Trace;
use App\Model\TraceStatus;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class KillJobService
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly HttpClientInterface $httpClient,
private readonly LoggerInterface $logger,
#[Autowire(env: 'SSL_ENABLED')]
private readonly string $sslEnabled,
) {
}
/**
* Sends the kill signal to the client's ogAgent and marks the trace as cancelled.
* Persists the trace but does not flush; the caller controls the flush boundary
* so this can be used both for a single kill and inside a batch loop.
*
* @throws BadRequestHttpException on missing client IP, a network/HTTP failure talking to the
* agent, or an agent-reported failure
*/
public function kill(Trace $trace, string $jobId): void
{
$client = $trace->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;
}
}

View File

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

View File

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

View File

@ -1,23 +0,0 @@
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
#[\Attribute]
class ClientsHaveSamePartitionSize extends Constraint
{
public string $message;
public function __construct(mixed $options = null, ?array $groups = null, mixed $payload = null)
{
parent::__construct($options, $groups, $payload);
$this->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;
}
}

View File

@ -1,76 +0,0 @@
<?php
namespace App\Validator\Constraints;
use App\Dto\Input\DeployImageInput;
use App\Dto\Input\DeployGitImageInput;
use App\Dto\Output\ClientOutput;
use App\Entity\Client;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
class ClientsHaveSamePartitionSizeValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint): void
{
if (!$value instanceof DeployImageInput && !$value instanceof DeployGitImageInput) {
return;
}
if (!isset($value->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();
}
}
}

View File

@ -575,7 +575,7 @@
<td>
{% if partition.operativeSystem %}
<a href="command+output:/opt/opengnsys/scripts/bootOs {{ partition.diskNumber }} {{ partition.partitionNumber }}"
<a href="command:/opt/opengnsys/scripts/bootOs {{ partition.diskNumber }} {{ partition.partitionNumber }}"
class="partition-boot-btn"
role="button">
<i class="fas fa-play"></i> Arrancar {{ partition.operativeSystem.name }}

View File

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

View File

@ -0,0 +1,86 @@
<?php
namespace Functional;
use App\Controller\OgAgent\Webhook\StatusController;
use App\Entity\ImageImageRepository;
use App\Factory\ClientFactory;
use App\Factory\ImageFactory;
use App\Factory\ImageImageRepositoryFactory;
use App\Factory\SoftwareFactory;
use App\Factory\UserFactory;
use App\Model\UserGroupPermissions;
/**
* Verifica que el inventario de software recibido al crear/inventariar una
* imagen se asocia a la versión concreta (ImageImageRepository) y no a la
* imagen lógica (Image), y que tanto el software ya existente como el
* software nuevo detectado quedan enlazados al perfil generado.
*/
class CreateSoftwareProfileFromInventoryTest extends AbstractTest
{
public function testCreateSoftwareProfileLinksExistingAndNewSoftwareToTheVersion(): 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();
$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');
}
}

View File

@ -0,0 +1,317 @@
<?php
namespace Functional;
use App\Entity\Client;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\ImageRepository;
use App\Entity\OrganizationalUnit;
use App\Factory\UserFactory;
use App\Model\DeployMethodTypes;
use App\Model\ImageStatus;
use App\Model\OrganizationalUnitP2PModes;
use App\Model\OrganizationalUnitTypes;
use App\Model\UserGroupPermissions;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
/**
* La creación de la transmisión en el ogRepository es una operación por repositorio, no por cliente.
* Antes se lanzaba dentro del bucle de clientes, así que un despliegue de N equipos hacía N veces la
* misma petición (y esa petición tarda ~10s en real), de ahí que el tiempo creciera con el nº de PCs.
*
* @see \App\Controller\DeployImageAction::prepareRepositoryTransmissions()
*/
class DeployImageTorrentTest extends AbstractTest
{
private const ADMIN_USER = 'deploy-super-admin';
/** @var string[] URLs invocadas sobre el httpClient, en orden */
private array $requestedUrls = [];
/** Contadores para no repetir IPs, que son únicas en BD. */
private int $clientIpCounter = 0;
private int $repositoryIpCounter = 0;
private ?string $adminToken = null;
/** @var string[] Orden de "start:" (peticion lanzada) y "read:" (respuesta leida) */
private array $callOrder = [];
/** Permite que un test elija el mock que registra el orden de las llamadas. */
private bool $trackCallOrder = false;
private function getEntityManager(): EntityManagerInterface
{
return static::getContainer()->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'
);
}
}

View File

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

View File

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

View File

@ -0,0 +1,90 @@
<?php
namespace Functional;
use App\Controller\OgAgent\CreateImageAction;
use App\Controller\OgAgent\RunScriptAction;
use App\Controller\OgRepository\Git\CreateRepositoryAction;
use App\Controller\OgRepository\Git\SshKeyAction;
use App\Dto\Input\CommandExecuteInput;
use App\Dto\Output\ClientOutput;
use App\Entity\Client;
use App\Entity\Trace;
use App\Factory\ClientFactory;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use App\Service\CreatePartitionService;
use App\Service\Trace\CreateService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
/**
* Reproduce el bug reportado: si el cliente está ocupado (el agente responde
* 409) y el usuario marcó "encolar tarea", ejecutar un script debía crear
* una traza PENDING para que opengnsys:execute-pending-traces la reintentase
* al terminar la tarea anterior. Antes del fix, esta rama ignoraba el flag
* "queue" por completo y siempre creaba una traza BUSY (que el comando de
* reintento nunca recoge, porque solo busca traces en PENDING).
*/
class RunScriptQueueTest extends AbstractTest
{
private function buildRunScriptAction(MockHttpClient $httpClient): RunScriptAction
{
$container = static::getContainer();
return new RunScriptAction(
$container->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)');
}
}

View File

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

View File

@ -0,0 +1,197 @@
<?php
namespace Functional;
use ApiPlatform\Symfony\Bundle\Test\Client as ApiClient;
use App\Entity\Client;
use App\Entity\OrganizationalUnit;
use App\Entity\Trace;
use App\Entity\User;
use App\Factory\UserFactory;
use App\Model\OrganizationalUnitTypes;
use App\Model\TraceStatus;
use App\Model\UserGroupPermissions;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
/**
* Una traza pertenece a un cliente y el cliente a una unidad organizativa, así que un usuario
* que no sea super-admin solo debe ver las trazas de los equipos de las OUs que tiene asignadas
* (y las de sus OUs hijas).
*
* @see \App\Doctrine\UserAllowedOrganizationalUnitExtension
*/
class TraceVisibilityTest extends AbstractTest
{
private const SA_USER = 'trace-super-admin';
private const OP_USER = 'trace-ou-operator';
/** Crea un usuario con el rol indicado y devuelve su JWT. */
private function tokenFor(string $username, string $role): string
{
UserFactory::createOne(['username' => $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));
}
}