Merge branch 'main' into develop

pull/88/head
Manuel Aranda Rosales 2026-04-13 12:35:00 +02:00
commit d422a46a3c
9 changed files with 255 additions and 1 deletions

View File

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

View File

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

View File

@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace App\Controller\OgAgent;
use App\Dto\Input\MultipleClientsInput;
use App\Entity\Client;
use App\Entity\Command;
use App\Entity\Image;
use App\Entity\Trace;
use App\Model\ClientStatus;
use App\Model\CommandTypes;
use App\Model\ImageStatus;
use App\Model\TraceStatus;
use App\Service\Trace\CreateService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Validator\Exception\ValidatorException;
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\HttpClientInterface;
class RefreshAction extends AbstractOgAgentController
{
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __invoke(MultipleClientsInput $input): JsonResponse
{
foreach ($input->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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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