diff --git a/CHANGELOG.md b/CHANGELOG.md index 398e221..39571c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,32 @@ # Changelog +## [1.4.0] - 2026-04-08 +### Added +- Entidad Partition: Añadido el campo deployDate expuesto mediante el DTO para registrar la fecha exacta de despliegue de imagen. +- CreatePartitionService: Inclusión de lógica idempotente que asocia la imagen y extrae su fecha real directamente del fichero /.ogimage enviado por el cliente en el parámetro img=. + +### Fixed +- Limpieza explícita del deployDate (null) en caso de que el inventario no informe de fecha o haya alteraciones en el payload para evitar desincronizaciones de trazas de la imagen subyacente. + +## [1.3.0] - 2026-03-31 +### Added +- Añadida acción Refresh para actualizar el estado de un cliente o clientes. Se actualiza su configuración de discos y se recarga el ogBrowser por si hubiese cambio del menu. + +## [1.2.11] - 2026-03-25 +### Added +Modificada columna cacheContent de una partición para que sea de tipo TEXT y contener la lista de ficheros que tiene la cache. Se envía desde el ogagent al obtener la configuración mediante el campo [cac] + +## [1.2.10] - 2026-03-25 +### Added +Modificado StatusController para que al recibir un webhook de Poweroff o reboot actualice el estado de las trazas en progreso y las ponga como finalizadas. + +## [1.2.9] - 2026-03-25 +### Added +- Nuevo webhook `START_SCRIPT` en StatusController que permite crear automáticamente una entidad Trace y poner el equipo local en estado `BUSY` cuando un cliente inicia sus propios scripts de forma autónoma (ej: menús locales de ogLive). +### Fixed +- Se ha corregido un bug en RunScriptAction que provocaba que al enviar la orden de ejecutar un script desde la web de administración, la interfaz no cambiara visualmente el estado del cliente a ocupado (rojo), unificando así el comportamiento con el resto de comandos (como crear o restaurar imagen). +### Improved +- En StatusController ahora se restablece automáticamente el estado del cliente a `OG_LIVE` cuando se recibe el webhook de finalización `RESPUESTA_EjecutarScript`, reflejando visualmente que el equipo ha terminado de trabajar. + ## [1.2.8] - 2026-03-20 ### Added - Modificado MenuBrowserController para permitir la edición de las plantillas de menú en "raw", permitiendo modificar el código twig en lugar del html ya compilado por twig, de esta forma podemos editar el fichero twig y aplicar cambios para ver el resultado antes de guardar la plantilla. diff --git a/config/api_platform/Client.yaml b/config/api_platform/Client.yaml index 3b0e448..229aa8c 100644 --- a/config/api_platform/Client.yaml +++ b/config/api_platform/Client.yaml @@ -100,6 +100,13 @@ resources: uriTemplate: /clients/server/power-off controller: App\Controller\OgAgent\PowerOffAction + refresh_client: + class: ApiPlatform\Metadata\Post + method: POST + input: App\Dto\Input\MultipleClientsInput + uriTemplate: /clients/server/refresh + controller: App\Controller\OgAgent\RefreshAction + check_partition_sizes: class: ApiPlatform\Metadata\Post method: POST diff --git a/src/Controller/OgAgent/RefreshAction.php b/src/Controller/OgAgent/RefreshAction.php new file mode 100644 index 0000000..2107a2d --- /dev/null +++ b/src/Controller/OgAgent/RefreshAction.php @@ -0,0 +1,93 @@ +clients as $clientEntity) { + /** @var Client $client */ + $client = $clientEntity->getEntity(); + + if (!$client->getIp()) { + throw new BadRequestHttpException('IP is required'); + } + + // ONLY execute if the client is in OG_LIVE state + if ($client->getStatus() !== ClientStatus::OG_LIVE) { + $this->logger->info('Skipping refresh for client not in OG_LIVE state', ['client' => $client->getId(), 'status' => $client->getStatus()]); + continue; + } + + $data = [ + 'nfn' => 'Actualizar', + 'ids' => '0' + ]; + + $response = $this->createRequest( + method: 'POST', + url: 'https://'.$client->getIp().':8000/ogAdmClient/Actualizar', + params: [ + 'json' => $data, + ], + token: $client->getToken(), + ); + + if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) { + $this->logger->error('Error refreshing client', ['client' => $client->getId(), 'error' => $response['error']]); + + if ($input->queue) { + $this->createService->__invoke($client, CommandTypes::REFRESH, TraceStatus::PENDING, null, []); + continue; + } + + continue; + } + + $this->logger->info('Refreshing client menu and disk configuration', ['client' => $client->getId()]); + + $jobId = $response['job_id'] ?? null; + + // We do not change the status here, it remains OG_LIVE + // $client->setStatus(ClientStatus::OG_LIVE); + + $this->createService->__invoke($client, CommandTypes::REFRESH, TraceStatus::SUCCESS, $jobId, []); + } + + return new JsonResponse(data: [], status: Response::HTTP_OK); + } +} diff --git a/src/Controller/OgAgent/RunScriptAction.php b/src/Controller/OgAgent/RunScriptAction.php index 4812bf5..b48917f 100644 --- a/src/Controller/OgAgent/RunScriptAction.php +++ b/src/Controller/OgAgent/RunScriptAction.php @@ -140,6 +140,10 @@ class RunScriptAction extends AbstractOgAgentController $jobId = $response['job_id']; $inputData = ['script' => $input->script]; + if (!$this->isLinuxOrWindows($client) && !$this->isLinuxOrWindowsSession($client)) { + $client->setStatus(ClientStatus::BUSY); + } + $this->entityManager->persist($client); $this->entityManager->flush(); diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index d3132f6..bc989ae 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -44,6 +44,7 @@ class StatusController extends AbstractController const string RESTORE_IMAGE_GIT = 'RESPUESTA_RestaurarImagenGit'; const string CONFIGURE_IMAGE = 'RESPUESTA_Configurar'; const string HARDWARE_INVENTORY = 'RESPUESTA_InventarioHardware'; + const string REFRESH = 'RESPUESTA_Actualizar'; const string SOFTWARE_INVENTORY = 'RESPUESTA_InventarioSoftware'; const string RUN_SCRIPT = 'RESPUESTA_EjecutarScript'; @@ -81,6 +82,43 @@ class StatusController extends AbstractController $this->entityManager->persist($client); $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); + } + + if ($client->getStatus() === ClientStatus::BUSY) { + $newStatus = ($data['nfn'] === 'REBOOT') ? ClientStatus::INITIALIZING : ClientStatus::TURNING_OFF; + $client->setStatus($newStatus); + $this->entityManager->persist($client); + } + + $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']]); @@ -242,6 +280,13 @@ class StatusController extends AbstractController $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(); } } @@ -280,6 +325,30 @@ class StatusController extends AbstractController } } + 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(); + } + return new JsonResponse(data: 'Webhook finished', status: Response::HTTP_OK); } diff --git a/src/Dto/Output/PartitionOutput.php b/src/Dto/Output/PartitionOutput.php index 76e55e2..0063ba6 100644 --- a/src/Dto/Output/PartitionOutput.php +++ b/src/Dto/Output/PartitionOutput.php @@ -74,6 +74,13 @@ class PartitionOutput extends AbstractOutput )] public ?int $memoryUsage = null; + #[Groups(['partition:read', 'client:read'])] + #[ApiProperty( + description: 'Fecha de despliegue de la imagen', + example: '2025-01-01T00:00:00+00:00' + )] + public ?\DateTimeInterface $deployDate = null; + public function __construct(Partition $partition) { parent::__construct($partition); @@ -94,5 +101,6 @@ class PartitionOutput extends AbstractOutput } $this->memoryUsage = $partition->getMemoryUsage() / 100; + $this->deployDate = $partition->getDeployDate(); } } \ No newline at end of file diff --git a/src/Entity/Partition.php b/src/Entity/Partition.php index b0cc7ca..dde3700 100644 --- a/src/Entity/Partition.php +++ b/src/Entity/Partition.php @@ -3,6 +3,7 @@ namespace App\Entity; use App\Repository\PartitionRepository; +use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: PartitionRepository::class)] @@ -21,7 +22,7 @@ class Partition extends AbstractEntity #[ORM\Column] private ?int $size = null; - #[ORM\Column(length: 255, nullable: true)] + #[ORM\Column(type: Types::TEXT, nullable: true)] private ?string $cacheContent = null; #[ORM\Column(length: 255, nullable: true)] @@ -42,6 +43,21 @@ class Partition extends AbstractEntity #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')] private ?ImageImageRepository $image = null; + #[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)] + private ?\DateTimeInterface $deployDate = null; + + public function getDeployDate(): ?\DateTimeInterface + { + return $this->deployDate; + } + + public function setDeployDate(?\DateTimeInterface $deployDate): static + { + $this->deployDate = $deployDate; + + return $this; + } + public function getDiskNumber(): ?int { return $this->diskNumber; diff --git a/src/Model/CommandTypes.php b/src/Model/CommandTypes.php index cff2407..a788231 100644 --- a/src/Model/CommandTypes.php +++ b/src/Model/CommandTypes.php @@ -29,6 +29,7 @@ final class CommandTypes public const string HARDWARE_INVENTORY = 'hardware-inventory'; public const string SOFTWARE_INVENTORY = 'software-inventory'; public const string KILL_JOB = 'kill-job'; + public const string REFRESH = 'refresh'; private const array COMMAND_TYPES = [ self::DEPLOY_IMAGE => 'Deploy Image', @@ -56,6 +57,7 @@ final class CommandTypes self::HARDWARE_INVENTORY => 'Hardware Inventory', self::SOFTWARE_INVENTORY => 'Software Inventory', self::KILL_JOB => 'Kill Job', + self::REFRESH => 'Refresh', ]; public static function getCommandTypes(): array diff --git a/src/Service/CreatePartitionService.php b/src/Service/CreatePartitionService.php index f48acfd..9e16482 100644 --- a/src/Service/CreatePartitionService.php +++ b/src/Service/CreatePartitionService.php @@ -63,6 +63,32 @@ class CreatePartitionService $partitionEntity->setOperativeSystem($operativeSystem); } } + + if (isset($cfg['img']) && $cfg['img'] !== '') { + $imgParts = explode(':', $cfg['img']); + $imgName = trim($imgParts[0]); + $imgDate = $imgParts[1] ?? null; + + $imageImageRepository = $this->entityManager->getRepository(\App\Entity\ImageImageRepository::class) + ->findOneBy(['name' => $imgName]); + + if ($imageImageRepository) { + $partitionEntity->setImage($imageImageRepository); + $partitionEntity->setDeployDate(null); + if ($imgDate) { + $dateObj = \DateTime::createFromFormat('YmdHi', trim($imgDate)); + if ($dateObj) { + $partitionEntity->setDeployDate($dateObj); + } + } + } else { + $partitionEntity->setImage(null); + $partitionEntity->setDeployDate(null); + } + } elseif (isset($cfg['img']) && $cfg['img'] === '') { + $partitionEntity->setImage(null); + $partitionEntity->setDeployDate(null); + } $partitionEntity->setClient($clientEntity); $partitionEntity->setDiskNumber($cfg['disk']); @@ -86,6 +112,7 @@ class CreatePartitionService $partitionEntity->setFilesystem($cfg['fsi']); $partitionEntity->setMemoryUsage(((int) $cfg['uso']) * 100); + $partitionEntity->setCacheContent($cfg['cac'] ?? null); $this->entityManager->persist($partitionEntity); $receivedPartitions[] = ['disk' => $cfg['disk'], 'partition' => $cfg['par']];