Merge branch 'main' into develop
testing/ogcore-api/pipeline/pr-main Build queued... Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details

pull/103/head
Manuel Aranda Rosales 2026-05-05 10:14:08 +02:00
commit 4aa57fa984
11 changed files with 582 additions and 78 deletions

View File

@ -0,0 +1,305 @@
# Integración RemotePC: UDS ↔ ogcore — Flujo y bugs corregidos
## Flujo de reserva de host
### Visión general
UDS actúa como broker de escritorios remotos. Cuando un usuario solicita una sesión, UDS llama a ogcore para reservar una máquina física, arrancarla en el SO correcto y notificar el login/logout.
### Endpoints implicados
| Método | Ruta | Descripción |
|--------|------|-------------|
| `POST` | `/opengnsys/rest/ous/{ouid}/images/{imageId}/reserve` | Reserva un cliente disponible |
| `POST` | `/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/events` | Registra URLs de callback login/logout |
| `POST` | `/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/session` | Define el tiempo máximo de sesión |
| `DELETE` | `/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/unreserve` | Libera la reserva y apaga el cliente |
---
### Flujo detallado: `POST /reserve`
```
UDS → POST /reserve {labid, maxtime}
```
**1. Selección del cliente** (`ClientRepository::findBestAvailableClientForImage`)
La query busca el primer cliente que cumpla todos estos criterios:
- Pertenece a una OU bajo el path del centro (`ouid`)
- El laboratorio tiene `remotePc = true`
- Tiene una partición con la imagen solicitada donde `iir.remotePc = true`
- No está en mantenimiento
- No tiene reserva activa (`reservedUntil IS NULL` o ya expiró)
- Si se pasó `labId`, filtra además por laboratorio
- Ordena por `reservedUntil ASC` (prioriza el liberado hace más tiempo)
- Si no hay cliente disponible → HTTP 404
**2. Búsqueda de la partición**
Se itera sobre las particiones del cliente para encontrar la que contiene la imagen solicitada.
**3. Arranque del cliente** (`startClient`) — máximo 2s por llamada HTTP
Hay tres ramas según el estado actual del cliente:
| Estado del cliente | Acción |
|--------------------|--------|
| `OG_LIVE` | Envía `IniciarSesion` directamente al agente (`https://{ip}:8000/opengnsys/IniciarSesion`) con disco y partición. Si falla, crea traza LOGIN pendiente. |
| `OFF` / `TURNING_OFF` / `DISCONNECTED` / `null` | Envía Wake-on-LAN al ogrepository (`http://{repo}:8006/ogrepository/v1/wol`). Crea traza LOGIN pendiente para cuando arranque en OGLive. |
| Cualquier otro (Windows, Linux…) | Envía `Reiniciar` al agente (`https://{ip}:8000/opengnsys/Reiniciar`). Crea traza LOGIN pendiente. |
**4. Registro de la reserva**
- Se crea la entidad `RemotePC` si no existe
- Se fija `reservedUntil = ahora + maxTime horas`
- Se limpian `urlLogin` y `urlLogout`
- Se persiste en BD
**5. Respuesta a UDS**
```json
{ "id": 3, "name": "PC-01", "ip": "172.16.53.196", "mac": "00:1B:...", "lab": {"id": 2}, "ou": {"id": 1} }
```
---
### Flujo posterior al reserve
```
UDS → POST /events { urlLogin, urlLogout }
ogcore guarda las URLs de callback en RemotePC
Máquina arranca en OGLive
ogagent OGLive → POST /ogAdmClient/InclusionCliente
ogcore: status = OG_LIVE
Command processor (cron cada minuto)
Encuentra traza LOGIN PENDING
Cliente en OG_LIVE → llama LoginAction → envía IniciarSesion
Máquina arranca Windows/Linux
ogagent Windows/Linux → POST /ogagent/started
ogcore: status = WINDOWS (o LINUX)
Usuario hace login en el SO
ogagent → POST /ogagent/loggedin
ogcore llama urlLogin de UDS ← UDS sabe que la sesión está lista
UDS → POST /session { deadLine: N }
ogcore encola: popup-10, popup-5, poweroff en AgentQueue
Usuario hace logout
ogagent → POST /ogagent/loggedout
ogcore llama urlLogout de UDS
UDS → DELETE /unreserve
ogcore: limpia reserva, borra AgentQueue y trazas LOGIN PENDING, envía Apagar
```
---
## Bugs identificados y corregidos
### Bug 1 — ogagent: POST con body vacío devuelve 500 antes de ejecutar el handler
**Fichero:** `ogagent/src/opengnsys/httpserver.py`
**Problema:** `do_POST` intentaba parsear el body como JSON siempre. Cuando ogcore enviaba `Reiniciar` o `Apagar` sin body (`Content-Length: 0`), `json.loads("")` lanzaba `JSONDecodeError`. El método llamaba a `sendJsonError(500)` pero **sin `return`**, de modo que continuaba ejecutando `notifyMessage` y enviaba un segundo response 200. El cliente (ogcore) recibía el primero: el 500.
Síntoma visible en logs del agente Windows:
```
(do_POST) length: 0, content >><<
(log_message) HTTP "POST /opengnsys/Reiniciar HTTP/1.1" 500 - ← enviado primero
(process_Reiniciar) Received reboot operation
(log_message) HTTP "POST /opengnsys/Reiniciar HTTP/1.1" 200 - ← ignorado por ogcore
```
**Fix:**
```python
# antes
length = int(self.headers.get('content-length'))
content = self.rfile.read(length).decode('utf-8')
post_params = json.loads(content)
except Exception as e:
self.sendJsonError(500, exceptionToMessage(e))
# sin return → continuaba ejecutando notifyMessage
# después
length = int(self.headers.get('content-length', 0))
if length > 0:
content = self.rfile.read(length).decode('utf-8')
logger.debug('length: {0}, content >>{1}<<'.format(length, content))
post_params = json.loads(content)
else:
logger.debug('length: 0, content >><<')
except Exception as e:
self.sendJsonError(500, exceptionToMessage(e))
return # ← impide llamar a notifyMessage tras el error
```
---
### Bug 2 — ogcore: excepciones HTTP 5xx no capturadas en startClient / sendIniciarSesion
**Fichero:** `src/Controller/UDS/RemotePcController.php`
**Problema:** Los bloques `try/catch` solo capturaban `TransportExceptionInterface` (errores de red). Cuando el agente devolvía HTTP 500, Symfony lanzaba `ServerExceptionInterface` (subclase de `HttpExceptionInterface`), que no era capturada. La excepción escalaba hasta el handler global de Symfony, que devolvía un error Hydra 500 a UDS:
```json
{
"@type": "hydra:Error",
"hydra:description": "HTTP/1.0 500 Internal Server Error returned for \"https://172.16.53.196:8000/opengnsys/Reiniciar\"."
}
```
UDS interpretaba la reserva como fallida y llamaba a `unreserve` → `Apagar`.
**Fix:**
```php
// antes
} catch (TransportExceptionInterface $e) {
// después
} catch (TransportExceptionInterface | HttpExceptionInterface $e) {
```
Aplicado en `startClient` y `sendIniciarSesion`.
---
### Bug 3 — ogcore: sin timeout en llamadas HTTP al agente → UDS recibe read timeout
**Fichero:** `src/Controller/UDS/RemotePcController.php`
**Problema:** Las llamadas HTTP a `IniciarSesion`, `Reiniciar`, WoL y `Apagar` no tenían timeout. Para `NativeHttpClient` (modo síncrono), `request()` bloqueaba hasta recibir respuesta o agotar el socket timeout del sistema. Se observó que `Apagar` bloqueó 35 segundos:
```
21:38:47 Request: "POST .../Apagar"
21:39:23 WARNING: poweroff failed ← 35 segundos después
```
UDS tiene un read timeout de 10 segundos, por lo que siempre agotaba el tiempo de espera. Esto provocaba que UDS llamase a `unreserve` inmediatamente después de un `reserve` aparentemente exitoso.
**Referencia:** El código antiguo (`opengnsys/admin/WebConsole/includes/restfunctions.php`) usaba `multiRequest()` con `CURLOPT_TIMEOUT_MS => 500`.
**Fix:** Añadir `timeout: 2.0` y `->getStatusCode()` en todas las llamadas. El `getStatusCode()` es necesario para forzar la resolución de la respuesta en clientes async (`CurlHttpClient`), ya que sin él el timeout nunca se aplica:
```php
$this->httpClient->request('POST', 'https://' . $client->getIp() . ':8000/opengnsys/IniciarSesion', [
'verify_host' => false,
'timeout' => 2.0,
'json' => [...],
'headers' => ['Authorization' => $client->getToken()],
])->getStatusCode();
```
Aplicado en: `sendIniciarSesion`, `startClient` (Reiniciar y WoL) y `sendPowerOff`.
---
### Bug 4 — ogcore: executeLogin no encontraba la partición (mismatch de formato)
**Fichero:** `src/Command/ExecutePendingTracesCommand.php`
**Problema:** `RemotePcController::startClient` creaba las trazas LOGIN con `{dsk: N, par: N}` (números de disco/partición). `ExecutePendingTracesCommand::executeLogin` esperaba `{partition: UUID}`. El mismatch causaba el error:
```json
{"error": "Partition not found in trace input", "input": {"dsk": 1, "par": 1}}
```
La traza fallaba e `IniciarSesion` nunca se enviaba cuando la máquina llegaba a OGLive.
**Fix:** Soportar ambos formatos en `executeLogin`:
```php
if (isset($input['partition'])) {
$partition = $repo->findOneBy(['uuid' => $input['partition']]);
} elseif (isset($input['dsk']) && isset($input['par'])) {
$partition = $repo->findOneBy([
'client' => $client,
'diskNumber' => $input['dsk'],
'partitionNumber' => $input['par'],
]);
} else {
throw new \Exception("Partition not found in trace input");
}
```
---
### Bug 5 — ogcore: LoginAction creaba trazas de retry con input vacío
**Fichero:** `src/Controller/OgAgent/LoginAction.php`
**Problema:** Cuando el cliente no estaba en `OG_LIVE` o `IniciarSesion` fallaba, `LoginAction` creaba nuevas trazas PENDING con input `[]` vacío:
```php
$this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, []);
```
Estas trazas eran recogidas por el command processor y fallaban con "Partition not found in trace input" (Bug 4).
**Fix:** Propagar la información de partición a las trazas de retry:
```php
$partitionInput = [
'dsk' => $partition->getDiskNumber(),
'par' => $partition->getPartitionNumber(),
];
$this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, $partitionInput);
```
---
### Bug 6 — ogcore: bucle infinito de trazas LOGIN cuando el cliente está apagado
**Ficheros:** `src/Command/ExecutePendingTracesCommand.php` y `src/Controller/UDS/RemotePcController.php`
**Problema:** Cuando el cliente estaba en estado `off` o `windows`:
1. El command processor encontraba una traza LOGIN PENDING
2. Llamaba a `loginAction->__invoke`
3. `LoginAction` detectaba que el cliente no estaba en OG_LIVE, creaba **otra traza LOGIN PENDING** y devolvía 200
4. `executeLogin` marcaba la traza original como `SUCCESS`
5. La nueva traza era recogida el siguiente minuto → vuelta al paso 2
Adicionalmente, al hacer `unreserve` las trazas LOGIN PENDING del cliente no se eliminaban. El código antiguo sí borraba los comandos pendientes de la tabla `acciones`:
```sql
DELETE FROM acciones
WHERE idordenador = '$clntid'
AND descriaccion = 'RemotePC Session';
```
El nuevo ogcore no tenía equivalente, por lo que las trazas LOGIN sobrevivían al unreserve y seguían ejecutándose.
Síntoma observable: la máquina entraba en bucle continuo de reinicios.
**Fix A — executeLogin espera a que el cliente esté en OG_LIVE:**
```php
if ($client->getStatus() !== ClientStatus::OG_LIVE) {
$this->logger->info('Login trace deferred: client not in OGLive', [
'client' => $client->getUuid(),
'status' => $client->getStatus(),
]);
return false; // la traza queda PENDING hasta que el cliente esté en OGLive
}
```
**Fix B — unreserve elimina las trazas LOGIN pendientes:**
```php
$this->entityManager->createQuery(
'DELETE FROM App\Entity\Trace t
WHERE t.client = :client
AND t.command = :command
AND t.status = :status'
)
->setParameter('client', $client)
->setParameter('command', CommandTypes::LOGIN)
->setParameter('status', TraceStatus::PENDING)
->execute();
```
---
## Resumen de ficheros modificados
| Repositorio | Fichero | Bugs corregidos |
|-------------|---------|-----------------|
| `ogagent` | `src/opengnsys/httpserver.py` | #1 |
| `ogcore` | `src/Controller/UDS/RemotePcController.php` | #2, #3, #6B |
| `ogcore` | `src/Controller/OgAgent/LoginAction.php` | #5 |
| `ogcore` | `src/Command/ExecutePendingTracesCommand.php` | #4, #6A |

