306 lines
12 KiB
Markdown
306 lines
12 KiB
Markdown
# 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 |
|