302 lines
12 KiB
PHP
302 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Controller\UDS;
|
|
|
|
use App\Entity\AgentQueue;
|
|
use App\Entity\Client;
|
|
use App\Entity\Partition;
|
|
use App\Entity\RemotePC;
|
|
use App\Model\ClientStatus;
|
|
use App\Model\CommandTypes;
|
|
use App\Model\TraceStatus;
|
|
use App\Repository\AgentQueueRepository;
|
|
use App\Repository\ClientRepository;
|
|
use App\Service\Trace\CreateService;
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
use Psr\Log\LoggerInterface;
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\HttpFoundation\JsonResponse;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
use Symfony\Component\HttpKernel\Attribute\AsController;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
|
|
|
#[AsController]
|
|
class RemotePcController extends AbstractController
|
|
{
|
|
private const QUEUE_OPERATIONS = ['popup-10', 'popup-5', 'poweroff'];
|
|
|
|
public function __construct(
|
|
private readonly EntityManagerInterface $entityManager,
|
|
private readonly HttpClientInterface $httpClient,
|
|
private readonly LoggerInterface $logger,
|
|
private readonly CreateService $createService,
|
|
) {
|
|
}
|
|
|
|
#[Route('/opengnsys/rest/ous/{ouid}/images/{imageId}/reserve', methods: ['POST'])]
|
|
#[Route('/opengnsys/rest//ous/{ouid}/images/{imageId}/reserve', methods: ['POST'])]
|
|
public function reserve(int $ouid, int $imageId, Request $request): JsonResponse
|
|
{
|
|
$data = $request->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);
|
|
}
|
|
}
|