View File

@ -507,16 +507,33 @@ class ExecutePendingTracesCommand extends Command
private function executeLogin(Trace $trace, array $input): bool
{
$client = $trace->getClient();
if (!isset($input['partition'])) {
throw new \Exception("Partition not found in trace input");
if ($client->getStatus() !== ClientStatus::OG_LIVE) {
$this->logger->info('Login trace deferred: client not in OGLive', [
'client' => $client->getUuid(),
'status' => $client->getStatus(),
]);
return false;
}
$partition = $this->entityManager->getRepository(\App\Entity\Partition::class)
->findOneBy(['uuid' => $input['partition']]);
if (!$partition) {
throw new \Exception("Partition not found with UUID: {$input['partition']}");
if (isset($input['partition'])) {
$partition = $this->entityManager->getRepository(Partition::class)
->findOneBy(['uuid' => $input['partition']]);
if (!$partition) {
throw new \Exception("Partition not found with UUID: {$input['partition']}");
}
} elseif (isset($input['dsk']) && isset($input['par'])) {
$partition = $this->entityManager->getRepository(Partition::class)
->findOneBy([
'client' => $client,
'diskNumber' => $input['dsk'],
'partitionNumber' => $input['par'],
]);
if (!$partition) {
throw new \Exception("Partition not found for disk {$input['dsk']} partition {$input['par']}");
}
} else {
throw new \Exception("Partition not found in trace input");
}
$bootClientsInput = new BootClientsInput();

View File

@ -52,8 +52,13 @@ class LoginAction extends AbstractOgAgentController
throw new BadRequestHttpException('IP is required');
}
$partitionInput = [
'dsk' => $partition->getDiskNumber(),
'par' => $partition->getPartitionNumber(),
];
if ($client->getStatus() !== ClientStatus::OG_LIVE) {
$this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, []);
$this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, $partitionInput);
continue;
}
@ -74,7 +79,7 @@ class LoginAction extends AbstractOgAgentController
);
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
$this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, []);
$this->createService->__invoke($client, CommandTypes::LOGIN, TraceStatus::PENDING, null, $partitionInput);
continue;
}

