From 8e83fce136a4c55f9ff951ebeda4e5e7e2624b28 Mon Sep 17 00:00:00 2001 From: Manuel Aranda Date: Mon, 27 Apr 2026 11:26:27 +0200 Subject: [PATCH] Updated remote PC and bug status classrom --- migrations/Version20260423100000.php | 63 ++++ migrations/Version20260424120000.php | 28 ++ migrations/Version20260424130000.php | 28 ++ .../OrganizationalUnitStatusAction.php | 10 +- src/Controller/OgAgent/StatusAction.php | 11 +- .../Webhook/AgentSessionController.php | 33 +- .../OgAgent/Webhook/StatusController.php | 6 + src/Controller/ServerInfoController.php | 39 +++ .../UDS/OrganizationalUnitController.php | 32 +- src/Controller/UDS/RemotePcController.php | 301 ++++++++++++++++++ src/Dto/Input/ImageImageRepositoryInput.php | 6 + src/Dto/Input/ImageInput.php | 6 - src/Dto/Input/ImageRepositoryInput.php | 1 - src/Dto/Output/ImageImageRepositoryOutput.php | 12 +- src/Dto/Output/ImageOutput.php | 8 - src/Entity/AgentQueue.php | 57 ++++ src/Entity/Client.php | 15 + src/Entity/Image.php | 15 - src/Entity/ImageImageRepository.php | 15 + src/Entity/ImageRepository.php | 1 + src/Entity/RemotePC.php | 78 +++++ .../UdsSyncOnClientStatusListener.php | 63 ++++ src/Repository/AgentQueueRepository.php | 27 ++ src/Repository/ClientRepository.php | 52 +++ src/Repository/RemotePCRepository.php | 17 + src/Service/UDS/UDSClient.php | 9 +- 26 files changed, 874 insertions(+), 59 deletions(-) create mode 100644 migrations/Version20260423100000.php create mode 100644 migrations/Version20260424120000.php create mode 100644 migrations/Version20260424130000.php create mode 100644 src/Controller/ServerInfoController.php create mode 100644 src/Controller/UDS/RemotePcController.php create mode 100644 src/Entity/AgentQueue.php create mode 100644 src/Entity/RemotePC.php create mode 100644 src/EventListener/UdsSyncOnClientStatusListener.php create mode 100644 src/Repository/AgentQueueRepository.php create mode 100644 src/Repository/RemotePCRepository.php diff --git a/migrations/Version20260423100000.php b/migrations/Version20260423100000.php new file mode 100644 index 0000000..b3980d6 --- /dev/null +++ b/migrations/Version20260423100000.php @@ -0,0 +1,63 @@ +addSql('CREATE TABLE remote_pc ( + id INT AUTO_INCREMENT NOT NULL, + client_id INT NOT NULL, + reserved_until DATETIME DEFAULT NULL, + url_login VARCHAR(512) DEFAULT NULL, + url_logout VARCHAR(512) DEFAULT NULL, + uuid VARCHAR(255) NOT NULL, + migration_id VARCHAR(255) DEFAULT NULL, + created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', + updated_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', + created_by VARCHAR(255) DEFAULT NULL, + updated_by VARCHAR(255) DEFAULT NULL, + UNIQUE INDEX UNIQ_REMOTE_PC_UUID (uuid), + UNIQUE INDEX UNIQ_REMOTE_PC_CLIENT (client_id), + PRIMARY KEY(id) + ) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); + + $this->addSql('CREATE TABLE agent_queue ( + id INT AUTO_INCREMENT NOT NULL, + client_id INT NOT NULL, + exec_time DATETIME NOT NULL, + operation VARCHAR(32) NOT NULL, + uuid VARCHAR(255) NOT NULL, + migration_id VARCHAR(255) DEFAULT NULL, + created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', + updated_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', + created_by VARCHAR(255) DEFAULT NULL, + updated_by VARCHAR(255) DEFAULT NULL, + UNIQUE INDEX UNIQ_AGENT_QUEUE_UUID (uuid), + INDEX IDX_AGENT_QUEUE_CLIENT (client_id), + PRIMARY KEY(id) + ) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); + + $this->addSql('ALTER TABLE remote_pc ADD CONSTRAINT FK_REMOTE_PC_CLIENT FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE CASCADE'); + $this->addSql('ALTER TABLE agent_queue ADD CONSTRAINT FK_AGENT_QUEUE_CLIENT FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE CASCADE'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE remote_pc DROP FOREIGN KEY FK_REMOTE_PC_CLIENT'); + $this->addSql('ALTER TABLE agent_queue DROP FOREIGN KEY FK_AGENT_QUEUE_CLIENT'); + $this->addSql('DROP TABLE remote_pc'); + $this->addSql('DROP TABLE agent_queue'); + } +} diff --git a/migrations/Version20260424120000.php b/migrations/Version20260424120000.php new file mode 100644 index 0000000..61ce978 --- /dev/null +++ b/migrations/Version20260424120000.php @@ -0,0 +1,28 @@ +addSql('ALTER TABLE image_repository ADD remote_pc TINYINT(1) DEFAULT 0'); + $this->addSql('ALTER TABLE image DROP remote_pc'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE image ADD remote_pc TINYINT(1) DEFAULT NULL'); + $this->addSql('ALTER TABLE image_repository DROP remote_pc'); + } +} diff --git a/migrations/Version20260424130000.php b/migrations/Version20260424130000.php new file mode 100644 index 0000000..9dd05ca --- /dev/null +++ b/migrations/Version20260424130000.php @@ -0,0 +1,28 @@ +addSql('ALTER TABLE image_image_repository ADD remote_pc TINYINT(1) DEFAULT 0'); + $this->addSql('ALTER TABLE image_repository DROP remote_pc'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE image_repository ADD remote_pc TINYINT(1) DEFAULT 0'); + $this->addSql('ALTER TABLE image_image_repository DROP remote_pc'); + } +} diff --git a/src/Controller/OgAgent/OrganizationalUnitStatusAction.php b/src/Controller/OgAgent/OrganizationalUnitStatusAction.php index 797132a..6a66704 100644 --- a/src/Controller/OgAgent/OrganizationalUnitStatusAction.php +++ b/src/Controller/OgAgent/OrganizationalUnitStatusAction.php @@ -80,9 +80,13 @@ class OrganizationalUnitStatusAction extends AbstractOgAgentController $this->createPartitionService->__invoke($data, $client); } - if ($client->getStatus() !== ClientStatus::LINUX - && $client->getStatus() !== ClientStatus::MACOS - && $client->getStatus() !== ClientStatus::WINDOWS) { + $preservedStatuses = [ + ClientStatus::LINUX, ClientStatus::LINUX_SESSION, + ClientStatus::MACOS, ClientStatus::MACOS_SESSION, + ClientStatus::WINDOWS, ClientStatus::WINDOWS_SESSION, + ClientStatus::BUSY, + ]; + if (!in_array($client->getStatus(), $preservedStatuses, true)) { $client->setStatus(ClientStatus::OG_LIVE); } diff --git a/src/Controller/OgAgent/StatusAction.php b/src/Controller/OgAgent/StatusAction.php index f1efecc..e8364e6 100644 --- a/src/Controller/OgAgent/StatusAction.php +++ b/src/Controller/OgAgent/StatusAction.php @@ -43,11 +43,14 @@ class StatusAction extends AbstractOgAgentController if ($client->getStatus() === ClientStatus::OG_LIVE || $client->getStatus() === ClientStatus::OFF - || $client->getStatus() === ClientStatus::BUSY || $client->getStatus() === ClientStatus::INITIALIZING) { $response = $this->getOgLiveStatus($client); } + if ($client->getStatus() === ClientStatus::BUSY) { + $response = $this->getOgLiveStatus($client, preserveStatus: true); + } + if ($client->getStatus() === ClientStatus::LINUX || $client->getStatus() === ClientStatus::MACOS || $client->getStatus() === ClientStatus::WINDOWS) { @@ -66,7 +69,7 @@ class StatusAction extends AbstractOgAgentController * @throws RedirectionExceptionInterface * @throws ClientExceptionInterface */ - public function getOgLiveStatus (Client $client): JsonResponse|int|string + public function getOgLiveStatus(Client $client, bool $preserveStatus = false): JsonResponse|int|string { $this->logger->info('Checking client status', ['client' => $client->getId()]); @@ -97,7 +100,9 @@ class StatusAction extends AbstractOgAgentController $this->createPartitionService->__invoke($data, $client); } - $client->setStatus(ClientStatus::OG_LIVE); + if (!$preserveStatus) { + $client->setStatus(ClientStatus::OG_LIVE); + } $this->entityManager->persist($client); $this->entityManager->flush(); diff --git a/src/Controller/OgAgent/Webhook/AgentSessionController.php b/src/Controller/OgAgent/Webhook/AgentSessionController.php index f1f2073..0fbebad 100644 --- a/src/Controller/OgAgent/Webhook/AgentSessionController.php +++ b/src/Controller/OgAgent/Webhook/AgentSessionController.php @@ -14,15 +14,16 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Attribute\AsController; use Symfony\Component\Routing\Annotation\Route; +use Symfony\Contracts\HttpClient\HttpClientInterface; #[AsController] class AgentSessionController extends AbstractController { public function __construct( protected readonly EntityManagerInterface $entityManager, - protected readonly LoggerInterface $logger - ) - { + protected readonly LoggerInterface $logger, + protected readonly HttpClientInterface $httpClient, + ) { } #[Route('/opengnsys/rest/ogagent/started', methods: ['POST'])] @@ -139,6 +140,19 @@ class AgentSessionController extends AbstractController $this->entityManager->persist($client); $this->entityManager->flush(); + $remotePC = $client->getRemotePC(); + if ($remotePC && $remotePC->isReservedActive() && $remotePC->getUrlLogin()) { + try { + $this->httpClient->request('POST', $remotePC->getUrlLogin(), [ + 'verify_host' => false, + 'body' => $request->getContent(), + 'headers' => ['Content-Type' => 'application/json'], + ]); + } catch (\Throwable $e) { + $this->logger->warning('RemotePC: loggedin callback failed', ['ip' => $client->getIp(), 'error' => $e->getMessage()]); + } + } + $this->logger->info('Client logged in', [ 'ip' => $data['ip'], 'user' => $data['user'], @@ -188,6 +202,19 @@ class AgentSessionController extends AbstractController $this->entityManager->persist($client); $this->entityManager->flush(); + $remotePC = $client->getRemotePC(); + if ($remotePC && $remotePC->isReservedActive() && $remotePC->getUrlLogout()) { + try { + $this->httpClient->request('POST', $remotePC->getUrlLogout(), [ + 'verify_host' => false, + 'body' => $request->getContent(), + 'headers' => ['Content-Type' => 'application/json'], + ]); + } catch (\Throwable $e) { + $this->logger->warning('RemotePC: loggedout callback failed', ['ip' => $client->getIp(), 'error' => $e->getMessage()]); + } + } + $this->logger->info('Client logged out', [ 'ip' => $data['ip'], 'user' => $data['user'], diff --git a/src/Controller/OgAgent/Webhook/StatusController.php b/src/Controller/OgAgent/Webhook/StatusController.php index 29e948d..f2cf5d1 100644 --- a/src/Controller/OgAgent/Webhook/StatusController.php +++ b/src/Controller/OgAgent/Webhook/StatusController.php @@ -236,6 +236,12 @@ class StatusController extends AbstractController 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) { diff --git a/src/Controller/ServerInfoController.php b/src/Controller/ServerInfoController.php new file mode 100644 index 0000000..3079949 --- /dev/null +++ b/src/Controller/ServerInfoController.php @@ -0,0 +1,39 @@ + 'Release file not found'], Response::HTTP_NOT_FOUND); + } + + $content = file_get_contents(self::RELEASE_FILE); + $lines = array_filter(explode("\n", trim($content))); + + $versions = []; + foreach ($lines as $line) { + if (!str_contains($line, ':')) { + continue; + } + [$key, $value] = explode(':', $line, 2); + $versions[trim($key)] = trim($value); + } + + return new JsonResponse($versions); + } +} diff --git a/src/Controller/UDS/OrganizationalUnitController.php b/src/Controller/UDS/OrganizationalUnitController.php index 165add1..2a6bdd0 100644 --- a/src/Controller/UDS/OrganizationalUnitController.php +++ b/src/Controller/UDS/OrganizationalUnitController.php @@ -2,7 +2,7 @@ namespace App\Controller\UDS; -use App\Entity\Image; +use App\Entity\ImageImageRepository; use App\Entity\OrganizationalUnit; use App\Model\OrganizationalUnitTypes; use Doctrine\ORM\EntityManagerInterface; @@ -74,9 +74,9 @@ class OrganizationalUnitController extends AbstractController $data[] = [ 'id' => $classroom->getId(), 'name' => $classroom->getName(), - 'inremotepc' => true, + 'inremotepc' => $classroom->getRemotePc() ?? false, 'ou' => [ - 'id' => 1 + 'id' => $centerId ], 'classroom' => [] ]; @@ -89,24 +89,24 @@ class OrganizationalUnitController extends AbstractController #[Route('/opengnsys/rest//ous/{centerId}/images', methods: ['GET'])] public function getImages(int $centerId): JsonResponse { - $parent = $this->entityManager - ->getRepository(OrganizationalUnit::class) - ->find($centerId); - - $images = $this->entityManager - ->getRepository(Image::class) - ->findAll(); + $iirs = $this->entityManager + ->getRepository(ImageImageRepository::class) + ->findBy(['remotePc' => true]); + $seen = []; $data = []; - foreach ($images as $image) { + foreach ($iirs as $iir) { + $image = $iir->getImage(); + if (!$image || isset($seen[$image->getId()])) { + continue; + } + $seen[$image->getId()] = true; $data[] = [ - 'id' => $image->getId(), - 'name' => $image->getName(), + 'id' => $image->getId(), + 'name' => $image->getName(), 'inremotepc' => true, - 'ou' => [ - 'id' => 1 - ] + 'ou' => ['id' => $centerId], ]; } diff --git a/src/Controller/UDS/RemotePcController.php b/src/Controller/UDS/RemotePcController.php new file mode 100644 index 0000000..3d899de --- /dev/null +++ b/src/Controller/UDS/RemotePcController.php @@ -0,0 +1,301 @@ +toArray(); + $labId = isset($data['labid']) && $data['labid'] !== 0 ? (int) $data['labid'] : null; + $maxTime = (int) ($data['maxtime'] ?? 24); + + /** @var ClientRepository $clientRepo */ + $clientRepo = $this->entityManager->getRepository(Client::class); + $client = $clientRepo->findBestAvailableClientForImage($ouid, $imageId, $labId); + + if (!$client) { + return new JsonResponse(['message' => 'No available client found for this image'], Response::HTTP_NOT_FOUND); + } + + $partition = $this->findPartitionForImage($client, $imageId); + $this->startClient($client, $partition); + + $remotePC = $client->getRemotePC() ?? $this->createRemotePC($client); + $remotePC->setReservedUntil(new \DateTime("+{$maxTime} hours")); + $remotePC->setUrlLogin(null); + $remotePC->setUrlLogout(null); + $this->entityManager->flush(); + + $lab = $client->getOrganizationalUnit(); + + $this->logger->info('RemotePC: client reserved', [ + 'client_id' => $client->getId(), + 'image_id' => $imageId, + 'reserved_until' => $remotePC->getReservedUntil()->format('Y-m-d H:i:s'), + ]); + + return new JsonResponse([ + 'id' => $client->getId(), + 'name' => $client->getName(), + 'ip' => $client->getIp(), + 'mac' => $client->getMac(), + 'lab' => ['id' => $lab?->getId()], + 'ou' => ['id' => $ouid], + ], Response::HTTP_OK); + } + + #[Route('/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/unreserve', methods: ['DELETE'])] + #[Route('/opengnsys/rest//ous/{ouid}/labs/{labId}/clients/{clientId}/unreserve', methods: ['DELETE'])] + public function unreserve(int $ouid, int $labId, int $clientId): JsonResponse + { + $client = $this->findClientInLabAndOu($ouid, $labId, $clientId); + if (!$client) { + return new JsonResponse(['message' => 'Client not found'], Response::HTTP_NOT_FOUND); + } + + $remotePC = $client->getRemotePC(); + if (!$remotePC || $remotePC->getReservedUntil() === null) { + return new JsonResponse(['message' => 'Client is not reserved'], Response::HTTP_BAD_REQUEST); + } + + $remotePC->setReservedUntil(null); + $remotePC->setUrlLogin(null); + $remotePC->setUrlLogout(null); + $this->entityManager->flush(); + + /** @var AgentQueueRepository $queueRepo */ + $queueRepo = $this->entityManager->getRepository(AgentQueue::class); + $queueRepo->deleteByClientAndOperations($client, self::QUEUE_OPERATIONS); + + $this->sendPowerOff($client); + + $this->logger->info('RemotePC: client unreserved', ['client_id' => $client->getId()]); + + return new JsonResponse('', Response::HTTP_OK); + } + + #[Route('/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/events', methods: ['POST'])] + #[Route('/opengnsys/rest//ous/{ouid}/labs/{labId}/clients/{clientId}/events', methods: ['POST'])] + public function events(int $ouid, int $labId, int $clientId, Request $request): JsonResponse + { + $client = $this->findClientInLabAndOu($ouid, $labId, $clientId); + if (!$client) { + return new JsonResponse(['message' => 'Client not found'], Response::HTTP_NOT_FOUND); + } + + $remotePC = $client->getRemotePC(); + if (!$remotePC || !$remotePC->isReservedActive()) { + return new JsonResponse(['message' => 'Client is not actively reserved'], Response::HTTP_BAD_REQUEST); + } + + $data = $request->toArray(); + $urlLogin = $data['urlLogin'] ?? null; + $urlLogout = $data['urlLogout'] ?? null; + + if (!filter_var($urlLogin, FILTER_VALIDATE_URL) || !filter_var($urlLogout, FILTER_VALIDATE_URL)) { + return new JsonResponse(['message' => 'Invalid urlLogin or urlLogout'], Response::HTTP_BAD_REQUEST); + } + + $remotePC->setUrlLogin($urlLogin); + $remotePC->setUrlLogout($urlLogout); + $this->entityManager->flush(); + + $this->logger->info('RemotePC: events registered', ['client_id' => $client->getId()]); + + return new JsonResponse('', Response::HTTP_OK); + } + + #[Route('/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/session', methods: ['POST'])] + #[Route('/opengnsys/rest//ous/{ouid}/labs/{labId}/clients/{clientId}/session', methods: ['POST'])] + public function session(int $ouid, int $labId, int $clientId, Request $request): JsonResponse + { + $client = $this->findClientInLabAndOu($ouid, $labId, $clientId); + if (!$client) { + return new JsonResponse(['message' => 'Client not found'], Response::HTTP_NOT_FOUND); + } + + $remotePC = $client->getRemotePC(); + if (!$remotePC || !$remotePC->getUrlLogin()) { + return new JsonResponse(['message' => 'Client has no active session'], Response::HTTP_BAD_REQUEST); + } + + $data = $request->toArray(); + $deadLine = (int) ($data['deadLine'] ?? 0); + + if ($deadLine === 0) { + return new JsonResponse('', Response::HTTP_OK); + } + + /** @var AgentQueueRepository $queueRepo */ + $queueRepo = $this->entityManager->getRepository(AgentQueue::class); + $queueRepo->deleteByClientAndOperations($client, self::QUEUE_OPERATIONS); + + $now = new \DateTime(); + + if ($deadLine > 600) { + $this->createQueueEntry($client, (clone $now)->modify("+{$deadLine} seconds")->modify('-600 seconds'), 'popup-10'); + } + + if ($deadLine > 300) { + $this->createQueueEntry($client, (clone $now)->modify("+{$deadLine} seconds")->modify('-300 seconds'), 'popup-5'); + } + + $this->createQueueEntry($client, (clone $now)->modify("+{$deadLine} seconds"), 'poweroff'); + + $this->entityManager->flush(); + + $this->logger->info('RemotePC: session deadline set', ['client_id' => $client->getId(), 'deadline' => $deadLine]); + + return new JsonResponse('', Response::HTTP_OK); + } + + private function findClientInLabAndOu(int $ouId, int $labId, int $clientId): ?Client + { + /** @var ClientRepository $repo */ + $repo = $this->entityManager->getRepository(Client::class); + + return $repo->findClientInLabAndOu($ouId, $labId, $clientId); + } + + private function createRemotePC(Client $client): RemotePC + { + $remotePC = new RemotePC(); + $remotePC->setClient($client); + $this->entityManager->persist($remotePC); + + return $remotePC; + } + + private function findPartitionForImage(Client $client, int $imageId): ?Partition + { + foreach ($client->getPartitions() as $partition) { + $iir = $partition->getImage(); + if ($iir && $iir->getImage() && $iir->getImage()->getId() === $imageId) { + return $partition; + } + } + + return null; + } + + private function startClient(Client $client, ?Partition $partition): void + { + if ($client->getStatus() === ClientStatus::OG_LIVE) { + if ($partition) { + $this->sendIniciarSesion($client, $partition); + } + + return; + } + + $offStatuses = [ClientStatus::OFF, ClientStatus::TURNING_OFF, ClientStatus::DISCONNECTED, null]; + + try { + if (in_array($client->getStatus(), $offStatuses, true)) { + $repository = $client->getRepository(); + if ($repository?->getIp()) { + $this->httpClient->request('POST', 'http://' . $repository->getIp() . ':8006/ogrepository/v1/wol', [ + 'json' => ['broadcast_ip' => '255.255.255.255', 'mac' => $client->getMac()], + ]); + $this->logger->info('RemotePC: WoL sent', ['mac' => $client->getMac()]); + } + } else { + $this->httpClient->request('POST', 'https://' . $client->getIp() . ':8000/opengnsys/reboot', [ + 'verify_host' => false, + 'headers' => ['Authorization' => $client->getToken()], + ]); + $this->logger->info('RemotePC: reboot sent', ['ip' => $client->getIp()]); + } + } catch (TransportExceptionInterface $e) { + $this->logger->warning('RemotePC: boot command failed', ['client_id' => $client->getId(), 'error' => $e->getMessage()]); + } + + if ($partition) { + $this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, [ + 'dsk' => $partition->getDiskNumber(), + 'par' => $partition->getPartitionNumber(), + ]); + } + } + + private function sendIniciarSesion(Client $client, Partition $partition): void + { + try { + $this->httpClient->request('POST', 'https://' . $client->getIp() . ':8000/opengnsys/IniciarSesion', [ + 'verify_host' => false, + 'json' => [ + 'nfn' => 'IniciarSesion', + 'dsk' => (string) $partition->getDiskNumber(), + 'par' => (string) $partition->getPartitionNumber(), + 'ids' => '0', + ], + 'headers' => ['Authorization' => $client->getToken()], + ]); + $client->setStatus(ClientStatus::INITIALIZING); + $this->entityManager->persist($client); + $this->logger->info('RemotePC: IniciarSesion sent', ['ip' => $client->getIp()]); + } catch (TransportExceptionInterface $e) { + $this->logger->warning('RemotePC: IniciarSesion failed', ['client_id' => $client->getId(), 'error' => $e->getMessage()]); + $this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, [ + 'dsk' => $partition->getDiskNumber(), + 'par' => $partition->getPartitionNumber(), + ]); + } + } + + private function sendPowerOff(Client $client): void + { + try { + $this->httpClient->request('POST', 'https://' . $client->getIp() . ':8000/opengnsys/poweroff', [ + 'verify_host' => false, + 'headers' => ['Authorization' => $client->getToken()], + ]); + } catch (TransportExceptionInterface $e) { + $this->logger->warning('RemotePC: poweroff failed', ['client_id' => $client->getId(), 'error' => $e->getMessage()]); + } + } + + private function createQueueEntry(Client $client, \DateTimeInterface $execTime, string $operation): void + { + $entry = new AgentQueue(); + $entry->setClient($client); + $entry->setExecTime($execTime); + $entry->setOperation($operation); + $this->entityManager->persist($entry); + } +} diff --git a/src/Dto/Input/ImageImageRepositoryInput.php b/src/Dto/Input/ImageImageRepositoryInput.php index b595bb2..80303e1 100644 --- a/src/Dto/Input/ImageImageRepositoryInput.php +++ b/src/Dto/Input/ImageImageRepositoryInput.php @@ -15,6 +15,10 @@ final class ImageImageRepositoryInput #[Groups(['image-image-repository:write'])] public ?string $description = ''; + #[Groups(['image-image-repository:write'])] + #[ApiProperty(description: 'Whether this image is available for Remote PC in this repository', example: false)] + public ?bool $remotePc = false; + public function __construct(?ImageImageRepository $imageImageRepository = null) { if (!$imageImageRepository) { @@ -22,6 +26,7 @@ final class ImageImageRepositoryInput } $this->description = $imageImageRepository->getDescription(); + $this->remotePc = $imageImageRepository->isRemotePc(); } public function createOrUpdateEntity(?ImageImageRepository $imageImageRepository = null): ImageImageRepository @@ -31,6 +36,7 @@ final class ImageImageRepositoryInput } $imageImageRepository->setDescription($this->description); + $imageImageRepository->setRemotePc($this->remotePc); return $imageImageRepository; } diff --git a/src/Dto/Input/ImageInput.php b/src/Dto/Input/ImageInput.php index f8f1f60..b611f4b 100644 --- a/src/Dto/Input/ImageInput.php +++ b/src/Dto/Input/ImageInput.php @@ -60,10 +60,6 @@ final class ImageInput #[ApiProperty(description: 'The parent of the image')] public ?int $version = null; - #[Groups(['image:write'])] - #[ApiProperty(description: 'The remote pc of the image')] - public ?bool $remotePc = false; - #[Groups(['image:write'])] #[ApiProperty(description: 'The global property of the image')] public ?bool $isGlobal = false; @@ -84,7 +80,6 @@ final class ImageInput $this->name = $image->getName(); $this->type = $image->getType(); - $this->remotePc = $image->isRemotePc(); $this->isGlobal = $image->isGlobal(); $this->version = $image->getVersion(); @@ -134,7 +129,6 @@ final class ImageInput } } - $image->setRemotePc($this->remotePc); $image->setIsGlobal($this->isGlobal); $partitionInfo = []; diff --git a/src/Dto/Input/ImageRepositoryInput.php b/src/Dto/Input/ImageRepositoryInput.php index f4e9089..2879813 100644 --- a/src/Dto/Input/ImageRepositoryInput.php +++ b/src/Dto/Input/ImageRepositoryInput.php @@ -39,7 +39,6 @@ final class ImageRepositoryInput #[ApiProperty(description: 'The sshPort of the repository', example: "Repository ssh port")] public ?string $sshPort = '22'; - public function __construct(?ImageRepository $repository = null) { if (!$repository) { diff --git a/src/Dto/Output/ImageImageRepositoryOutput.php b/src/Dto/Output/ImageImageRepositoryOutput.php index 6cfe2d8..a0eda0f 100644 --- a/src/Dto/Output/ImageImageRepositoryOutput.php +++ b/src/Dto/Output/ImageImageRepositoryOutput.php @@ -94,6 +94,13 @@ class ImageImageRepositoryOutput extends AbstractOutput )] public ?string $createdBy = null; + #[Groups(['image-image-repository:read', 'image:read'])] + #[ApiProperty( + description: 'Indica si esta imagen está disponible para Remote PC en este repositorio', + example: false + )] + public ?bool $remotePc = false; + public function __construct(ImageImageRepository $imageImageRepository, array $context = []) { parent::__construct($imageImageRepository); @@ -116,7 +123,8 @@ class ImageImageRepositoryOutput extends AbstractOutput $this->datasize = $imageImageRepository->getDatasize(); $this->size = $imageImageRepository->getSize(); $this->description = $imageImageRepository->getDescription(); - $this->createdAt = $imageImageRepository->getCreatedAt(); - $this->createdBy = $imageImageRepository->getCreatedBy(); + $this->remotePc = $imageImageRepository->isRemotePc(); + $this->createdAt = $imageImageRepository->getCreatedAt(); + $this->createdBy = $imageImageRepository->getCreatedBy(); } } \ No newline at end of file diff --git a/src/Dto/Output/ImageOutput.php b/src/Dto/Output/ImageOutput.php index 4ee6c2c..48e8284 100644 --- a/src/Dto/Output/ImageOutput.php +++ b/src/Dto/Output/ImageOutput.php @@ -20,13 +20,6 @@ final class ImageOutput extends AbstractOutput )] public ?string $name = ''; - #[Groups(['image:read', 'image-image-repository:read'])] - #[ApiProperty( - description: 'Indica si es una imagen de PC remoto', - example: false - )] - public ?bool $remotePc = null; - #[Groups(['image:read', 'image-image-repository:read'])] #[ApiProperty( description: 'Indica si la imagen es global', @@ -100,7 +93,6 @@ final class ImageOutput extends AbstractOutput $this->version = $image->getVersion(); $this->type = $image->getType(); $this->partitionInfo = json_decode($image->getPartitionInfo(), true); - $this->remotePc = $image->isRemotePc(); $this->isGlobal = $image->isGlobal(); $this->createdAt = $image->getCreatedAt(); $this->createdBy = $image->getCreatedBy(); diff --git a/src/Entity/AgentQueue.php b/src/Entity/AgentQueue.php new file mode 100644 index 0000000..5afc97f --- /dev/null +++ b/src/Entity/AgentQueue.php @@ -0,0 +1,57 @@ +client; + } + + public function setClient(Client $client): static + { + $this->client = $client; + + return $this; + } + + public function getExecTime(): \DateTimeInterface + { + return $this->execTime; + } + + public function setExecTime(\DateTimeInterface $execTime): static + { + $this->execTime = $execTime; + + return $this; + } + + public function getOperation(): string + { + return $this->operation; + } + + public function setOperation(string $operation): static + { + $this->operation = $operation; + + return $this; + } +} diff --git a/src/Entity/Client.php b/src/Entity/Client.php index 79d9eaf..49eee77 100644 --- a/src/Entity/Client.php +++ b/src/Entity/Client.php @@ -100,6 +100,9 @@ class Client extends AbstractEntity #[ORM\Column(type: 'text', nullable: true)] private ?string $notes = null; + #[ORM\OneToOne(mappedBy: 'client', cascade: ['persist', 'remove'])] + private ?RemotePC $remotePC = null; + public function __construct() { parent::__construct(); @@ -400,4 +403,16 @@ class Client extends AbstractEntity return $this; } + + public function getRemotePC(): ?RemotePC + { + return $this->remotePC; + } + + public function setRemotePC(?RemotePC $remotePC): static + { + $this->remotePC = $remotePC; + + return $this; + } } diff --git a/src/Entity/Image.php b/src/Entity/Image.php index 5324aeb..09e51fe 100644 --- a/src/Entity/Image.php +++ b/src/Entity/Image.php @@ -19,9 +19,6 @@ class Image extends AbstractEntity #[ORM\JoinColumn(nullable: true)] private ?SoftwareProfile $softwareProfile = null; - #[ORM\Column] - private ?bool $remotePc = null; - #[ORM\Column(length: 255, nullable: true)] private ?string $partitionInfo = null; @@ -65,18 +62,6 @@ class Image extends AbstractEntity return $this; } - public function isRemotePc(): ?bool - { - return $this->remotePc; - } - - public function setRemotePc(bool $remotePc): static - { - $this->remotePc = $remotePc; - - return $this; - } - public function getPartitionInfo(): ?string { return $this->partitionInfo; diff --git a/src/Entity/ImageImageRepository.php b/src/Entity/ImageImageRepository.php index fc9fd55..ea6fc2d 100644 --- a/src/Entity/ImageImageRepository.php +++ b/src/Entity/ImageImageRepository.php @@ -38,6 +38,9 @@ class ImageImageRepository extends AbstractEntity #[ORM\Column(nullable: true)] private ?int $version = null; + #[ORM\Column(nullable: true)] + private ?bool $remotePc = false; + #[ORM\Column(length: 255, nullable: true)] private ?string $description = null; @@ -152,6 +155,18 @@ class ImageImageRepository extends AbstractEntity return $this; } + public function isRemotePc(): ?bool + { + return $this->remotePc; + } + + public function setRemotePc(?bool $remotePc): static + { + $this->remotePc = $remotePc; + + return $this; + } + public function getDescription(): ?string { return $this->description; diff --git a/src/Entity/ImageRepository.php b/src/Entity/ImageRepository.php index 64bc645..f4305cc 100644 --- a/src/Entity/ImageRepository.php +++ b/src/Entity/ImageRepository.php @@ -120,4 +120,5 @@ class ImageRepository extends AbstractEntity return $this; } + } diff --git a/src/Entity/RemotePC.php b/src/Entity/RemotePC.php new file mode 100644 index 0000000..f9edafd --- /dev/null +++ b/src/Entity/RemotePC.php @@ -0,0 +1,78 @@ +client; + } + + public function setClient(Client $client): static + { + $this->client = $client; + + return $this; + } + + public function getReservedUntil(): ?\DateTimeInterface + { + return $this->reservedUntil; + } + + public function setReservedUntil(?\DateTimeInterface $reservedUntil): static + { + $this->reservedUntil = $reservedUntil; + + return $this; + } + + public function isReservedActive(): bool + { + return $this->reservedUntil !== null && $this->reservedUntil > new \DateTime(); + } + + public function getUrlLogin(): ?string + { + return $this->urlLogin; + } + + public function setUrlLogin(?string $urlLogin): static + { + $this->urlLogin = $urlLogin; + + return $this; + } + + public function getUrlLogout(): ?string + { + return $this->urlLogout; + } + + public function setUrlLogout(?string $urlLogout): static + { + $this->urlLogout = $urlLogout; + + return $this; + } +} diff --git a/src/EventListener/UdsSyncOnClientStatusListener.php b/src/EventListener/UdsSyncOnClientStatusListener.php new file mode 100644 index 0000000..268e160 --- /dev/null +++ b/src/EventListener/UdsSyncOnClientStatusListener.php @@ -0,0 +1,63 @@ +getObject(); + + if (!$entity instanceof Client) { + return; + } + + $changeSet = $args->getObjectManager()->getUnitOfWork()->getEntityChangeSet($entity); + + if (!array_key_exists('status', $changeSet)) { + return; + } + + $ou = $entity->getOrganizationalUnit(); + if (!$ou || !$ou->getRemoteCalendar()) { + return; + } + + $this->syncNeeded = true; + } + + public function postFlush(PostFlushEventArgs $args): void + { + if (!$this->syncNeeded) { + return; + } + + $this->syncNeeded = false; + + try { + $this->udsClient->__invoke(); + $this->logger->info('UDS sync triggered by client status change'); + } catch (\Throwable $e) { + $this->logger->warning('UDS sync failed after client status change', ['error' => $e->getMessage()]); + } + } +} diff --git a/src/Repository/AgentQueueRepository.php b/src/Repository/AgentQueueRepository.php new file mode 100644 index 0000000..46c75cd --- /dev/null +++ b/src/Repository/AgentQueueRepository.php @@ -0,0 +1,27 @@ + + */ +class AgentQueueRepository extends AbstractRepository +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, AgentQueue::class); + } + + public function deleteByClientAndOperations(Client $client, array $operations): void + { + $this->getEntityManager() + ->createQuery('DELETE FROM App\Entity\AgentQueue aq WHERE aq.client = :client AND aq.operation IN (:operations)') + ->setParameter('client', $client) + ->setParameter('operations', $operations) + ->execute(); + } +} diff --git a/src/Repository/ClientRepository.php b/src/Repository/ClientRepository.php index 392b257..65b9d68 100644 --- a/src/Repository/ClientRepository.php +++ b/src/Repository/ClientRepository.php @@ -161,6 +161,58 @@ class ClientRepository extends AbstractRepository return (int) $qb->getQuery()->getSingleScalarResult(); } + public function findBestAvailableClientForImage(int $ouId, int $imageId, ?int $labId = null): ?Client + { + $centerPath = $this->getEntityManager() + ->createQuery('SELECT o.path FROM App\Entity\OrganizationalUnit o WHERE o.id = :id') + ->setParameter('id', $ouId) + ->getSingleScalarResult(); + $qb = $this->getEntityManager()->createQueryBuilder(); + $qb->select('c') + ->from(Client::class, 'c') + ->join('c.organizationalUnit', 'lab') + ->join('c.partitions', 'p') + ->join('p.image', 'iir') + ->join('iir.image', 'img') + ->leftJoin('c.remotePC', 'rpc') + ->where('lab.path LIKE :pathPrefix') + ->andWhere('lab.remotePc = true') + ->andWhere('img.id = :imageId') + ->andWhere('iir.remotePc = true') + ->andWhere('c.maintenance = false') + ->andWhere('(rpc.reservedUntil IS NULL OR rpc.reservedUntil < :now)') + ->setParameter('pathPrefix', $centerPath . '%') + ->setParameter('imageId', $imageId) + ->setParameter('now', new \DateTime()) + ->orderBy('rpc.reservedUntil', 'ASC') + ->setMaxResults(1); + if ($labId !== null) { + $qb->andWhere('lab.id = :labId')->setParameter('labId', $labId); + } + + return $qb->getQuery()->getOneOrNullResult(); + } + + public function findClientInLabAndOu(int $ouId, int $labId, int $clientId): ?Client + { + $centerPath = $this->getEntityManager() + ->createQuery('SELECT o.path FROM App\Entity\OrganizationalUnit o WHERE o.id = :id') + ->setParameter('id', $ouId) + ->getSingleScalarResult(); + + $qb = $this->getEntityManager()->createQueryBuilder(); + $qb->select('c') + ->from(Client::class, 'c') + ->join('c.organizationalUnit', 'lab') + ->where('lab.path LIKE :pathPrefix') + ->andWhere('lab.id = :labId') + ->andWhere('c.id = :clientId') + ->setParameter('pathPrefix', $centerPath . '%') + ->setParameter('labId', $labId) + ->setParameter('clientId', $clientId); + + return $qb->getQuery()->getOneOrNullResult(); + } } diff --git a/src/Repository/RemotePCRepository.php b/src/Repository/RemotePCRepository.php new file mode 100644 index 0000000..e4235de --- /dev/null +++ b/src/Repository/RemotePCRepository.php @@ -0,0 +1,17 @@ + + */ +class RemotePCRepository extends AbstractRepository +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, RemotePC::class); + } +} diff --git a/src/Service/UDS/UDSClient.php b/src/Service/UDS/UDSClient.php index f3a1c1b..0138801 100644 --- a/src/Service/UDS/UDSClient.php +++ b/src/Service/UDS/UDSClient.php @@ -4,6 +4,7 @@ namespace App\Service\UDS; use AllowDynamicProperties; use App\Entity\OrganizationalUnit; +use App\Model\ClientStatus; use Doctrine\ORM\EntityManagerInterface; use Psr\Log\LoggerInterface; use Symfony\Component\HttpClient\Exception\TransportException; @@ -60,6 +61,8 @@ class UDSClient $this->login(); $servicePools = $this->getServicePools(); + $results = []; + foreach ($servicePools as $servicePool) { $servicePoolInfo = $this->getServicePool($servicePool['provider_id'], $servicePool['service_id']); @@ -82,8 +85,10 @@ class UDSClient 'body' => json_encode($servicePool) ]); - return json_decode($response->getContent(false), true); + $results[] = json_decode($response->getContent(false), true); } + + return $results; } /** @@ -202,7 +207,7 @@ class UDSClient } $status = $client->getStatus(); - $clientAvailable = in_array($status, ['active', 'windows', 'linux']); + $clientAvailable = in_array($status, [ClientStatus::OG_LIVE, ClientStatus::WINDOWS, ClientStatus::LINUX]); $totalAvailableClients += $clientAvailable ? 1 : 0; } -- 2.40.1