View File

@ -26,6 +26,11 @@ class AgentSessionController extends AbstractController
) {
}
private function toHttps(string $url): string
{
return str_starts_with($url, 'http://') ? 'https://' . substr($url, 7) : $url;
}
#[Route('/opengnsys/rest/ogagent/started', methods: ['POST'])]
public function agentStarted(Request $request): JsonResponse
{
@ -63,6 +68,21 @@ class AgentSessionController extends AbstractController
$this->entityManager->persist($client);
$this->entityManager->flush();
// Notify UDS the machine is now running the session OS and ready for connection.
$remotePC = $client->getRemotePC();
if ($remotePC && $remotePC->isReservedActive() && $remotePC->getUrlLogin()) {
try {
$url = $this->toHttps($remotePC->getUrlLogin());
$status = $this->httpClient->request('GET', $url, [
'verify_peer' => false,
'verify_host' => false,
])->getStatusCode();
$this->logger->info('RemotePC: urlLogin called on agent start', ['ip' => $data['ip'], 'status' => $status]);
} catch (\Throwable $e) {
$this->logger->warning('RemotePC: urlLogin on agent start failed', ['ip' => $data['ip'], 'error' => $e->getMessage()]);
}
}
$this->logger->info('Client started', [
'mac' => $data['mac'],
'ip' => $data['ip'],
@ -143,11 +163,12 @@ class AgentSessionController extends AbstractController
$remotePC = $client->getRemotePC();
if ($remotePC && $remotePC->isReservedActive() && $remotePC->getUrlLogin()) {
try {
$this->httpClient->request('POST', $remotePC->getUrlLogin(), [
$url = $this->toHttps($remotePC->getUrlLogin());
$status = $this->httpClient->request('GET', $url, [
'verify_peer' => false,
'verify_host' => false,
'body' => $request->getContent(),
'headers' => ['Content-Type' => 'application/json'],
]);
])->getStatusCode();
$this->logger->info('RemotePC: loggedin callback sent', ['ip' => $client->getIp(), 'status' => $status]);
} catch (\Throwable $e) {
$this->logger->warning('RemotePC: loggedin callback failed', ['ip' => $client->getIp(), 'error' => $e->getMessage()]);
}
@ -205,11 +226,12 @@ class AgentSessionController extends AbstractController
$remotePC = $client->getRemotePC();
if ($remotePC && $remotePC->isReservedActive() && $remotePC->getUrlLogout()) {
try {
$this->httpClient->request('POST', $remotePC->getUrlLogout(), [
$url = $this->toHttps($remotePC->getUrlLogout());
$status = $this->httpClient->request('GET', $url, [
'verify_peer' => false,
'verify_host' => false,
'body' => $request->getContent(),
'headers' => ['Content-Type' => 'application/json'],
]);
])->getStatusCode();
$this->logger->info('RemotePC: loggedout callback sent', ['ip' => $client->getIp(), 'status' => $status]);
} catch (\Throwable $e) {
$this->logger->warning('RemotePC: loggedout callback failed', ['ip' => $client->getIp(), 'error' => $e->getMessage()]);
}

View File

@ -47,6 +47,7 @@ class StatusController extends AbstractController
const string REFRESH = 'RESPUESTA_Actualizar';
const string SOFTWARE_INVENTORY = 'RESPUESTA_InventarioSoftware';
const string RUN_SCRIPT = 'RESPUESTA_EjecutarScript';
const string INICIAR_SESION = 'RESPUESTA_IniciarSesion';
public function __construct(
protected readonly EntityManagerInterface $entityManager,
@ -54,6 +55,7 @@ class StatusController extends AbstractController
protected readonly CreatePartitionService $createPartitionService,
protected readonly LoggerInterface $logger,
protected readonly CreateService $createService,
protected readonly HttpClientInterface $httpClient,
)
{
}
@ -355,6 +357,41 @@ class StatusController extends AbstractController
$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()]);
}
}
} 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,
]);
}
}
}
return new JsonResponse(data: 'Webhook finished', status: Response::HTTP_OK);
}

View File

@ -93,18 +93,12 @@ class OrganizationalUnitController extends AbstractController
->getRepository(ImageImageRepository::class)
->findBy(['remotePc' => true]);
$seen = [];
$data = [];
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' => $iir->getId(),
'name' => $iir->getName(),
'inremotepc' => true,
'ou' => ['id' => $centerId],
];

View File

@ -6,6 +6,7 @@ use App\Entity\AgentQueue;
use App\Entity\Client;
use App\Entity\Partition;
use App\Entity\RemotePC;
use App\Entity\Trace;
use App\Model\ClientStatus;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
@ -20,6 +21,7 @@ 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\HttpExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
@ -44,15 +46,35 @@ class RemotePcController extends AbstractController
$labId = isset($data['labid']) && $data['labid'] !== 0 ? (int) $data['labid'] : null;
$maxTime = (int) ($data['maxtime'] ?? 24);
$this->logger->info('RemotePC: reserve requested', [
'ouid' => $ouid,
'imageId' => $imageId,
'labId' => $labId,
]);
/** @var ClientRepository $clientRepo */
$clientRepo = $this->entityManager->getRepository(Client::class);
$client = $clientRepo->findBestAvailableClientForImage($ouid, $imageId, $labId);
if (!$client) {
$this->logReserveDiagnostics($ouid, $imageId, $labId);
return new JsonResponse(['message' => 'No available client found for this image'], Response::HTTP_NOT_FOUND);
}
$partition = $this->findPartitionForImage($client, $imageId);
if (!$partition) {
$iirIds = array_map(
fn($p) => $p->getImage()?->getId(),
$client->getPartitions()->toArray()
);
$this->logger->info('RemotePC: partition not found for imageId on client', [
'client_id' => $client->getId(),
'imageId_requested' => $imageId,
'iir_ids_on_client' => $iirIds,
]);
}
$this->startClient($client, $partition);
$remotePC = $client->getRemotePC() ?? $this->createRemotePC($client);
@ -63,20 +85,68 @@ class RemotePcController extends AbstractController
$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([
$responseData = [
'id' => $client->getId(),
'name' => $client->getName(),
'ip' => $client->getIp(),
'mac' => $client->getMac(),
'lab' => ['id' => $lab?->getId()],
'ou' => ['id' => $ouid],
], Response::HTTP_OK);
];
$this->logger->info('RemotePC: reserve response 200', [
'client_id' => $client->getId(),
'image_id' => $imageId,
'reserved_until' => $remotePC->getReservedUntil()->format('Y-m-d H:i:s'),
'response' => $responseData,
]);
return new JsonResponse($responseData, Response::HTTP_OK);
}
#[Route('/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/status', methods: ['GET'])]
#[Route('/opengnsys/rest//ous/{ouid}/labs/{labId}/clients/{clientId}/status', methods: ['GET'])]
public function status(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);
}
$statusMap = [
ClientStatus::OFF => 'off',
ClientStatus::INITIALIZING => 'initializing',
ClientStatus::DISCONNECTED => 'off',
ClientStatus::TURNING_OFF => 'off',
ClientStatus::OG_LIVE => 'oglive',
ClientStatus::BUSY => 'busy',
ClientStatus::LINUX => 'linux',
ClientStatus::LINUX_SESSION => 'linux',
ClientStatus::MACOS => 'macos',
ClientStatus::MACOS_SESSION => 'macos',
ClientStatus::WINDOWS => 'windows',
ClientStatus::WINDOWS_SESSION => 'windows',
];
$clientStatus = $client->getStatus();
$apiStatus = $statusMap[$clientStatus] ?? 'unknown';
$loggedIn = in_array($clientStatus, [
ClientStatus::LINUX_SESSION,
ClientStatus::MACOS_SESSION,
ClientStatus::WINDOWS_SESSION,
], true);
$response = [
'id' => $client->getId(),
'ip' => $client->getIp(),
'status' => $apiStatus,
];
if ($loggedIn) {
$response['loggedin'] = true;
}
return new JsonResponse($response, Response::HTTP_OK);
}
#[Route('/opengnsys/rest/ous/{ouid}/labs/{labId}/clients/{clientId}/unreserve', methods: ['DELETE'])]
@ -102,6 +172,17 @@ class RemotePcController extends AbstractController
$queueRepo = $this->entityManager->getRepository(AgentQueue::class);
$queueRepo->deleteByClientAndOperations($client, self::QUEUE_OPERATIONS);
$this->entityManager->createQuery(
'DELETE FROM App\Entity\Trace t
WHERE t.client = :client
AND t.command = :command
AND t.status = :status'
)
->setParameter('client', $client)
->setParameter('command', CommandTypes::LOGIN)
->setParameter('status', TraceStatus::PENDING)
->execute();
$this->sendPowerOff($client);
$this->logger->info('RemotePC: client unreserved', ['client_id' => $client->getId()]);
@ -205,7 +286,7 @@ class RemotePcController extends AbstractController
{
foreach ($client->getPartitions() as $partition) {
$iir = $partition->getImage();
if ($iir && $iir->getImage() && $iir->getImage()->getId() === $imageId) {
if ($iir && $iir->getId() === $imageId) {
return $partition;
}
}
@ -230,18 +311,20 @@ class RemotePcController extends AbstractController
$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()],
]);
'json' => ['broadcast_ip' => '255.255.255.255', 'mac' => $client->getMac()],
'timeout' => 2.0,
])->getStatusCode();
$this->logger->info('RemotePC: WoL sent', ['mac' => $client->getMac()]);
}
} else {
$this->httpClient->request('POST', 'https://' . $client->getIp() . ':8000/opengnsys/Reiniciar', [
'verify_host' => false,
'timeout' => 2.0,
'headers' => ['Authorization' => $client->getToken()],
]);
])->getStatusCode();
$this->logger->info('RemotePC: reboot sent', ['ip' => $client->getIp()]);
}
} catch (TransportExceptionInterface $e) {
} catch (TransportExceptionInterface | HttpExceptionInterface $e) {
$this->logger->warning('RemotePC: boot command failed', ['client_id' => $client->getId(), 'error' => $e->getMessage()]);
}
@ -258,6 +341,7 @@ class RemotePcController extends AbstractController
try {
$this->httpClient->request('POST', 'https://' . $client->getIp() . ':8000/opengnsys/IniciarSesion', [
'verify_host' => false,
'timeout' => 2.0,
'json' => [
'nfn' => 'IniciarSesion',
'dsk' => (string) $partition->getDiskNumber(),
@ -265,11 +349,11 @@ class RemotePcController extends AbstractController
'ids' => '0',
],
'headers' => ['Authorization' => $client->getToken()],
]);
])->getStatusCode();
$client->setStatus(ClientStatus::INITIALIZING);
$this->entityManager->persist($client);
$this->logger->info('RemotePC: IniciarSesion sent', ['ip' => $client->getIp()]);
} catch (TransportExceptionInterface $e) {
} catch (TransportExceptionInterface | HttpExceptionInterface $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(),
@ -283,9 +367,10 @@ class RemotePcController extends AbstractController
try {
$this->httpClient->request('POST', 'https://' . $client->getIp() . ':8000/opengnsys/Apagar', [
'verify_host' => false,
'timeout' => 2.0,
'headers' => ['Authorization' => $client->getToken()],
]);
} catch (TransportExceptionInterface $e) {
])->getStatusCode();
} catch (TransportExceptionInterface | HttpExceptionInterface $e) {
$this->logger->warning('RemotePC: poweroff failed', ['client_id' => $client->getId(), 'error' => $e->getMessage()]);
}
}
@ -298,4 +383,56 @@ class RemotePcController extends AbstractController
$entry->setOperation($operation);
$this->entityManager->persist($entry);
}
private function logReserveDiagnostics(int $ouid, int $imageId, ?int $labId): void
{
$em = $this->entityManager;
// 1. Does the ImageImageRepository exist and is it marked remotePc?
$iir = $em->createQuery(
'SELECT iir.id, iir.name, iir.remotePc FROM App\Entity\ImageImageRepository iir WHERE iir.id = :id'
)->setParameter('id', $imageId)->getOneOrNullResult();
if (!$iir) {
$this->logger->info('RemotePC: diagnose - ImageImageRepository not found', ['imageId' => $imageId]);
return;
}
$this->logger->info('RemotePC: diagnose - IIR found', ['iir' => $iir]);
if (!$iir['remotePc']) {
$this->logger->info('RemotePC: diagnose - IIR has remotePc=false, clients will never match');
return;
}
// 2. Are there partitions with this IIR?
$partitions = $em->createQuery(
'SELECT c.id AS client_id, c.name AS client_name, c.maintenance,
lab.id AS lab_id, lab.remotePc AS lab_remotePc,
rpc.reservedUntil
FROM App\Entity\Partition p
JOIN p.client c
JOIN c.organizationalUnit lab
JOIN p.image iir
LEFT JOIN c.remotePC rpc
WHERE iir.id = :iirId'
)->setParameter('iirId', $imageId)->getResult();
if (!$partitions) {
$this->logger->info('RemotePC: diagnose - no partitions have this IIR', ['imageId' => $imageId]);
return;
}
$this->logger->info('RemotePC: diagnose - partitions with this IIR', ['rows' => $partitions]);
// 3. Check OU path
try {
$centerPath = $em->createQuery(
'SELECT o.path FROM App\Entity\OrganizationalUnit o WHERE o.id = :id'
)->setParameter('id', $ouid)->getSingleScalarResult();
$this->logger->info('RemotePC: diagnose - OU path', ['ouid' => $ouid, 'path' => $centerPath]);
} catch (\Throwable $e) {
$this->logger->info('RemotePC: diagnose - OU not found', ['ouid' => $ouid]);
}
}
}

View File

@ -182,6 +182,13 @@ final class ClientOutput extends AbstractOutput
)]
public ?BootServerOutput $bootServer = null;
#[Groups(['client:read', 'organizational-unit:read'])]
#[ApiProperty(
description: 'Indica si el cliente tiene una reserva activa de RemotePC (UDS)',
example: false
)]
public bool $isRemotePcActive = false;
public function __construct(Client $client)
{
parent::__construct($client);
@ -236,6 +243,8 @@ final class ClientOutput extends AbstractOutput
if ($client->getBootServer()) {
$this->bootServer = new BootServerOutput($client->getBootServer());
}
$this->isRemotePcActive = (bool) $client->getRemotePC()?->isReservedActive();
}
public function convertMaskToCIDR($mask): int

View File

@ -25,39 +25,13 @@ class UdsSyncOnClientStatusListener
public function preUpdate(PreUpdateEventArgs $args): void
{
$entity = $args->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;
// UDS sync on client status change is disabled.
// Sync is now triggered manually via the calendar sync button.
}
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()]);
}
// UDS sync on client status change is disabled.
// Sync is now triggered manually via the calendar sync button.
}
}

View File

@ -174,11 +174,10 @@ class ClientRepository extends AbstractRepository
->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.id = :imageId')
->andWhere('iir.remotePc = true')
->andWhere('c.maintenance = false')
->andWhere('(rpc.reservedUntil IS NULL OR rpc.reservedUntil < :now)')

View File

@ -91,8 +91,8 @@ class UDSClient
$servicePool['osmanager_id'] = null;
$servicePool['max_srvs'] = $maxAvailableSeats;
$servicePool['initial_srvs'] = $maxAvailableSeats;
$servicePool['cache_l1_srvs'] = 0;
//$servicePool['initial_srvs'] = $maxAvailableSeats;
//$servicePool['cache_l1_srvs'] = 0;
$servicePool['visible'] = $maxAvailableSeats > 0;
$response = $this->httpClient->request('PUT', $this->udsAPIurl . 'servicespools/' . $servicePool['id'], [
@ -231,6 +231,11 @@ class UDSClient
continue;
}
$remotePC = $client->getRemotePC();
if ($remotePC && $remotePC->isReservedActive()) {
continue;
}
if ($imageId !== null && !$this->clientHasImage($client, $imageId)) {
continue;
}
@ -245,7 +250,7 @@ class UDSClient
{
foreach ($client->getPartitions() as $partition) {
$iir = $partition->getImage();
if ($iir && $iir->getImage() && $iir->getImage()->getId() === $imageId) {
if ($iir && $iir->getId() === $imageId) {
return true;
}
}