Compare commits

..

No commits in common. "main" and "develop" have entirely different histories.

139 changed files with 1736 additions and 6472 deletions

View File

@ -1,267 +1,5 @@
# Changelog
## [1.15.2] - 2026-10-26
### Fixed
- **Cancelación Robusta de Trazas (`KillJobService`, `CancelMultipleTracesAction`)**:
- Al cancelar una traza en progreso (`IN_PROGRESS`), la petición HTTP al endpoint del agente (`/opengnsys/KillJob`) se ejecuta de forma segura capturando cualquier excepción (código HTTP 404 por trabajo inexistente o ya finalizado, error de conexión por cliente reiniciando o apagado, etc.).
- La traza se cancela siempre localmente a nivel de base de datos (`CANCELLED`), registrando la fecha de finalización (`finished_at`) y publicando el cambio reactivo a través de Mercure, evitando errores Hydra 400 y bloqueos en la interfaz cuando el agente no responde.
## [1.15.1] - 2026-10-26
### Fixed
- **Asignación de Cliente en Creación de Imagen (`CreateImageAction`)**:
- Corregida la creación de nuevas trazas para que utilicen el cliente actual que ejecuta la orden (`$client`) en lugar del cliente original asociado a la entidad imagen (`$image->getClient()`), evitando la asignación errónea de trazas al crear nuevas versiones de imágenes desde puestos diferentes.
## [1.15.0] - 2026-10-23
### Added
- **Activación y Desactivación de Plugins (`PluginController`)**:
- Incorporado parámetro `?all=true` en `GET /plugins` para permitir listar todos los plugins instalados (tanto activos como inactivos) desde la consola de administración.
- Nuevo endpoint `POST|PATCH /plugins/{name}/toggle` para activar o desactivar plugins de manera dinámica y desacoplada, persistiendo el estado en `og_plugins.enabled`.
## [1.14.2] - 2026-10-22
### Fixed
- **Consistencia de Estado en Trazas de Script (`RunScriptAction`, `CancelMultipleTracesAction`)**:
- `RunScriptAction`: Al actualizar trazas existentes desde la cola pendientes (`updateExistingTrace`), se unifica el estado a `IN_PROGRESS` (en lugar de `SENT`), alineándolo con la ejecución directa y con el estándar de scripts del sistema.
- `CancelMultipleTracesAction`: Revertida la cancelación de trazas en `SENT`, manteniendo la regla estricta que solo permite cancelar trazas en estado `pending` o `in-progress`.
## [1.14.1] - 2026-10-22
### Fixed
- **Resolución y Cancelación de Tareas en Estado Enviado (`StatusController`, `CancelMultipleTracesAction`)**:
- `CancelMultipleTracesAction`: Permite cancelar de forma explícita trazas que se encuentran en estado `sent` (`SENT`), eliminando el bloqueo que impedía cancelar tareas en vuelo o pendientes de respuesta.
- `StatusController`: En el webhook de reinicio y apagado (`REBOOT` / `POWEROFF`), se resuelven automáticamente a éxito tanto las trazas en progreso (`IN_PROGRESS`) como las enviadas (`SENT`), asegurando que los scripts que provocan el reinicio del equipo (como los scripts de congelación/descongelación) cierren su ciclo de ejecución correctamente.
## [1.14.0] - 2026-10-22
### Added
- **Soporte de Sistema Operativo Destino en Cola de Tareas (`target_os` en `PendingTraceExecutionService`, `ExecutePendingTracesCommand`, `RunScriptAction`)**:
- Incorporada la capacidad de asociar restricciones de sistema operativo (`target_os`, ej: `windows`, `linux`, `og-live`) a las trazas encoladas (`PENDING`).
- `PendingTraceExecutionService::executeNextTraceForClient` comprueba ahora si el estado del cliente (`ClientStatus`) coincide con el sistema operativo requerido por la tarea. Si un equipo arranca en un entorno incompatible (como `ogLive` vía PXE cuando la tarea requiere `windows`), la traza no se dispara indebidamente en bash y se mantiene en espera (`PENDING`) hasta que el cliente reporte su inicio en el sistema operativo correspondiente.
- Actualizado `ExecutePendingTracesCommand` para posponer tareas pendientes cuyos requisitos de SO no se cumplan.
- Actualizado `CommandExecuteInput` y `RunScriptAction` para aceptar `targetOs`, encolando la orden si el cliente está offline o si está encendido en un SO distinto al destino solicitado.
## [1.13.0] - 2026-10-22
### Added
- **Infraestructura Modular de Plugins (`Plugin`, `PluginRepository`, `PluginController`, `og_plugins`)**:
- Incorporada la arquitectura base y endpoints agnósticos (`/api/plugins`, `/api/plugins/{name}`, `/api/plugins/{name}/config`) para soportar extensiones y plugins desacoplados (como el próximo plugin de congelación de puestos `ogfreeze`).
- La nueva tabla `og_plugins` almacena de forma dinámica comandos inyectables en la consola de comandos, esquemas de configuración JSON autogenerados y parámetros persistentes de cada plugin.
- Comportamiento 100% neutro e idéntico a 1.12.0 si la tabla de plugins se encuentra vacía.
- Creada migración de base de datos (`Version20261022100000`).
## [1.12.0] - 2026-10-20
### Added
- **Cola y Despacho Asíncrono de Comandos (`AbstractOgAgentController`, `RunScriptAction`, `RebootAction`, `PowerOffAction`, `PartitionAssistantAction`, `RefreshAction`, `DeployImageAction`)**:
- Implementada detección temprana de clientes offline (`isClientOffline`): cuando un equipo está apagado o no disponible, sus acciones o scripts se encolan directamente en estado `PENDING` en la base de datos sin realizar peticiones de red bloqueantes, eliminando los cuelgues del servidor por timeouts prolongados al enviar comandos masivos en aulas.
- Implementado envío HTTP asíncrono y en paralelo (`sendAsyncRequest` / Guzzle Promises) para clientes encendidos en todas las acciones principales de ogAgent, optimizando la concurrencia y reduciendo drásticamente el tiempo de respuesta de la API.
## [1.11.3] - 2026-10-14
### Fixed
- **Menú del navegador (`MenuBrowserController`)**: Corregido un error crítico ("Call to a member function getPublicUrl() on null") al cargar el menú en clientes que no tienen asignado un menú explícito o cuando el cliente no está registrado. Se ha implementado un mecanismo de resolución en cascada que busca primero en la jerarquía de Unidades Organizativas (de hijo a ancestros), luego en el menú por defecto del sistema (`isDefault: true`), y como último recurso en cualquier menú disponible, persistiendo automáticamente la asignación en la base de datos para evitar futuros bloqueos. Además, se añade verificación de existencia de la plantilla Twig con fallback a `browser/main.html.twig`.
## [1.11.2] - 2026-10-06
### Fixed
- **API Platform (Client)**: Corregido un error ("The input data is misformatted") al mover clientes a otras unidades organizativas o aulas desde la interfaz. El endpoint de la API (`/clients/change-organizational-unit`) estaba utilizando incorrectamente la restricción de validación `GreaterThan(1)` sobre la lista de equipos en lugar de `Count(min: 1)`, lo que provocaba un fallo interno en el serializador de Symfony. Ahora se pueden mover equipos correctamente, incluso de uno en uno.
## [1.11.1] - 2026-10-02
### Fixed
- **RemotePC Calendars**: Rediseñada por completo la lógica de evaluación en `RemoteCalendar::isAvailable()`. Se ha solucionado un error grave donde las reglas de calendario (especialmente las negativas) se ignoraban de forma silente al depender del orden y salir prematuramente del bucle con valores positivos. Ahora, las reglas negativas bloquean inmediatamente la disponibilidad, y las positivas exigen cumplimiento estricto, respetando casos de calendarios con solo reglas negativas.
## [1.11.0] - 2026-10-02
### Added
- **RemotePC**: Añadida la propiedad `remotePcRebootOnUnreserve` a la entidad `OrganizationalUnit` para permitir configurar si un equipo remoto debe ser reiniciado en lugar de apagado cuando UDS libera su reserva.
## [1.10.0] - 2026-09-23
### Added
- **Cola de Tareas Reactiva**: Refactorizado el sistema de colas (`ExecutePendingTracesCommand` y `StatusController`) para extraer la lógica a un nuevo servicio (`PendingTraceExecutionService`). Ahora el servidor procesa y asigna las siguientes tareas inmediatamente (push-model) al recibir las confirmaciones webhooks de finalización, eliminando la latencia de 1 minuto que imponía el crontab.
## [1.9.7] - 2026-09-18
### Fixed
- **Subida de Assets (`AssetManagerController`)**: Solucionado el error silencioso (código HTTP 500) y la creación de carpetas vacías al subir archivos ZIP que superaban el límite global de `upload_max_filesize` configurado en PHP. Se ha añadido validación nativa que devuelve un mensaje claro de error en la interfaz. También se ha incluido verificación y control de excepciones al extraer con `ZipArchive`.
- **Previsualización de Menús (`MenuBrowserController`)**: Corregido el problema de los iconos rotos (errores 404) al previsualizar menús HTML en la interfaz. El servidor ahora emplea el `baseUrl` exacto enviado por el cliente para reescribir de manera explícita (mediante expresiones regulares) todas las rutas relativas o absolutas de los `assets`, superando así las limitaciones de resolución de rutas en entornos de proxy inverso (Nginx) y descartando el uso inestable de etiquetas `<base>`.
## [1.9.6] - 2026-09-10
### Fixed
- **OgBoot (`DeleteAction`)**: Solucionado error 404 al borrar plantillas PXE durante una modificación de MAC. El código ahora convierte la MAC a minúsculas para coincidir con el sistema de archivos Linux de ogBoot. Además, ahora extrae el `BootServer` específico del cliente para dirigir la petición de borrado al servidor correcto, y maneja de forma estricta los errores 404 como "borrados exitosos" sin abortar la transacción de la base de datos de ogcore.
## [1.9.5] - 2026-09-03
### Fixed
- **Webhook (`StatusController`)**: Añadido mecanismo de protección para ignorar latidos (heartbeats) si el cliente está en los estados de transición `INITIALIZING` o `TURNING_OFF`. Esto evita el conocido error donde un latido residual marcaba permanentemente al cliente como `BUSY` (Rojo) en el momento del apagado o reinicio.
- **Trazas (`CreateService`)**: Corregido el cierre de trazas para que rellene automáticamente la "Hora de fin" (`finishedAt`) al procesar tareas inmediatas que entran con estado `SUCCESS` o `FAILED`.
## [1.9.4] - 2026-07-31
### Added
- Inventario Hardware: Añadida captura y persistencia del tipo de disco (`diskType` en la entidad `Partition`) y de la velocidad de red (`netSpeed` en la entidad `Client`). Estos campos ahora se exponen a través de la API REST para su visualización en el frontend.
## [1.9.3] - 2026-07-31
### Fixed
- Actualización de imagen (`CreateImageAction`): Resuelto error 500 (`Call to a member function getRepository() on null`) al actualizar una imagen existente desde un cliente distinto al que se usó para crearla originalmente. Ahora se utiliza correctamente el cliente enviado en el payload para determinar el repositorio de destino.
## [1.9.2] - 2026-07-23
### Added
- Mercure (`TraceStatusProgressNotifier`): Publish `output` and `finishedAt` fields in Mercure traces event for real-time log updates without page reload.
### Fixed
- Filtro de imágenes (`ImageSearchRepositoryFilter`): Corregida la propiedad `repositories` a `imageImageRepositories` en el `QueryBuilder` de Doctrine para evitar un error 500 al filtrar imágenes por repositorio.
- Menú del navegador (`main.html.twig`): Modificada la acción por defecto para el arranque de sistemas operativos. Se ha cambiado de `command+output:` a `command:` para evitar que se abra la ventana emergente de salida de comandos, ofreciendo una experiencia de arranque más limpia.
- Webhook (`StatusController` y `RunScriptAction`): Solucionado el problema de condición de carrera que creaba trazas duplicadas al ejecutar scripts. Ahora se establece el estado a `IN_PROGRESS` de forma síncrona en `RunScriptAction` al enviar el script a clientes Windows/Linux, prescindiendo del problemático webhook asíncrono `START_SCRIPT`.
- OgBoot (`PostAction`): El enrutador y la máscara de red ahora se extraen prioritariamente de las propiedades de la Subred (Subnet) asociada al cliente, antes de consultar la configuración de red de la Unidad Organizativa, o usar los valores por defecto (vacío y `255.255.255.0`).
- Repositorios Git (`DeleteAction` y `DeleteRepositoryInput`): Corregido el mapeo del payload de Angular aplicando el grupo de serialización correcto (`repository:write`), permitiendo recibir el nombre del repositorio a borrar. Además, se ha blindado el control de errores para capturar e informar correctamente de cualquier código de error (como 404) devuelto por `ogrepository`.
## [1.9.1] - 2026-07-17
### Added
- Webhook (`StatusController`): Procesa la configuración de discos, particiones y caché en la respuesta del payload de la tarea `EjecutarScript`, guardándola automáticamente en base de datos.
- Perfil de usuario: Añadido campo de preferencia de idioma (`language`).
- Unidades organizativas: Ordenar hijos alfabéticamente por nombre.
### Fixed
- Base de datos (`Trace`): Ampliado el tipo de columna de `output` de string a TEXT para evitar errores HTTP 500 al recibir y almacenar salidas de comandos muy largas de los agentes de sistema operativos (OGAgent).
- Tareas programadas (`Schedule`): Corregido bug en ejecución inmediata de comandos (Execute task right now).
- Despliegue de imágenes: Eliminada restricción que impedía el despliegue en clientes con distintos tamaños de partición.
- Perfiles de software: Corregido bug en la creación del perfil de software y actualizada entidad de imagen asociada.
- Perfiles de hardware: Ajustes en los settings de red y propagación de perfiles.
- Scripts: Aumentado el tamaño del campo de texto en base de datos para almacenar scripts más largos.
- Roles: Actualización menor de permisos.
## [1.9.0] - 2026-06-16
### Added
- Sistema de permisos por rol para los cuatro perfiles de usuario:
`ROLE_SUPER_ADMIN`, `ROLE_ORGANIZATIONAL_UNIT_ADMIN`,
`ROLE_ORGANIZATIONAL_UNIT_OPERATOR` y `ROLE_ORGANIZATIONAL_UNIT_MINIMAL`.
Solo super-admin y administrador de aulas pueden crear clientes y unidades
organizativas. La escritura en infraestructura (DHCP, Boot servers,
repositorios, comandos, subredes) queda restringida a super-admin.
- El administrador de aulas solo puede borrar las unidades organizativas que
él mismo creó (verificado via campo `createdBy` de Gedmo Blameable).
- Suite de tests funcionales (`PermissionsTest`) con 25 casos que cubren la
matriz completa de permisos por rol.
- ogLive (`ROLE_OGCLIENT_API`) puede consultar clientes por GET para obtener
su configuración al arrancar.
### Fixed
- Los clientes sin plantilla de arranque (`PxeTemplate`) asignada ahora pueden
borrarse correctamente. Antes el processor intentaba eliminar el fichero PXE
en ogBoot aunque nunca se hubiera creado, provocando un error 404 que abortaba
el borrado.
- Borrado en cascada de `HardwareProfile` al eliminar un cliente: los perfiles
de hardware asociados quedaban como registros huérfanos. Corregido con
`cascade: remove` y migración `Version20260615092704`.
- Las reglas `access_control` del firewall de Symfony usaban el prefijo `/api/`
que nginx elimina antes de reenviar las peticiones a ogcore. Corregido a las
rutas reales (`/clients`, `/organizational-units`).
- La operación DELETE de unidades organizativas devolvía 404 a todos los usuarios
al tener configurado un provider personalizado que no implementaba el caso
`Delete`. Corregido usando el proveedor Doctrine por defecto.
- `DeleteAction` de ficheros PXE usaba la variable `$content` (no definida) en
lugar de `$response` para comprobar errores de ogBoot.
- Normalización de timezone a UTC en los campos `executionTime`, `executionDate`,
`lastExecution` y `nextExecution` de los DTOs de `CommandTask` y
`CommandTaskSchedule`.
### Improved
- Timeout de 5 segundos en el sondeo del estado de cada equipo al consultar un
aula completa, evitando bloqueos cuando algún cliente no responde.
## [1.8.3] - 2026-05-22
### Improved
- Modificada accion WolAction, calcula la ip de broadcast para el comando wakeonlan, para ello, detecta la mascara de red usando la subred configurada en el dhcp, si no se usa ogdhcp, busca la máscara de red en la configuración de la OU, en caso de tampoco encontrala, usa la ip de broadcast por defecto del comando wakeonlan
## [1.8.2] - 2026-05-18
### Improved
- Modificada accion RemoveCacheImage para montar la cache y luego eliminar la imagen deseada
## [1.8.1] - 2026-05-18
### Fixed
- Corregido fallo setRemotePc en la entidad Imagen al sincronizar un repositorio
## [1.8.0] - 2026-05-18
### Added
- Infraestructura journal-pull: servicio plantilla `journal-pull@.service` para
extraer journals de componentes por IP vía `systemd-journal-gatewayd`, con
filtros para ogcore, ogdhcp, ogboot, ogrepo, kea, tftpd-hpa y samba
- `JournalPullService` y `JournalPullSubscriber`: habilitación y deshabilitación
automática de `journal-pull@<IP>` al registrar o eliminar un BootServer,
DhcpServer o ImageRepository desde el GUI; protección contra borrado de IP
compartida entre varios componentes en la misma máquina
- `DiskLogsAction`: soporte de múltiples `SYSLOG_IDENTIFIER` separados por coma
o en array, salida estructurada en JSON y lectura desde fichero de journal
remoto (`/var/log/journal/remote/<IP>.journal`) cuando se indica el parámetro host
- La retención de los journals remotos se delega en `systemd-journald` de cada
componente (configurado por oginstaller: 500MB máx, 10 días); los ficheros
pulled en ogcore quedan acotados sin necesidad de logrotate local
### Fixed
- `journal-pull@.service`: `Restart=always` para reconectar tras salida limpia
(sin entradas); `ExecStartPre` elimina el fichero solo si está vacío para
evitar cursor inválido tras fallos previos; `--split-mode=none` requerido
para escritura a fichero único por IP
- `JournalPullSubscriber`: al cambiar la IP de un servidor se verifica que
ninguna otra entidad usa la IP anterior antes de eliminarla del fichero de
configuración
- postinst: añadido `--no-interaction` al comando de generación de claves JWT
para evitar bloqueo en instalación desatendida
- postinst: permisos `775` en `api/var/` para evitar errores de caché de Doctrine
- postinst: permisos de acceso al journal para el usuario `opengnsys`
(`systemd-journal` y `systemd-journal-remote`)
- postinst (upgrade): añadidos symlinks faltantes en actualizaciones —
`mercure.conf` en nginx, unidades `journal-pull@`, `journal-pull-sync`;
`chmod +x` en `journal-pull-sync.sh`; propietario y permisos de
`journal-pull-sources.conf`; cambiado `ln -s` por `ln -sf` en las
unidades journal-pull para evitar fallo cuando el fichero existe como
fichero regular en lugar de symlink
- `systemd-journal-remote` y `logrotate` añadidos como dependencias del paquete
## [1.7.12] - 2026-05-14
### Fixed
- Corregida migracion de perfiles hardware y software, los tipos de software y hardware no se guardaban en base de datos antes de tener que ser usados por los perfiles.
## [1.7.11] - 2026-05-14
### Fixed
- Corregido error "Call to undefined method App\Entity\Image::setRemotePc()" al importar una imagen desde un repositorio. La propiedad `remotePc` fue eliminada de la entidad `Image` en la versión 1.7.0 pero la llamada a `setRemotePc()` no fue eliminada del controlador `ImportAction`.
## [1.7.10] - 2026-05-13
### Improved
- Modificado setClientBootMode para crear una traza en caso de ejecución en modo temporal, el id de dicha traza se le pasa al comando opengnsys:pxe:sync para que pueda sincronizar el fichero PXE del cliente y finalizar la traza indicando si se ha realizado correctamente o no
- Modificado comando opengnsys:pxe:sync para que pueda ser llamado desde la api con un trace id y se pueda hacer un seguimiento del mismo, con lo que se ha tenido que añadir el servicio de trazas.
## [1.7.9] - 2026-05-12
### Added
- Añadida nueva ruta para cambiar la plantilla de un cliente /clients/set-boot-mode, recibe el nombre de la plantilla, el modo 0=temporal, 1=permanente y puede enviarse mac, ip o nombre del cliente o nombre del aula.
### Fixed
- Modificado script de importación de base de datos OG 1.1 para añadir las tablas grupos y gruposordenadores como obligatorias junto con centros y aulas.
## [1.7.8] - 2026-05-11
### Fixed
- En la importación de clientes, se inicializan con estado "off"
## [1.7.7] - 2026-05-08
### Added
- Mejorado comando ImportLegacy y creada ruta api para invocarlo desde la consola web, controla errores e informa de cambios a través de mercure
## [1.7.6] - 2026-05-08
### Added
- Añadido comando ImportLegacy para importar una base de datos de OG 1.1 a OG 3.0, hace llamadas al resto de comandos Migrate ya creados. Acepta un fichero dump.sql o los parametros de conexión a la base de datos OG 1.1
## [1.7.5] - 2026-05-06
### Fixed
- Corregida la ejecución de tareas programadas y la gestión de zona horaria UTC

View File

@ -61,19 +61,6 @@ pipeline {
}
}
stage('Generate Changelog (Devel)') {
when {
branch 'devel'
}
steps {
script {
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
generateDebianChangelog(env.BUILD_DIR, devName, devEmail, "devel")
}
}
}
stage('Build') {
steps {
script {
@ -109,19 +96,6 @@ pipeline {
}
}
}
stage ('Publish to Debian Repository (Devel)') {
when {
branch 'devel'
}
agent { label 'debian-repo' }
steps {
script {
def versionPattern = "-${env.BUILD_NUMBER}~devel"
publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogcore', 'devel', versionPattern)
}
}
}
}
post {
success {
@ -134,13 +108,6 @@ pipeline {
string(name: 'TRIGGERED_BY', value: "${env.JOB_NAME}-${env.BUILD_NUMBER}")
]
}
if (env.BRANCH_NAME == 'devel') {
build job: 'Aptly publish develop repository',
wait: false,
parameters: [
string(name: 'TRIGGERED_BY', value: "${env.JOB_NAME}-${env.BUILD_NUMBER}")
]
}
}
}

View File

@ -54,8 +54,7 @@
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/",
"Functional\\": "tests/Functional/"
"App\\Tests\\": "tests/"
}
},
"replace": {

View File

@ -13,22 +13,17 @@ resources:
ApiPlatform\Metadata\Get:
provider: App\State\Provider\BootServerProvider
ApiPlatform\Metadata\Put:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\BootServerProvider
ApiPlatform\Metadata\Patch:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\BootServerProvider
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
oglives_sync:
shortName: BootServer
class: ApiPlatform\Metadata\Post
method: POST
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /boot-servers/{uuid}/oglives/sync
controller: App\Controller\OgBoot\OgLive\SyncAction
@ -37,7 +32,6 @@ resources:
class: ApiPlatform\Metadata\Post
method: POST
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /boot-servers/{uuid}/pxe-templates/sync
controller: App\Controller\OgBoot\PxeTemplate\SyncAction

View File

@ -24,8 +24,7 @@ resources:
provider: App\State\Provider\ClientProvider
validationContext:
groups: [ 'client:patch' ]
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_OPERATOR")'
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
delete_multiple_clients:

View File

@ -20,15 +20,11 @@ resources:
ApiPlatform\Metadata\Get:
provider: App\State\Provider\CommandProvider
ApiPlatform\Metadata\Put:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\CommandProvider
ApiPlatform\Metadata\Patch:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\CommandProvider
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
command_execute:
class: ApiPlatform\Metadata\Post

View File

@ -24,13 +24,6 @@ resources:
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
command_task_execute:
class: ApiPlatform\Metadata\Post
method: POST
input: App\Dto\Input\CommandTaskExecuteInput
uriTemplate: /command-tasks/{uuid}/execute
controller: App\Controller\CommandTaskExecuteAction
properties:
App\Entity\CommandTask:
id:

View File

@ -15,24 +15,19 @@ resources:
provider: App\State\Provider\DhcpServerProvider
ApiPlatform\Metadata\Put:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\DhcpServerProvider
ApiPlatform\Metadata\Patch:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\DhcpServerProvider
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
subnet_sync:
shortName: DhcpServer
class: ApiPlatform\Metadata\Post
method: POST
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /dhcp-servers/{uuid}/sync
controller: App\Controller\OgDhcp\Subnet\SyncAction

View File

@ -18,15 +18,11 @@ resources:
ApiPlatform\Metadata\Get:
provider: App\State\Provider\ImageRepositoryProvider
ApiPlatform\Metadata\Put:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\ImageRepositoryProvider
ApiPlatform\Metadata\Patch:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\ImageRepositoryProvider
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
image_ogrepository_sync:
shortName: OgRepository Server

View File

@ -1,6 +1,5 @@
resources:
App\Entity\OrganizationalUnit:
order: { name: 'ASC' }
processor: App\State\Processor\OrganizationalUnitProcessor
output: App\Dto\Output\OrganizationalUnitOutput
input: App\Dto\Input\OrganizationalUnitInput
@ -26,11 +25,8 @@ resources:
provider: App\State\Provider\OrganizationalUnitProvider
validationContext:
groups: ['organizational-unit:patch' ]
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN") or is_granted("ROLE_ORGANIZATIONAL_UNIT_OPERATOR")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN") or (is_granted("ROLE_ORGANIZATIONAL_UNIT_ADMIN") and object.getCreatedBy() == user.getUserIdentifier())'
securityMessage: 'You can only delete organizational units you created.'
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
change_parent:
class: ApiPlatform\Metadata\Post
method: POST

View File

@ -17,15 +17,11 @@ resources:
ApiPlatform\Metadata\Get:
provider: App\State\Provider\SubnetProvider
ApiPlatform\Metadata\Put:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\SubnetProvider
ApiPlatform\Metadata\Patch:
security: 'is_granted("ROLE_SUPER_ADMIN")'
provider: App\State\Provider\SubnetProvider
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
get_subnet:
@ -43,7 +39,6 @@ resources:
class: ApiPlatform\Metadata\Post
method: POST
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/post
controller: App\Controller\OgDhcp\Subnet\PostAction
@ -53,7 +48,6 @@ resources:
class: ApiPlatform\Metadata\Put
method: PUT
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/put
controller: App\Controller\OgDhcp\Subnet\PutAction
@ -63,7 +57,6 @@ resources:
class: ApiPlatform\Metadata\Delete
method: DELETE
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/delete
controller: App\Controller\OgDhcp\Subnet\DeleteAction
@ -73,7 +66,6 @@ resources:
class: ApiPlatform\Metadata\Post
method: POST
input: App\Dto\Input\SubnetAddHostInput
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/post-host
controller: App\Controller\OgDhcp\Subnet\PostHostAction
@ -92,7 +84,6 @@ resources:
class: ApiPlatform\Metadata\Put
method: PUT
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/put-host
controller: App\Controller\OgDhcp\Subnet\PutHostAction
@ -103,7 +94,6 @@ resources:
method: DELETE
input: false
read: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/delete-host/{clientUuid}
controller: App\Controller\OgDhcp\Subnet\DeleteHostAction
@ -113,7 +103,6 @@ resources:
class: ApiPlatform\Metadata\Delete
method: DELETE
input: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/delete-leases
controller: App\Controller\OgDhcp\Subnet\DeleteSubnetLeasesAction
@ -124,7 +113,6 @@ resources:
method: DELETE
input: false
read: false
security: 'is_granted("ROLE_SUPER_ADMIN")'
uriTemplate: /og-dhcp/server/{uuid}/delete-lease/{clientUuid}
controller: App\Controller\OgDhcp\Subnet\DeleteClientLeaseAction

View File

@ -39,11 +39,6 @@ security:
- { path: ^/validate, roles: PUBLIC_ACCESS }
- { path: ^/menu-browser, roles: PUBLIC_ACCESS }
- { path: ^/menu/, roles: PUBLIC_ACCESS }
# Creación de clientes y OUs: super-admin, ou-admin y ou-operator
- { path: ^/clients$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN, ROLE_ORGANIZATIONAL_UNIT_OPERATOR] }
- { path: ^/organizational-units$, methods: [POST], roles: [ROLE_SUPER_ADMIN, ROLE_ORGANIZATIONAL_UNIT_ADMIN, ROLE_ORGANIZATIONAL_UNIT_OPERATOR] }
# ogLive puede consultar clientes por IP con su API key
- { path: ^/clients, methods: [GET], roles: [ROLE_OGCLIENT_API, ROLE_USER] }
- { path: ^/, roles: ROLE_USER }
when@test:

View File

@ -142,7 +142,7 @@ services:
api_platform.filter.hardware.search:
parent: 'api_platform.doctrine.orm.search_filter'
arguments: [ { 'id': 'exact', 'name': 'partial', 'clients.id': 'exact' } ]
arguments: [ { 'id': 'exact', 'name': 'partial' } ]
tags: [ 'api_platform.filter' ]
api_platform.filter.menu.order:

2
debian/control vendored
View File

@ -10,7 +10,7 @@ Architecture: all
Depends: ${misc:Depends}, mariadb-server, systemd, nginx, libzip-dev, zip, unzip,
php8.3-opcache, php8.3-bcmath, php8.3-cli, php8.3-curl, php8.3-fpm,
php8.3-gd, php8.3-ldap, php8.3-mbstring, php8.3-mysql, php8.3-common,
php8.3-xml, php8.3-zip, mercure, systemd-journal-remote, logrotate
php8.3-xml, php8.3-zip, mercure
Description: OpenGnsys Core
OgCore package is responsible about management of Opengnsys platform
OpenGnsys Core is a platform for system management.

View File

@ -54,7 +54,7 @@ if [ "$1" = "configure" ] && [ -z "$2" ]; then
echo ">>> Creando par de claves para JWT"
php bin/console lexik:jwt:generate-keypair --overwrite --no-interaction
php bin/console lexik:jwt:generate-keypair --overwrite
echo ">>> Creando base de datos"
php bin/console doctrine:database:create --if-not-exists
@ -79,28 +79,12 @@ if [ "$1" = "configure" ] && [ -z "$2" ]; then
ln -s /opt/opengnsys/ogcore/etc/nginx/sites-available/mercure.conf /etc/nginx/sites-enabled/mercure.conf
ln -s /opt/opengnsys/ogcore/etc/php/8.3/fpm/pool.d/ogcore-fpm.conf /etc/php/8.3/fpm/pool.d/ogcore-fpm.conf
ln -s /opt/opengnsys/ogcore/etc/systemd/system/og-mercure.service /etc/systemd/system/og-mercure.service
ln -s /opt/opengnsys/ogcore/etc/systemd/system/journal-pull@.service /etc/systemd/system/journal-pull@.service
ln -s /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.path /etc/systemd/system/journal-pull-sync.path
ln -s /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.service /etc/systemd/system/journal-pull-sync.service
ln -s /opt/opengnsys/ogcore/etc/logrotate.d/ogclients /etc/logrotate.d/ogclients
chown root:root /opt/opengnsys/ogcore/etc/logrotate.d/ogclients
echo ">>> Configurando journal-pull"
touch /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chmod +x /opt/opengnsys/ogcore/etc/bin/journal-pull-sync.sh
mkdir -p /var/log/journal/remote
chown systemd-journal-remote:systemd-journal-remote /var/log/journal/remote
echo ">>> Configurando permisos de archivos"
chown opengnsys:www-data /opt/opengnsys/
chown -R opengnsys:www-data /opt/opengnsys/ogcore
chmod -R 775 /opt/opengnsys/ogcore/api/var/
chown www-data:www-data /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chmod 664 /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
usermod -aG systemd-journal opengnsys
usermod -aG systemd-journal-remote opengnsys
systemctl daemon-reload
systemctl enable og-mercure
systemctl enable --now journal-pull-sync.path
systemctl restart mariadb.service
systemctl restart og-mercure
systemctl restart nginx
@ -159,21 +143,8 @@ elif [ "$1" = "configure" ] && [ -n "$2" ]; then
php bin/console cache:clear
echo ">>> Configurando servidor web y servicios"
[ ! -L /etc/nginx/sites-enabled/ogcore.conf ] && ln -s /opt/opengnsys/ogcore/etc/nginx/sites-available/ogcore.conf /etc/nginx/sites-enabled/ogcore.conf
[ ! -L /etc/nginx/sites-enabled/mercure.conf ] && ln -s /opt/opengnsys/ogcore/etc/nginx/sites-available/mercure.conf /etc/nginx/sites-enabled/mercure.conf
[ ! -L /etc/php/8.3/fpm/pool.d/ogcore-fpm.conf ] && ln -s /opt/opengnsys/ogcore/etc/php/8.3/fpm/pool.d/ogcore-fpm.conf /etc/php/8.3/fpm/pool.d/ogcore-fpm.conf
[ ! -L /etc/systemd/system/og-mercure.service ] && ln -s /opt/opengnsys/ogcore/etc/systemd/system/og-mercure.service /etc/systemd/system/og-mercure.service
ln -sf /opt/opengnsys/ogcore/etc/systemd/system/journal-pull@.service /etc/systemd/system/journal-pull@.service
ln -sf /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.path /etc/systemd/system/journal-pull-sync.path
ln -sf /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.service /etc/systemd/system/journal-pull-sync.service
ln -sf /opt/opengnsys/ogcore/etc/logrotate.d/ogclients /etc/logrotate.d/ogclients
chown root:root /opt/opengnsys/ogcore/etc/logrotate.d/ogclients
chmod +x /opt/opengnsys/ogcore/etc/bin/journal-pull-sync.sh
if [ ! -f /opt/opengnsys/ogcore/etc/journal-pull-sources.conf ]; then
touch /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chown www-data:www-data /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chmod 664 /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
fi
[ ! -d /var/log/journal/remote ] && mkdir -p /var/log/journal/remote && chown systemd-journal-remote:systemd-journal-remote /var/log/journal/remote
echo ">>> Configurando permisos de archivos"
chown opengnsys:www-data /opt/opengnsys/
chown -R opengnsys:www-data /opt/opengnsys/ogcore
@ -188,10 +159,6 @@ elif [ "$1" = "configure" ] && [ -n "$2" ]; then
chown root:root /etc/cron.d/opengnsys-check-clients
fi
systemctl enable og-mercure
systemctl enable --now journal-pull-sync.path 2>/dev/null || true
usermod -aG systemd-journal opengnsys 2>/dev/null || true
usermod -aG systemd-journal-remote opengnsys 2>/dev/null || true
chmod -R 775 /opt/opengnsys/ogcore/api/var/ 2>/dev/null || true
systemctl daemon-reload
systemctl restart og-mercure
systemctl restart php8.3-fpm

View File

@ -1,30 +0,0 @@
#!/bin/bash
# Syncs journal-pull@ systemd instances with /etc/opengnsys/journal-pull-sources.conf.
# Triggered by journal-pull-sync.path whenever the config file changes.
set -euo pipefail
CONF=/opt/opengnsys/ogcore/etc/journal-pull-sources.conf
[[ -f "$CONF" ]] || exit 0
mapfile -t WANTED < <(grep -v '^\s*#' "$CONF" | grep -v '^\s*$' | sort -u)
mapfile -t CURRENT < <(
systemctl list-units 'journal-pull@*.service' --all --plain --no-legend \
| awk '{print $1}' | sed 's/journal-pull@//;s/\.service//' | sort -u
)
for ip in "${WANTED[@]:-}"; do
[[ -z "$ip" ]] && continue
if ! printf '%s\n' "${CURRENT[@]:-}" | grep -qxF "$ip"; then
systemctl enable --now "journal-pull@${ip}.service"
echo "journal-pull-sync: enabled journal-pull@${ip}"
fi
done
for ip in "${CURRENT[@]:-}"; do
[[ -z "$ip" ]] && continue
if ! printf '%s\n' "${WANTED[@]:-}" | grep -qxF "$ip"; then
systemctl disable --now "journal-pull@${ip}.service"
echo "journal-pull-sync: disabled journal-pull@${ip}"
fi
done

View File

@ -1,9 +0,0 @@
/var/log/ogclients/*/*.log {
daily
rotate 10
compress
missingok
copytruncate
dateext
delaycompress
}

View File

@ -1,8 +0,0 @@
[Unit]
Description=Watch journal-pull sources config
[Path]
PathModified=/opt/opengnsys/ogcore/etc/journal-pull-sources.conf
[Install]
WantedBy=multi-user.target

View File

@ -1,7 +0,0 @@
[Unit]
Description=Sync journal-pull instances from config
After=network-online.target
[Service]
Type=oneshot
ExecStart=/opt/opengnsys/ogcore/etc/bin/journal-pull-sync.sh

View File

@ -1,15 +0,0 @@
[Unit]
Description=Pull OpenGNSYS journal from %i
After=network-online.target
Wants=network-online.target
[Service]
User=systemd-journal-remote
Group=systemd-journal-remote
ExecStartPre=/bin/mkdir -p /var/log/journal/remote/%i
ExecStart=/usr/lib/systemd/systemd-journal-remote --url=http://%i:19531/entries?boot=0&SYSLOG_IDENTIFIER=ogcore&SYSLOG_IDENTIFIER=oggui&SYSLOG_IDENTIFIER=ogdhcp&SYSLOG_IDENTIFIER=ogboot&SYSLOG_IDENTIFIER=ogrepo-api&SYSLOG_IDENTIFIER=ogrepo-api_DEBUG&SYSLOG_IDENTIFIER=kea-dhcp4&SYSLOG_IDENTIFIER=kea-ctrl-agent&SYSLOG_IDENTIFIER=DhcpLFC&SYSLOG_IDENTIFIER=kea-dhcp6&SYSLOG_IDENTIFIER=tftpd-hpa&SYSLOG_IDENTIFIER=%%28smbd%%29&SYSLOG_IDENTIFIER=%%28nmbd%%29 --split-mode=host --output=/var/log/journal/remote/%i/
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target

View File

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260507135000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Change partition size and memoryUsage columns to BIGINT';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE `partition` MODIFY size BIGINT NOT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE `partition` MODIFY size INT NOT NULL');
}
}

View File

@ -1,33 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260615092704 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE hardware_profile DROP FOREIGN KEY FK_2D9A246019EB6921');
$this->addSql('ALTER TABLE hardware_profile ADD CONSTRAINT FK_2D9A246019EB6921 FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE CASCADE');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE hardware_profile DROP FOREIGN KEY FK_2D9A246019EB6921');
$this->addSql('ALTER TABLE hardware_profile ADD CONSTRAINT FK_2D9A246019EB6921 FOREIGN KEY (client_id) REFERENCES client (id)');
}
}

View File

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260703000000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Change command_task_script.content from VARCHAR(255) to LONGTEXT';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE command_task_script CHANGE content content LONGTEXT DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE command_task_script CHANGE content content VARCHAR(255) DEFAULT NULL');
}
}

View File

@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Add language column to user table for storing preferred language.
*/
final class Version20260707091500 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add language column to user table';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE `user` ADD language VARCHAR(10) DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE `user` DROP COLUMN language');
}
}

View File

@ -1,42 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Invierte la relación Client <-> HardwareProfile de OneToOne (perfil propio
* de cada cliente) a OneToMany (un perfil de hardware compartido por varios
* clientes de una misma aula), para permitir asignarlo y propagarlo desde
* la unidad organizativa.
*/
final class Version20260710100654 extends AbstractMigration
{
public function getDescription(): string
{
return 'Client.hardwareProfile pasa a ser propietario de la relación (N clientes por perfil) en vez de HardwareProfile.client (1 cliente por perfil)';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE client ADD hardware_profile_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE client ADD CONSTRAINT FK_C7440455CFA495C1 FOREIGN KEY (hardware_profile_id) REFERENCES hardware_profile (id) ON DELETE SET NULL');
$this->addSql('CREATE INDEX IDX_C7440455CFA495C1 ON client (hardware_profile_id)');
$this->addSql('ALTER TABLE hardware_profile DROP FOREIGN KEY FK_2D9A246019EB6921');
$this->addSql('DROP INDEX IDX_2D9A246019EB6921 ON hardware_profile');
$this->addSql('ALTER TABLE hardware_profile DROP client_id');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE hardware_profile ADD client_id INT NOT NULL');
$this->addSql('ALTER TABLE hardware_profile ADD CONSTRAINT FK_2D9A246019EB6921 FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE CASCADE');
$this->addSql('CREATE INDEX IDX_2D9A246019EB6921 ON hardware_profile (client_id)');
$this->addSql('ALTER TABLE client DROP FOREIGN KEY FK_C7440455CFA495C1');
$this->addSql('DROP INDEX IDX_C7440455CFA495C1 ON client');
$this->addSql('ALTER TABLE client DROP hardware_profile_id');
}
}

View File

@ -1,41 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Mueve el perfil de software de Image (entidad lógica) a ImageImageRepository
* (la versión/copia concreta de la imagen en un repositorio), para poder
* conservar y editar el perfil de software por versión.
*/
final class Version20260710114751 extends AbstractMigration
{
public function getDescription(): string
{
return 'Mueve software_profile_id de image a image_image_repository';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE image DROP FOREIGN KEY FK_C53D045FED42A742');
$this->addSql('DROP INDEX IDX_C53D045FED42A742 ON image');
$this->addSql('ALTER TABLE image DROP software_profile_id');
$this->addSql('ALTER TABLE image_image_repository ADD software_profile_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE image_image_repository ADD CONSTRAINT FK_B7851337ED42A742 FOREIGN KEY (software_profile_id) REFERENCES software_profile (id)');
$this->addSql('CREATE INDEX IDX_B7851337ED42A742 ON image_image_repository (software_profile_id)');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE image_image_repository DROP FOREIGN KEY FK_B7851337ED42A742');
$this->addSql('DROP INDEX IDX_B7851337ED42A742 ON image_image_repository');
$this->addSql('ALTER TABLE image_image_repository DROP software_profile_id');
$this->addSql('ALTER TABLE image ADD software_profile_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE image ADD CONSTRAINT FK_C53D045FED42A742 FOREIGN KEY (software_profile_id) REFERENCES software_profile (id)');
$this->addSql('CREATE INDEX IDX_C53D045FED42A742 ON image (software_profile_id)');
}
}

View File

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260722100000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Change trace output column type to TEXT to support long output';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE trace CHANGE output output LONGTEXT DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE trace CHANGE output output VARCHAR(255) DEFAULT NULL');
}
}

View File

@ -1,33 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260731113500 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add diskType to partition and netSpeed to client';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE client ADD net_speed INT DEFAULT NULL');
$this->addSql('ALTER TABLE `partition` ADD disk_type VARCHAR(50) DEFAULT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE `partition` DROP disk_type');
$this->addSql('ALTER TABLE client DROP net_speed');
}
}

View File

@ -1,31 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20261002135500 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add remotePcRebootOnUnreserve property to OrganizationalUnit';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE organizational_unit ADD remote_pc_reboot_on_unreserve TINYINT(1) NOT NULL DEFAULT 0');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE organizational_unit DROP remote_pc_reboot_on_unreserve');
}
}

View File

@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20261022100000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create og_plugins table for modular plugin infrastructure';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE og_plugins (id INT AUTO_INCREMENT NOT NULL, uuid CHAR(36) NOT NULL COMMENT \'(DC2Type:uuid)\', migration_id VARCHAR(255) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, created_by VARCHAR(255) DEFAULT NULL, updated_by VARCHAR(255) DEFAULT NULL, name VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, version VARCHAR(50) NOT NULL, description LONGTEXT DEFAULT NULL, author VARCHAR(255) DEFAULT NULL, icon VARCHAR(100) DEFAULT NULL, enabled TINYINT(1) NOT NULL, commands JSON DEFAULT NULL COMMENT \'(DC2Type:json)\', schema_definition JSON DEFAULT NULL COMMENT \'(DC2Type:json)\', config_data JSON DEFAULT NULL COMMENT \'(DC2Type:json)\', UNIQUE INDEX UNIQ_OG_PLUGIN_UUID (uuid), UNIQUE INDEX UNIQ_OG_PLUGIN_NAME (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
}
public function down(Schema $schema): void
{
$this->addSql('DROP TABLE og_plugins');
}
}

View File

@ -4,11 +4,26 @@ declare(strict_types=1);
namespace App\Command;
use App\Controller\OgAgent\CreateImageAction;
use App\Controller\DeployImageAction;
use App\Controller\OgAgent\PartitionAssistantAction;
use App\Controller\OgAgent\RunScriptAction;
use App\Dto\Input\CommandExecuteInput;
use App\Dto\Input\DeployImageInput;
use App\Dto\Input\PartitionInput;
use App\Dto\Input\PartitionPostInput;
use App\Dto\Input\MultipleClientsInput;
use App\Dto\Input\BootClientsInput;
use App\Dto\Output\ClientOutput;
use App\Dto\Output\PartitionOutput;
use App\Entity\Client;
use App\Model\ClientStatus;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\Partition;
use App\Entity\Trace;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use App\Service\PendingTraceExecutionService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
@ -22,7 +37,13 @@ class ExecutePendingTracesCommand extends Command
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly PendingTraceExecutionService $pendingTraceExecutionService,
private readonly CreateImageAction $createImageAction,
private readonly DeployImageAction $deployImageAction,
private readonly PartitionAssistantAction $partitionAssistantAction,
private readonly RunScriptAction $runScriptAction,
private readonly \App\Controller\OgAgent\RebootAction $rebootAction,
private readonly \App\Controller\OgAgent\PowerOffAction $powerOffAction,
private readonly \App\Controller\OgAgent\LoginAction $loginAction,
private readonly LoggerInterface $logger,
) {
parent::__construct();
@ -63,15 +84,10 @@ class ExecutePendingTracesCommand extends Command
if ($client->getStatus() === ClientStatus::BUSY) {
continue;
}
if (!$this->pendingTraceExecutionService->matchesTargetOs($trace, $client)) {
$io->note("Trace {$trace->getUuid()} postponed: client {$client->getIp()} is in '{$client->getStatus()}', waiting for target OS");
continue;
}
$io->info("Processing trace {$trace->getUuid()} with command: {$trace->getCommand()}");
$result = $this->pendingTraceExecutionService->executeTrace($trace);
$result = $this->executeTrace($trace);
if ($result) {
$processedCount++;
@ -83,6 +99,11 @@ class ExecutePendingTracesCommand extends Command
} catch (\Exception $e) {
$errorCount++;
$io->error("Error processing trace {$trace->getUuid()}: " . $e->getMessage());
$trace->setStatus(TraceStatus::FAILED);
$trace->setOutput($e->getMessage());
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
}
}
@ -94,4 +115,439 @@ class ExecutePendingTracesCommand extends Command
return Command::SUCCESS;
}
}
private function executeTrace(Trace $trace): bool
{
$command = $trace->getCommand();
$input = $trace->getInput() ?? [];
$client = $trace->getClient();
$this->logger->info('Executing trace', [
'command' => $command,
'input' => $input,
'client' => $client->getUuid()
]);
if (!$client) {
throw new \Exception("No client associated with trace");
}
$trace->setExecutedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
try {
switch ($command) {
case CommandTypes::CREATE_IMAGE:
$this->logger->info('Executing create image trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executeCreateImage($trace, $input);
case CommandTypes::DEPLOY_IMAGE:
$this->logger->info('Executing deploy image trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executeDeployImage($trace, $input);
case CommandTypes::PARTITION_AND_FORMAT:
$this->logger->info('Executing partition and format trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executePartitionAssistant($trace, $input);
case CommandTypes::RUN_SCRIPT:
$this->logger->info('Executing run script trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executeRunScript($trace, $input);
case CommandTypes::POWER_ON:
$this->logger->info('Executing power on trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executePowerOn($trace, $input);
case CommandTypes::REBOOT:
$this->logger->info('Executing reboot trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executeReboot($trace, $input);
case CommandTypes::SHUTDOWN:
$this->logger->info('Executing shutdown trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executeShutdown($trace, $input);
case CommandTypes::LOGIN:
$this->logger->info('Executing login trace', [
'input' => $input,
'client' => $client->getUuid()
]);
return $this->executeLogin($trace, $input);
default:
throw new \Exception("Unsupported command type: $command");
}
} catch (\Exception $e) {
$this->logger->error('Error executing trace', [
'command' => $command,
'input' => $input,
'client' => $client->getUuid(),
'error' => $e->getMessage()
]);
$trace->setStatus(TraceStatus::FAILED);
$trace->setOutput($e->getMessage());
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
throw $e;
}
}
private function executeCreateImage(Trace $trace, array $input): bool
{
$client = $trace->getClient();
$image = null;
if (isset($input['action']) && $input['action'] === 'create') {
$image = new Image();
$image->setName($input['imageName'] ?? $input['name']);
$image->setType($input['type'] ?? 'monolithic');
$image->setRemotePc($input['remotePc'] ?? false);
$image->setIsGlobal($input['isGlobal'] ?? false);
$image->setClient($client);
$this->entityManager->persist($image);
} elseif (isset($input['action']) && $input['action'] === 'update') {
if (!isset($input['imageUuid'])) {
throw new \Exception("Image UUID not found in trace input for update operation");
}
$image = $this->entityManager->getRepository(Image::class)
->findOneBy(['uuid' => $input['imageUuid']]);
if (!$image) {
throw new \Exception("Image not found with UUID: {$input['imageUuid']} for update operation");
}
} else {
throw new \Exception("Either 'create' or 'update' field must be set to true in trace input");
}
if (isset($input['diskNumber']) && isset($input['partitionNumber'])) {
$partitionInfo = [
'numDisk' => $input['diskNumber'],
'numPartition' => $input['partitionNumber'],
'partitionCode' => $input['partitionCode'] ?? 'LINUX',
'filesystem' => $input['filesystem'] ?? 'EXT4'
];
$image->setPartitionInfo(json_encode($partitionInfo));
}
$partition = null;
if (isset($input['diskNumber']) && isset($input['partitionNumber'])) {
$partition = $this->entityManager->getRepository(Partition::class)
->findOneBy([
'client' => $client,
'diskNumber' => $input['diskNumber'],
'partitionNumber' => $input['partitionNumber']
]);
if (!$partition) {
throw new \Exception("Partition not found for client {$client->getUuid()} with disk {$input['diskNumber']} and partition {$input['partitionNumber']}");
}
}
$this->logger->info('Creating image', [
'image' => $image,
'partition' => $partition,
'client' => $client->getUuid()
]);
try {
$response = $this->createImageAction->__invoke(
queue: false,
image: $image,
partition: $partition,
client: $client,
gitRepositoryName: $input['gitRepositoryName'] ?? null,
existingTrace: $trace
);
if (json_decode($response->getContent(), true)['status'] === 200) {
$trace->setStatus(TraceStatus::IN_PROGRESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
return true;
}
return false;
} catch (\Exception $e) {
return false;
}
}
private function executeDeployImage(Trace $trace, array $input): bool
{
$client = $trace->getClient();
if (!isset($input['imageImageRepository']) && !isset($input['image'])) {
throw new \Exception("ImageImageRepository UUID or image UUID not found in trace input for deploy image");
}
$imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)
->findOneBy(['uuid' => $input['imageImageRepository'] ?? $input['image']]);
if (!$imageImageRepository) {
throw new \Exception("ImageImageRepository not found with UUID: {$input['imageImageRepository']}");
}
$diskNumber = isset($input['diskNumber']) ? $input['diskNumber'] : $input['numDisk'];
$partitionNumber = isset($input['partitionNumber']) ? $input['partitionNumber'] : $input['numPartition'];
if (!$diskNumber || !$partitionNumber) {
throw new \Exception("Disk number or partition number not found in trace input for deploy image");
}
$deployInput = new DeployImageInput();
$deployInput->method = $input['method'] ?? 'unicast';
$deployInput->type = $input['type'] ?? 'monolithic';
$deployInput->diskNumber = (int) $diskNumber;
$deployInput->partitionNumber = (int) $partitionNumber;
$deployInput->mcastMode = $input['mcastMode'] ?? null;
$deployInput->mcastSpeed = $input['mcastSpeed'] ?? null;
$deployInput->mcastPort = $input['mcastPort'] ?? null;
$deployInput->mcastIp = $input['mcastIp'] ?? null;
$deployInput->maxClients = $input['maxClients'] ?? null;
$deployInput->maxTime = $input['maxTime'] ?? null;
$deployInput->p2pMode = $input['p2pMode'] ?? null;
$deployInput->p2pTime = $input['p2pTime'] ?? null;
$deployInput->queue = $input['queue'] ?? false;
$deployInput->clients = [new ClientOutput($client)];
$this->logger->info('Deploying image', [
'input' => $deployInput,
'client' => $client->getUuid()
]);
$response = $this->deployImageAction->__invoke($deployInput, $imageImageRepository, $trace);
$clientJobs = $response['data'];
$clientKey = '/clients/' . $client->getUuid();
$jobId = $clientJobs[$clientKey] ?? [];
$trace->setJobId($jobId['jobId']);
$trace->setStatus(TraceStatus::IN_PROGRESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
return true;
}
private function executePartitionAssistant(Trace $trace, array $input): bool
{
$client = $trace->getClient();
$partitionInput = new PartitionPostInput();
$partitionInput->clients = [new ClientOutput($client)];
$partitions = [];
foreach ($input as $item) {
$partitionInputObj = new PartitionInput();
$partitionInputObj->diskNumber = $item['diskNumber'];
$partitionInputObj->partitionNumber = (int)$item['partitionNumber'];
$partitionInputObj->partitionCode = $item['partitionCode'] ?? 'LINUX';
$partitionInputObj->size = $item['size'];
$partitionInputObj->filesystem = $item['filesystem'] ?? 'EXT4';
$partitionInputObj->format = $item['format'] ?? false;
$partitions[] = $partitionInputObj;
}
$partitionInput->partitions = $partitions;
$partitionInput->queue = false;
$this->logger->info('Executing partition assistant', [
'input' => $partitionInput,
'client' => $client->getUuid()
]);
try {
$response = $this->partitionAssistantAction->__invoke($partitionInput, $trace);
if (json_decode($response->getContent(), true)['status'] === 200) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
return true;
}
return false;
} catch (\Exception $e) {
return false;
}
}
private function executeRunScript(Trace $trace, array $input): bool
{
$client = $trace->getClient();
if (!isset($input['script'])) {
throw new \Exception("Script not found in trace input");
}
$commandExecuteInput = new CommandExecuteInput();
$commandExecuteInput->clients = [new ClientOutput($client)];
$commandExecuteInput->script = $input['script'];
$commandExecuteInput->queue = false;
$this->logger->info('Executing run script', [
'input' => $commandExecuteInput,
'client' => $client->getUuid()
]);
try {
$response = $this->runScriptAction->__invoke($commandExecuteInput, $trace);
return $response->getStatusCode() === 200;
} catch (\Exception $e) {
$this->logger->error('Error executing run script', [
'input' => $commandExecuteInput,
'client' => $client->getUuid(),
'error' => $e->getMessage()
]);
return false;
}
}
private function executePowerOn(Trace $trace, array $input): bool
{
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
return true;
}
private function executeReboot(Trace $trace, array $input): bool
{
$client = $trace->getClient();
$multipleClientsInput = new MultipleClientsInput();
$multipleClientsInput->clients = [new ClientOutput($client)];
$multipleClientsInput->queue = false;
try {
$response = $this->rebootAction->__invoke($multipleClientsInput);
if ($response->getStatusCode() === 200) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
return true;
}
return false;
} catch (\Exception $e) {
return false;
}
}
private function executeShutdown(Trace $trace, array $input): bool
{
$client = $trace->getClient();
$multipleClientsInput = new MultipleClientsInput();
$multipleClientsInput->clients = [new ClientOutput($client)];
$multipleClientsInput->queue = false;
try {
$response = $this->powerOffAction->__invoke($multipleClientsInput);
if ($response->getStatusCode() === 200) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
return true;
}
return false;
} catch (\Exception $e) {
return false;
}
}
private function executeLogin(Trace $trace, array $input): bool
{
$client = $trace->getClient();
if ($client->getStatus() !== ClientStatus::OG_LIVE) {
$this->logger->info('Login trace deferred: client not in OGLive', [
'client' => $client->getUuid(),
'status' => $client->getStatus(),
]);
return false;
}
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();
$bootClientsInput->clients = [new ClientOutput($client)];
$bootClientsInput->partition = new PartitionOutput($partition);
try {
$response = $this->loginAction->__invoke($bootClientsInput);
if ($response->getStatusCode() === 200) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
return true;
}
return false;
} catch (\Exception $e) {
return false;
}
}
}

View File

@ -1,356 +0,0 @@
<?php
namespace App\Command\Migration;
use App\Entity\User;
use App\Entity\OrganizationalUnit;
use App\Model\OrganizationalUnitTypes;
use Doctrine\ORM\EntityManagerInterface;
use PDO;
use PDOException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Console\Input\ArrayInput;
#[AsCommand(
name: 'opengnsys:import-legacy',
description: 'Import data from OpenGnsys 1.1 database dump into ogcore',
)]
class ImportLegacyDbCommand extends Command
{
public function __construct(
private EntityManagerInterface $entityManager,
private UserPasswordHasherInterface $passwordHasher,
private ?HubInterface $hub = null
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addOption('file', 'f', InputOption::VALUE_OPTIONAL, 'Path to the .sql dump file')
->addOption('legacy-host', null, InputOption::VALUE_OPTIONAL, 'Legacy database host')
->addOption('legacy-user', null, InputOption::VALUE_OPTIONAL, 'Legacy database user')
->addOption('legacy-password', null, InputOption::VALUE_OPTIONAL, 'Legacy database password')
->addOption('legacy-db', null, InputOption::VALUE_OPTIONAL, 'Legacy database name')
->addOption('cleanup-file', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Files to clean up after execution')
->addOption('log-file', null, InputOption::VALUE_OPTIONAL, 'Log file to read and send via Mercure');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$file = $input->getOption('file');
$legacyHost = $input->getOption('legacy-host');
$legacyUser = $input->getOption('legacy-user');
$legacyPass = $input->getOption('legacy-password');
$legacyDb = $input->getOption('legacy-db');
if (!$file && (!$legacyHost || !$legacyUser || !$legacyDb)) {
$io->error("You must provide either a .sql file via --file OR legacy database credentials (--legacy-host, --legacy-user, --legacy-db)");
return Command::FAILURE;
}
if ($file && !file_exists($file)) {
$io->error("The file provided does not exist: $file");
return Command::FAILURE;
}
$connection = $this->entityManager->getConnection();
$params = $connection->getParams();
$host = $params['host'] ?? '127.0.0.1';
$dbuser = $params['user'] ?? 'root';
$dbpass = $params['password'] ?? '';
$dbname = $params['dbname'] ?? '';
try {
// Get existing tables using DBAL
$existingTables = $connection->fetchFirstColumn("SHOW TABLES");
$io->section("Phase 1: Injecting legacy SQL data into current database");
$passwordArg = $dbpass ? "-p$dbpass" : "";
if ($file) {
$command = "mysql -h " . escapeshellarg($host) . " -u " . escapeshellarg($dbuser) . " $passwordArg " . escapeshellarg($dbname) . " < " . escapeshellarg($file);
exec($command . ' 2>&1', $outputLines, $resultCode);
if ($resultCode !== 0) {
$errorMsg = "Failed to import SQL dump.\n" . implode("\n", $outputLines);
$io->error($errorMsg);
throw new \Exception($errorMsg);
}
} else {
$legacyPassArg = $legacyPass ? "-p" . escapeshellarg($legacyPass) : "";
$tablesToDump = [
'centros', 'aulas', 'grupos', 'gruposordenadores',
'nombresos',
'tiposoftwares', 'softwares', 'perfilessoft', 'perfilessoft_softwares',
'ordenadores',
'tipohardwares', 'hardwares', 'perfileshard', 'perfileshard_hardwares',
'ordenadores_particiones',
'usuarios', 'administradores_centros'
];
$tablesArg = implode(' ', $tablesToDump);
$io->text("Fetching tables from remote database $legacyHost...");
$tempDump = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('legacy_dump_', true) . '.sql';
// Execute dump
// Using --no-tablespaces if supported, but if it fails we will see the error now
$dumpCmd = "mysqldump --no-tablespaces -h " . escapeshellarg($legacyHost) . " -u " . escapeshellarg($legacyUser) . " $legacyPassArg " . escapeshellarg($legacyDb) . " $tablesArg > " . escapeshellarg($tempDump);
exec($dumpCmd . ' 2>&1', $dumpOutput, $dumpResult);
// If mysqldump fails due to --no-tablespaces, fallback without it
if ($dumpResult !== 0 && stripos(implode(" ", $dumpOutput), 'unknown option') !== false) {
$dumpCmd = "mysqldump -h " . escapeshellarg($legacyHost) . " -u " . escapeshellarg($legacyUser) . " $legacyPassArg " . escapeshellarg($legacyDb) . " $tablesArg > " . escapeshellarg($tempDump);
$dumpOutput = [];
exec($dumpCmd . ' 2>&1', $dumpOutput, $dumpResult);
}
if (!file_exists($tempDump) || filesize($tempDump) < 100) {
$errorMsg = "Failed to dump remote database. Dump is empty or failed.\n" . implode("\n", $dumpOutput);
$io->error($errorMsg);
if (file_exists($tempDump)) unlink($tempDump);
throw new \Exception($errorMsg);
}
// Execute import
$importCmd = "mysql -h " . escapeshellarg($host) . " -u " . escapeshellarg($dbuser) . " $passwordArg " . escapeshellarg($dbname) . " < " . escapeshellarg($tempDump);
exec($importCmd . ' 2>&1', $importOutput, $importResult);
if (file_exists($tempDump)) unlink($tempDump);
if ($importResult !== 0) {
$errorMsg = "Failed to import remote database dump.\n" . implode("\n", $importOutput);
$io->error($errorMsg);
throw new \Exception($errorMsg);
}
}
// Get new tables
$currentTables = $connection->fetchFirstColumn("SHOW TABLES");
$injectedTables = array_diff($currentTables, $existingTables);
if (empty($injectedTables)) {
$io->warning("No new tables were detected after import. Make sure the dump is valid.");
} else {
$io->text("Detected " . count($injectedTables) . " injected tables.");
}
$this->dispatchProgress($input);
// Define commands and their mandatory table dependencies
$commands = [
'opengnsys:migration:organizational-unit' => [
'desc' => 'Migrating Organizational Units',
'tables' => ['centros', 'aulas', 'grupos', 'gruposordenadores']
],
'opengnsys:migration:os' => [
'desc' => 'Migrating Operative Systems',
'tables' => ['nombresos']
],
'opengnsys:migration:software-profile' => [
'desc' => 'Migrating Software and Profiles',
'tables' => ['tiposoftwares', 'softwares', 'perfilessoft', 'perfilessoft_softwares']
],
'opengnsys:migration:clients' => [
'desc' => 'Migrating Clients',
'tables' => ['ordenadores']
],
'opengnsys:migration:hardware-profile' => [
'desc' => 'Migrating Hardware and Profiles',
'tables' => ['tipohardwares', 'hardwares', 'perfileshard']
],
'opengnsys:migration:partition' => [
'desc' => 'Migrating Partitions',
'tables' => ['ordenadores_particiones']
],
];
// Execute Orchestration with guaranteed cleanup
try {
$io->section("Phase 2: Executing Migration Commands");
$app = $this->getApplication();
foreach ($commands as $cmdName => $info) {
$io->text("-> " . $info['desc']);
// Check dependencies
$missingTables = array_diff($info['tables'], $currentTables);
if (!empty($missingTables)) {
$io->warning("Skipped. Missing required tables: " . implode(', ', $missingTables));
continue;
}
try {
$consolePath = dirname(__DIR__, 3) . '/bin/console';
$commandLine = "php " . escapeshellarg($consolePath) . " $cmdName 2>&1";
$cmdOutput = [];
exec($commandLine, $cmdOutput, $returnCode);
foreach ($cmdOutput as $line) {
$io->writeln(' ' . $line);
}
if ($returnCode !== 0) {
$io->error("Command $cmdName failed with code $returnCode.");
}
$this->dispatchProgress($input);
} catch (\Exception $e) {
$io->error("Exception during $cmdName: " . $e->getMessage());
$this->dispatchProgress($input);
}
}
// Migrate Users manually since there is no official command for it
$this->importUsers($connection, $io);
$this->dispatchProgress($input);
} finally {
// Cleanup ALWAYS runs
$io->section("Phase 3: Cleaning up injected tables");
if (!empty($injectedTables)) {
$connection->executeStatement("SET FOREIGN_KEY_CHECKS=0");
foreach ($injectedTables as $table) {
$connection->executeStatement("DROP TABLE IF EXISTS `$table`");
}
$connection->executeStatement("SET FOREIGN_KEY_CHECKS=1");
$io->success("Dropped " . count($injectedTables) . " temporary tables.");
}
}
$io->success('Migration orchestrator finished successfully!');
$this->finalize(true, "Migration completed successfully.", $input);
return Command::SUCCESS;
} catch (\Exception $e) {
$io->error("Error: " . $e->getMessage());
$this->finalize(false, "Error: " . $e->getMessage(), $input);
return Command::FAILURE;
}
}
private function dispatchProgress(InputInterface $input): void
{
if ($this->hub) {
$logFile = $input->getOption('log-file');
if ($logFile && file_exists($logFile)) {
$outputStr = file_get_contents($logFile);
$update = new Update(
'/migration',
json_encode([
'type' => 'migration_progress',
'output' => $outputStr
])
);
$this->hub->publish($update);
}
}
}
private function finalize(bool $success, string $message, InputInterface $input): void
{
if ($this->hub) {
$outputStr = $message;
$logFile = $input->getOption('log-file');
if ($logFile && file_exists($logFile)) {
$outputStr = file_get_contents($logFile);
}
$update = new Update(
'/migration',
json_encode([
'type' => 'migration_result',
'status' => $success ? 'success' : 'error',
'output' => $outputStr
])
);
$this->hub->publish($update);
}
$cleanupFiles = $input->getOption('cleanup-file');
if (!empty($cleanupFiles)) {
foreach ($cleanupFiles as $f) {
if (file_exists($f)) {
@unlink($f);
}
}
}
}
private function importUsers(\Doctrine\DBAL\Connection $connection, SymfonyStyle $io): void
{
$io->text("-> Migrating Users and Permissions...");
try {
// Check if tables exist
$connection->executeQuery("SELECT 1 FROM usuarios LIMIT 1");
} catch (\Exception $e) {
$io->warning("Legacy table 'usuarios' not found. Skipping users migration.");
return;
}
$users = $connection->fetchAllAssociative("SELECT * FROM usuarios");
$usersMap = [];
$userRepo = $this->entityManager->getRepository(User::class);
foreach ($users as $row) {
// Check if user already exists
$existingUser = $userRepo->findOneBy(['username' => $row['usuario']]);
if ($existingUser) {
$usersMap[$row['idusuario']] = $existingUser;
continue;
}
$user = new User();
$user->setUsername($row['usuario']);
// $user->setEmail($row['email'] ?? null); // User entity doesn't have email yet
$user->setRoles(['ROLE_ADMIN']);
// Standard generic password
$user->setPassword($this->passwordHasher->hashPassword($user, '12345678'));
$this->entityManager->persist($user);
$usersMap[$row['idusuario']] = $user;
}
$this->entityManager->flush();
try {
$connection->executeQuery("SELECT 1 FROM administradores_centros LIMIT 1");
// Assign access to Centros based on legacy `administradores_centros`
$adminCentros = $connection->fetchAllAssociative("
SELECT ac.idusuario, c.nombrecentro
FROM administradores_centros ac
JOIN centros c ON ac.idcentro = c.idcentro
");
$ouRepo = $this->entityManager->getRepository(OrganizationalUnit::class);
foreach ($adminCentros as $row) {
$idUser = $row['idusuario'];
$centerName = $row['nombrecentro'];
if (isset($usersMap[$idUser])) {
$ou = $ouRepo->findOneBy(['name' => $centerName, 'type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]);
if ($ou) {
$usersMap[$idUser]->addAllowedOrganizationalUnit($ou);
}
}
}
$this->entityManager->flush();
} catch (\Exception $e) {
// Table doesn't exist, ignore
}
}
}

View File

@ -3,7 +3,6 @@
namespace App\Command\Migration;
use App\Entity\Client;
use App\Model\ClientStatus;
use App\Entity\HardwareProfile;
use App\Entity\OrganizationalUnit;
use App\Model\OrganizationalUnitTypes;
@ -29,7 +28,7 @@ class MigrateClientsCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$clientRepository = $this->entityManager->getRepository(Client::class);
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
@ -44,89 +43,52 @@ class MigrateClientsCommand extends Command
$rsmClients->addScalarResult('ip', 'ip');
$rsmClients->addScalarResult('netiface', 'netiface');
$rsmClients->addScalarResult('netdriver', 'netdriver');
$rsmClients->addScalarResult('idperfilhard', 'idperfilhard');
$rsmClients->addScalarResult('grupoid', 'grupoid');
$rsmClients->addScalarResult('idaula', 'idaula');
$rsmClients->addScalarResult('idperfilhard', 'ordenadores.idperfilhard');
$rsmClients->addScalarResult('grupoid', 'ordenadores.grupoid');
$rsmClients->addScalarResult('idaula', 'ordenadores.idaula');
$clientsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idordenador, nombreordenador, numserie, ip, mac, netiface, netdriver, idaula, grupoid, idperfilhard FROM ordenadores', $rsmClients);
$clientsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idordenador, nombreordenador, numserie, ip, mac, netiface, netdriver, ordenadores.idaula, ordenadores.grupoid, ordenadores.idperfilhard FROM ordenadores LEFT JOIN aulas ON ordenadores.idaula = aulas.idaula LEFT JOIN perfileshard ON ordenadores.idperfilhard = perfileshard.idperfilhard', $rsmClients);
$clients = $clientsQuery->getResult();
/** Ordenadores **/
$output->writeln("CLIENTES TOTAL: ". count($clients));
$count = 0;
foreach ($clients as $client){
try {
$clientEntity = $clientRepository->findOneBy(['migrationId' => $client['idordenador']]);
if(!$clientEntity){
// Proactive check to avoid EntityManager closure on duplicate key
if ($client['ip'] && $clientRepository->findOneBy(['ip' => $client['ip']])) {
$output->writeln("<error>Skipping client " . $client['nombreordenador'] . " due to duplicate IP: " . $client['ip'] . "</error>");
continue;
}
if ($client['mac'] && $clientRepository->findOneBy(['mac' => $client['mac']])) {
$output->writeln("<error>Skipping client " . $client['nombreordenador'] . " due to duplicate MAC: " . $client['mac'] . "</error>");
continue;
}
$clientEntity = new Client();
$clientEntity->setStatus(ClientStatus::OFF);
$clientEntity->setMigrationId($client['idordenador']);
$clientEntity->setName($client['nombreordenador']);
$clientEntity->setSerialNumber($client['numserie']);
$clientEntity->setNetiface($client['netiface']);
$clientEntity->setNetdriver($client['netdriver']);
// Format MAC: ensure colons and uppercase
$mac = str_replace([':', '-', '.'], '', $client['mac']);
if (strlen($mac) === 12) {
$mac = strtoupper(implode(':', str_split($mac, 2)));
}
$clientEntity->setMac($mac);
$clientEntity->setIp($client['ip']);
$clientEntity->setMaintenance(false);
$clientEntity->setPosition(['x' => 0, 'y' => 0]);
}
$parentMigrationId = (empty($client['grupoid']) || $client['grupoid'] == 0)
? OrganizationalUnitTypes::CLASSROOM . '-' . $client['idaula']
: OrganizationalUnitTypes::CLIENTS_GROUP . '-' . $client['grupoid'];
$organizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $parentMigrationId]);
if (!$organizationalUnit){
$output->writeln("ORGANIZATIONAL UNIT NOT FOUND FOR CLIENT: ". $client['nombreordenador'] . " (ID: ". $parentMigrationId .")");
}
if ($organizationalUnit){
$clientEntity->setOrganizationalUnit($organizationalUnit);
}
// Note: We don't link the 1.1 hardware profile entity here because the 2.0
// HardwareProfile entity is exclusive to the client (OneToOne).
// The population of hardware items will be done in the next command
// based on the client's legacy idperfilhard.
$this->entityManager->persist($clientEntity);
$count++;
if ($count % 100 === 0) {
$output->writeln("... Processed $count clients ...");
$this->entityManager->flush();
$this->entityManager->clear(Client::class);
$this->entityManager->clear(HardwareProfile::class);
}
} catch (\Exception $e) {
$output->writeln("<error>CRITICAL ERROR migrating client " . ($client['nombreordenador'] ?? 'ID:'.$client['idordenador']) . ": " . $e->getMessage() . "</error>");
// Reset EntityManager if a database error occurred
if (!$this->entityManager->isOpen()) {
$output->writeln("<error>EntityManager closed. Stopping migration.</error>");
return Command::FAILURE;
}
$clientEntity = $clientRepository->findOneBy(['migrationId' => $client['idordenador']]);
if(!$clientEntity){
$clientEntity = new Client();
$clientEntity->setMigrationId($client['idordenador']);
$clientEntity->setName($client['nombreordenador']);
$clientEntity->setSerialNumber($client['numserie']);
$clientEntity->setNetiface($client['netiface']);
$clientEntity->setNetdriver($client['netdriver']);
$clientEntity->setMac($client['mac']);
$clientEntity->setIp($client['ip']);
$clientEntity->setMaintenance(false);
$clientEntity->setPosition(['x' => 0, 'y' => 0]);
}
$migrationId = match ($client['ordenadores.grupoid']) {
0 => OrganizationalUnitTypes::CLASSROOM . '-' . $client['ordenadores.idaula'],
default => OrganizationalUnitTypes::CLIENTS_GROUP . '-' . $client['ordenadores.grupoid'],
};
$organizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if (!$organizationalUnit){
$output->writeln("ORGANIZATIONAL UNIT NOT FOUND: ". $migrationId);
}
if ($organizationalUnit){
$clientEntity->setOrganizationalUnit($organizationalUnit);
}
$hardwareProfile = $hardwareProfileRepository->findOneBy(['migrationId' => $client['ordenadores.idperfilhard']]);
if ($hardwareProfile){
$clientEntity->setHardwareProfile($hardwareProfile);
}
$this->entityManager->persist($clientEntity);
}
$this->entityManager->flush();
$output->writeln("CLIENTES MIGRADOS CORRECTAMENTE: $count");
return Command::SUCCESS;
}

View File

@ -2,7 +2,6 @@
namespace App\Command\Migration;
use App\Entity\Client;
use App\Entity\Hardware;
use App\Entity\HardwareProfile;
use App\Entity\HardwareType;
@ -30,9 +29,8 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
try {
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
$hardwareProfileRepository = $this->entityManager->getRepository(HardwareProfile::class);
@ -59,7 +57,6 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
$this->entityManager->persist($hardwareProfileEntity);
}
$this->entityManager->flush();
/** Obtener los hardware de la base de datos antigua **/
$rsmHardware = new ResultSetMapping();
@ -98,79 +95,66 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
$this->entityManager->persist($hardwareEntity);
}
$this->entityManager->flush();
/**
* In OpenGnsys 2.0, HardwareProfile is linked OneToOne with Client and is mandatory.
* We already created empty HardwareProfiles for each client in MigrateClientsCommand.
* Now we populate them with the hardware items from the legacy profiles.
**/
/** Obtener los perfiles hardware de la base de datos antigua **/
$rsmHardwareProfiles = new ResultSetMapping();
$rsmHardwareProfiles->addScalarResult('idperfilhard', 'idperfilhard');
$rsmHardwareProfiles->addScalarResult('descripcion', 'descripcion');
$rsmHardwareProfiles->addScalarResult('comentarios', 'perfilhard.comentarios');
$rsmHardwareProfiles->addScalarResult('grupoid', 'perfilhard.grupoid');
$rsmHardwareProfiles->addScalarResult('idcentro', 'perfilhard.idcentro');
// 1. Get legacy profile-to-hardware relations
$hardwareProfilesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilhard, descripcion, grupos.comentarios, perfileshard.grupoid, perfileshard.idcentro FROM perfileshard LEFT JOIN grupos ON perfileshard.grupoid = grupos.idgrupo', $rsmHardwareProfiles);
$hardwareProfiles = $hardwareProfilesQuery->getResult();
/** Perfiles hardware **/
$output->writeln("PERFILES HARDWARE TOTAL: ". count($hardwareProfiles));
foreach ($hardwareProfiles as $hardwareProfile){
$hardwareProfileEntity = null;
$hardwareProfileEntity = $hardwareProfileRepository->findOneBy(['migrationId' => $hardwareProfile['idperfilhard']]);
if(!$hardwareProfileEntity){
$hardwareProfileEntity = new HardwareProfile();
$hardwareProfileEntity->setMigrationId($hardwareProfile['idperfilhard']);
$hardwareProfileEntity->setDescription($hardwareProfile['descripcion']);
$hardwareProfileEntity->setComments($hardwareProfile['perfilhard.comentarios']);
}
$migrationId = match ($hardwareProfile['perfilhard.grupoid']) {
0 => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT . '-' . $hardwareProfile['perfilhard.idcentro'],
default => OrganizationalUnitTypes::CLASSROOMS_GROUP . '-' . $hardwareProfile['perfilhard.grupoid'],
};
$organizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if ($organizationalUnit){
$hardwareProfileEntity->setOrganizationalUnit($organizationalUnit);
}
$this->entityManager->persist($hardwareProfileEntity);
}
/** Obtener los hardware, y asignarselos a los perfiles hardware **/
$rsmHardwareProfilesRelation = new ResultSetMapping();
$rsmHardwareProfilesRelation->addScalarResult('idperfilhard', 'idperfilhard');
$rsmHardwareProfilesRelation->addScalarResult('idhardware', 'idhardware');
$hardwareProfileRelationsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilhard, idhardware FROM perfileshard_hardwares', $rsmHardwareProfilesRelation);
$hardwareProfileRelations = $hardwareProfileRelationsQuery->getResult();
$hardwareProfilesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilhard, idhardware FROM perfileshard_hardwares', $rsmHardwareProfilesRelation);
$hardwareProfileRelations = $hardwareProfilesQuery->getResult();
$profileItemsMap = [];
foreach ($hardwareProfileRelations as $rel) {
$profileItemsMap[$rel['idperfilhard']][] = $rel['idhardware'];
}
$output->writeln("PERFILES HARDWARE RELACIONES TOTAL: ". count($hardwareProfileRelations));
foreach ($hardwareProfileRelations as $hardwareProfileRelation){
$hardwareProfileEntity = $hardwareProfileRepository->findOneBy(['migrationId' => $hardwareProfileRelation['idperfilhard']]);
$hardwareEntity = $hardwareRepository->findOneBy(['migrationId' => $hardwareProfileRelation['idhardware']]);
// 2. Get all legacy clients and their profile IDs
$rsmClientProfiles = new ResultSetMapping();
$rsmClientProfiles->addScalarResult('idordenador', 'idordenador');
$rsmClientProfiles->addScalarResult('idperfilhard', 'idperfilhard');
$clientProfilesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idordenador, idperfilhard FROM ordenadores', $rsmClientProfiles);
$clientProfiles = $clientProfilesQuery->getResult();
$output->writeln("POPULATING HARDWARE PROFILES FOR ". count($clientProfiles) . " CLIENTS");
$count = 0;
foreach ($clientProfiles as $cp) {
$clientId = $cp['idordenador'];
$legacyProfileId = (int)$cp['idperfilhard'];
// Only create/populate if there's a valid legacy profile
if ($legacyProfileId > 0 && isset($profileItemsMap[$legacyProfileId])) {
$clientEntity = $this->entityManager->getRepository(Client::class)->findOneBy(['migrationId' => $clientId]);
if ($clientEntity) {
$hardwareProfileEntity = $clientEntity->getHardwareProfile();
if (!$hardwareProfileEntity) {
$hardwareProfileEntity = new HardwareProfile();
$hardwareProfileEntity->setClient($clientEntity);
$hardwareProfileEntity->setMigrationId('client-' . $clientId);
$hardwareProfileEntity->setDescription("Hardware Profile for " . $clientEntity->getName());
}
foreach ($profileItemsMap[$legacyProfileId] as $hardwareId) {
$hardwareEntity = $hardwareRepository->findOneBy(['migrationId' => $hardwareId]);
if ($hardwareEntity) {
$hardwareProfileEntity->addHardwareCollection($hardwareEntity);
}
}
$this->entityManager->persist($hardwareProfileEntity);
}
}
$count++;
if ($count % 100 === 0) {
$this->entityManager->flush();
if ($hardwareProfileEntity && $hardwareEntity){
$hardwareProfileEntity->addHardwareCollection($hardwareEntity);
$this->entityManager->persist($hardwareProfileEntity);
}
}
$this->entityManager->flush();
return Command::SUCCESS;
} catch (\Throwable $e) {
$output->writeln("<error>FATAL ERROR IN HARDWARE COMMAND: " . $e->getMessage() . "</error>");
$output->writeln($e->getTraceAsString());
return Command::FAILURE;
}
return Command::SUCCESS;
}
}

View File

@ -7,7 +7,6 @@ namespace App\Command\Migration;
use App\Entity\Client;
use App\Entity\Image;
use App\Entity\ImageRepository;
use App\Entity\ImageImageRepository;
use App\Entity\OrganizationalUnit;
use App\Model\ImageStatus;
use App\Model\OrganizationalUnitTypes;
@ -33,7 +32,7 @@ class MigrateImagesCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$imagesRepository = $this->entityManager->getRepository(Image::class);
$clientRepository = $this->entityManager->getRepository(Client::class);
@ -81,20 +80,16 @@ class MigrateImagesCommand extends Command
$imageEntity->setMigrationId((string) $image['idimagen']);
$imageEntity->setName($image['nombreca']);
$imageEntity->setClient($clientEntity);
$imageEntity->setType('monolithic');
$imageEntity->setIsGlobal(false);
$this->entityManager->persist($imageEntity);
$imageImageRepository = new ImageImageRepository();
$imageImageRepository->setImage($imageEntity);
$imageImageRepository->setRepository($repository);
$imageImageRepository->setName($image['nombreca']);
$imageImageRepository->setStatus(ImageStatus::SUCCESS);
$imageImageRepository->setVersion(is_numeric($image['revision']) ? (int) $image['revision'] : null);
$imageImageRepository->setDescription($image['descripcion']);
$imageImageRepository->setRemotePc(false);
$this->entityManager->persist($imageImageRepository);
//$imageEntity->setOrganizationalUnit($ouEntity);
$imageEntity->setRemotePc(false);
$imageEntity->setStatus(ImageStatus::SUCCESS);
$imageEntity->setRepository($repository);
$imageEntity->setRevision((string) $image['revision']);
$imageEntity->setDescription($image['descripcion']);
$imageEntity->setComments($image['comentarios']);
}
$this->entityManager->persist($imageEntity);
$this->entityManager->flush();
}

View File

@ -28,7 +28,7 @@ class MigrateOperativeSystemCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$osRepository = $this->entityManager->getRepository(OperativeSystem::class);

View File

@ -24,235 +24,172 @@ class MigrateOrganizationalUnitCommand extends Command
parent::__construct();
}
private array $seenNames = [];
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
try {
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
/** Obtener los centros de la base de datos antigua **/
$rsmCenters = new ResultSetMapping();
$rsmCenters->addScalarResult('idcentro', 'idcentro');
$rsmCenters->addScalarResult('nombrecentro', 'nombrecentro');
$rsmCenters->addScalarResult('comentarios', 'comentarios');
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
$centersQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idcentro, nombrecentro, comentarios FROM centros', $rsmCenters);
$centers = $centersQuery->getResult();
/** Centros **/
$rsmCenters = new ResultSetMapping();
$rsmCenters->addScalarResult('idcentro', 'idcentro');
$rsmCenters->addScalarResult('nombrecentro', 'nombrecentro');
$rsmCenters->addScalarResult('comentarios', 'comentarios');
/** Obtener los grupos de aulas de la base de datos antigua **/
$rsmGroups = new ResultSetMapping();
$rsmGroups->addScalarResult('idgrupo', 'idgrupo');
$rsmGroups->addScalarResult('nombregrupo', 'nombregrupo');
$rsmGroups->addScalarResult('comentarios', 'grupos.comentarios');
$rsmGroups->addScalarResult('idcentro', 'grupos.idcentro');
$centersQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idcentro, nombrecentro, comentarios FROM centros', $rsmCenters);
$centers = $centersQuery->getResult();
$groupsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idgrupo, nombregrupo, grupos.comentarios, grupos.idcentro FROM grupos LEFT JOIN centros ON grupos.idcentro = centros.idcentro', $rsmGroups);
$groups = $groupsQuery->getResult();
$output->writeln("CENTROS TOTAL: ". count($centers));
foreach ($centers as $center){
$migrationId = OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$center['idcentro'];
$centerOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if(!$centerOrganizationalUnit){
$centerOrganizationalUnit = new OrganizationalUnit();
$centerOrganizationalUnit->setMigrationId($migrationId);
}
$centerOrganizationalUnit->setType(OrganizationalUnitTypes::ORGANIZATIONAL_UNIT);
$name = $center['nombrecentro'];
$key = 'root';
$originalName = $name;
$counter = 1;
while (isset($this->seenNames[$key][$name])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
// Also check database but exclude the current entity if it already exists
$existingOU = $organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => null]);
if ($existingOU && $existingOU->getMigrationId() !== $migrationId) {
while ($organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => null])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
}
$this->seenNames[$key][$name] = true;
/** Obtener las aulas de la base de datos antigua **/
$rsmClassrooms = new ResultSetMapping();
$rsmClassrooms->addScalarResult('idaula', 'idaula');
$rsmClassrooms->addScalarResult('nombreaula', 'nombreaula');
$rsmClassrooms->addScalarResult('comentarios', 'aulas.comentarios');
$rsmClassrooms->addScalarResult('grupoid', 'aulas.grupoid');
$rsmClassrooms->addScalarResult('idcentro', 'aulas.idcentro');
$rsmClassrooms->addScalarResult('proxy', 'proxy');
$rsmClassrooms->addScalarResult('dns', 'dns');
$rsmClassrooms->addScalarResult('netmask', 'netmask');
$rsmClassrooms->addScalarResult('router', 'router');
$rsmClassrooms->addScalarResult('ntp', 'ntp');
$rsmClassrooms->addScalarResult('timep2p', 'timep2p');
$rsmClassrooms->addScalarResult('modp2p', 'modp2p');
$rsmClassrooms->addScalarResult('ipmul', 'ipmul');
$rsmClassrooms->addScalarResult('pormul', 'pormul');
$rsmClassrooms->addScalarResult('modomul', 'modomul');
$rsmClassrooms->addScalarResult('velmul', 'velmul');
$rsmClassrooms->addScalarResult('pizarra', 'pizarra');
$rsmClassrooms->addScalarResult('cagnon', 'cagnon');
$rsmClassrooms->addScalarResult('ubicacion', 'ubicacion');
$centerOrganizationalUnit->setName($name);
$roomsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idaula, nombreaula, aulas.comentarios, aulas.grupoid, aulas.idcentro, proxy, dns, netmask, router, ntp, timep2p, modp2p, modomul, ipmul, velmul, pormul, pizarra, cagnon, ubicacion FROM aulas LEFT JOIN grupos ON aulas.grupoid = grupos.idgrupo', $rsmClassrooms);
$rooms = $roomsQuery->getResult();
/** Obtener los grupos de ordenadores de la base de datos antigua **/
$rsmClientGroups = new ResultSetMapping();
$rsmClientGroups->addScalarResult('idgrupo', 'idgrupo');
$rsmClientGroups->addScalarResult('nombregrupoordenador', 'nombregrupoordenador');
$rsmClientGroups->addScalarResult('comentarios', 'gruposordenadores.comentarios');
$rsmClientGroups->addScalarResult('idaula', 'gruposordenadores.idaula');
$clientGroupsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idgrupo, nombregrupoordenador, gruposordenadores.comentarios, gruposordenadores.idaula FROM gruposordenadores LEFT JOIN aulas ON gruposordenadores.idaula = aulas.idaula', $rsmClientGroups);
$clientGroups = $clientGroupsQuery->getResult();
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
/** Centros **/
$output->writeln("CENTROS TOTAL: ". count($centers));
foreach ($centers as $center){
$centerOrganizationalUnit = null;
$centerOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$center['idcentro'], 'type' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT]);
if(!$centerOrganizationalUnit){
$centerOrganizationalUnit = new OrganizationalUnit();
$centerOrganizationalUnit->setMigrationId(OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$center['idcentro']);
$centerOrganizationalUnit->setName($center['nombrecentro']);
$centerOrganizationalUnit->setComments($center['comentarios']);
$centerOrganizationalUnit->setType(OrganizationalUnitTypes::ORGANIZATIONAL_UNIT);
$this->entityManager->persist($centerOrganizationalUnit);
}
$this->entityManager->flush();
}
$this->entityManager->flush();
/** Grupos de aulas **/
$rsmGroups = new ResultSetMapping();
$rsmGroups->addScalarResult('idgrupo', 'idgrupo');
$rsmGroups->addScalarResult('nombregrupo', 'nombregrupo');
$rsmGroups->addScalarResult('comentarios', 'comentarios');
$rsmGroups->addScalarResult('idcentro', 'idcentro');
$groupsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idgrupo, nombregrupo, comentarios, idcentro FROM grupos', $rsmGroups);
$groups = $groupsQuery->getResult();
$output->writeln("GRUPOS DE AULAS TOTAL: ". count($groups));
foreach ($groups as $group){
$migrationId = OrganizationalUnitTypes::CLASSROOMS_GROUP.'-'.$group['idgrupo'];
$groupPcOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if(!$groupPcOrganizationalUnit){
$groupPcOrganizationalUnit = new OrganizationalUnit();
$groupPcOrganizationalUnit->setMigrationId($migrationId);
}
/** Grupos de aulas **/
$output->writeln("GRUPOS DE AULAS TOTAL: ". count($groups));
foreach ($groups as $group){
$groupPcOrganizationalUnit = null;
$groupPcOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::CLASSROOMS_GROUP.'-'.$group['idgrupo'], 'type' => OrganizationalUnitTypes::CLASSROOMS_GROUP]);
if(!$groupPcOrganizationalUnit){
$groupPcOrganizationalUnit = new OrganizationalUnit();
$groupPcOrganizationalUnit->setMigrationId(OrganizationalUnitTypes::CLASSROOMS_GROUP.'-'.$group['idgrupo']);
$groupPcOrganizationalUnit->setName($group['nombregrupo']);
$groupPcOrganizationalUnit->setComments($group['grupos.comentarios']);
$groupPcOrganizationalUnit->setType(OrganizationalUnitTypes::CLASSROOMS_GROUP);
$center = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$group['idcentro']]);
$center = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$group['grupos.idcentro']]);
if ($center){
$groupPcOrganizationalUnit->setParent($center);
}
$name = $group['nombregrupo'];
$key = $center ? $center->getMigrationId() : 'root';
$originalName = $name;
$counter = 1;
while (isset($this->seenNames[$key][$name])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
$existingOU = $organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => $center]);
if ($existingOU && $existingOU->getMigrationId() !== $migrationId) {
while ($organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => $center])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
}
$this->seenNames[$key][$name] = true;
$groupPcOrganizationalUnit->setName($name);
$groupPcOrganizationalUnit->setComments($group['comentarios']);
$this->entityManager->persist($groupPcOrganizationalUnit);
}
$this->entityManager->flush();
}
$this->entityManager->flush();
/** Aulas **/
$rsmRooms = new ResultSetMapping();
$rsmRooms->addScalarResult('idaula', 'idaula');
$rsmRooms->addScalarResult('nombreaula', 'nombreaula');
$rsmRooms->addScalarResult('comentarios', 'comentarios');
$rsmRooms->addScalarResult('pizarra', 'pizarra');
$rsmRooms->addScalarResult('cagnon', 'cagnon');
$rsmRooms->addScalarResult('ubicacion', 'ubicacion');
$rsmRooms->addScalarResult('idcentro', 'idcentro');
$rsmRooms->addScalarResult('grupoid', 'grupoid');
$roomsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idaula, nombreaula, comentarios, pizarra, cagnon, ubicacion, idcentro, grupoid FROM aulas', $rsmRooms);
$rooms = $roomsQuery->getResult();
$output->writeln("AULAS TOTAL: ". count($rooms));
foreach ($rooms as $room){
$migrationId = OrganizationalUnitTypes::CLASSROOM.'-'.$room['idaula'];
$roomOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if(!$roomOrganizationalUnit){
$roomOrganizationalUnit = new OrganizationalUnit();
$roomOrganizationalUnit->setMigrationId($migrationId);
}
$roomOrganizationalUnit->setType(OrganizationalUnitTypes::CLASSROOM);
// Hierarchy: If grupoid is 0 or null, parent is center. Otherwise, parent is classrooms-group.
$parentMigrationId = (empty($room['grupoid']) || $room['grupoid'] == 0)
? OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$room['idcentro']
: OrganizationalUnitTypes::CLASSROOMS_GROUP.'-'.$room['grupoid'];
$parentOU = $organizationalUnitRepository->findOneBy(['migrationId' => $parentMigrationId]);
if ($parentOU){
$roomOrganizationalUnit->setParent($parentOU);
}
$name = $room['nombreaula'];
$key = $parentOU ? $parentOU->getMigrationId() : 'root';
$originalName = $name;
$counter = 1;
while (isset($this->seenNames[$key][$name])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
$existingOU = $organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => $parentOU]);
if ($existingOU && $existingOU->getMigrationId() !== $migrationId) {
while ($organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => $parentOU])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
}
$this->seenNames[$key][$name] = true;
$roomOrganizationalUnit->setName($name);
$roomOrganizationalUnit->setComments($room['comentarios']);
/** Aulas **/
$output->writeln("AULAS TOTAL: ". count($rooms));
foreach ($rooms as $room){
$roomOrganizationalUnit = null;
$roomOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::CLASSROOM.'-'.$room['idaula'], 'type' => OrganizationalUnitTypes::CLASSROOM]);
if(!$roomOrganizationalUnit){
$roomOrganizationalUnit = new OrganizationalUnit();
$roomOrganizationalUnit->setMigrationId(OrganizationalUnitTypes::CLASSROOM.'-'.$room['idaula']);
$roomOrganizationalUnit->setName($room['nombreaula']);
$roomOrganizationalUnit->setComments($room['aulas.comentarios']);
$roomOrganizationalUnit->setBoard($room['pizarra']);
$roomOrganizationalUnit->setProjector($room['cagnon']);
$roomOrganizationalUnit->setLocation($room['ubicacion']);
$roomOrganizationalUnit->setType(OrganizationalUnitTypes::CLASSROOM);
$migrationId = $room['aulas.grupoid'] === 0 ? OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$room['aulas.idcentro'] : OrganizationalUnitTypes::CLASSROOMS_GROUP.'-'.$room['aulas.grupoid'];
$organizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if ($organizationalUnit){
$roomOrganizationalUnit->setParent($organizationalUnit);
}
$this->entityManager->persist($roomOrganizationalUnit);
}
$this->entityManager->flush();
/** Grupos de ordenadores **/
$rsmClientGroups = new ResultSetMapping();
$rsmClientGroups->addScalarResult('idgrupo', 'idgrupo');
$rsmClientGroups->addScalarResult('nombregrupoordenador', 'nombregrupoordenador');
$rsmClientGroups->addScalarResult('comentarios', 'comentarios');
$rsmClientGroups->addScalarResult('idaula', 'idaula');
$networkSettings = $roomOrganizationalUnit->getNetworkSettings();
if(!$networkSettings){
$networkSettings = new NetworkSettings();
$roomOrganizationalUnit->setNetworkSettings($networkSettings);
$this->entityManager->persist($networkSettings);
}
$networkSettings->setProxy($room['proxy']);
$networkSettings->setDns($room['dns']);
$networkSettings->setNetmask($room['netmask']);
$networkSettings->setRouter($room['router']);
$networkSettings->setNtp($room['ntp']);
$networkSettings->setP2pTime($room['timep2p']);
$networkSettings->setP2pMode($room['modp2p']);
$networkSettings->setMcastIp($room['ipmul']);
$networkSettings->setMcastSpeed($room['velmul']);
$networkSettings->setMcastPort($room['pormul']);
$networkSettings->setMcastMode($room['modomul']);
}
$clientGroupsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idgrupo, nombregrupoordenador, comentarios, idaula FROM gruposordenadores', $rsmClientGroups);
$clientGroups = $clientGroupsQuery->getResult();
$this->entityManager->flush();
$output->writeln("GRUPOS ORDENADORES ". count($clientGroups));
foreach ($clientGroups as $clientGroup){
$migrationId = OrganizationalUnitTypes::CLIENTS_GROUP.'-'.$clientGroup['idgrupo'];
$groupPcOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if(!$groupPcOrganizationalUnit){
$groupPcOrganizationalUnit = new OrganizationalUnit();
$groupPcOrganizationalUnit->setMigrationId($migrationId);
}
/** Grupo Ordenador **/
$output->writeln("GRUPOS ORDENADORES ". count($clientGroups));
foreach ($clientGroups as $clientGroup){
$groupPcOrganizationalUnit = null;
$groupPcOrganizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::CLIENTS_GROUP.'-'.$clientGroup['idgrupo'], 'type' => OrganizationalUnitTypes::CLIENTS_GROUP]);
if(!$groupPcOrganizationalUnit){
$groupPcOrganizationalUnit = new OrganizationalUnit();
$groupPcOrganizationalUnit->setMigrationId(OrganizationalUnitTypes::CLIENTS_GROUP.'-'.$clientGroup['idgrupo']);
$groupPcOrganizationalUnit->setName($clientGroup['nombregrupoordenador']);
$groupPcOrganizationalUnit->setComments($clientGroup['gruposordenadores.comentarios']);
$groupPcOrganizationalUnit->setType(OrganizationalUnitTypes::CLIENTS_GROUP);
$room = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::CLASSROOM.'-'.$clientGroup['idaula']]);
$room = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::CLASSROOM.'-'.$clientGroup['gruposordenadores.idaula']]);
if ($room){
$groupPcOrganizationalUnit->setParent($room);
}
$name = $clientGroup['nombregrupoordenador'];
$key = $room ? $room->getMigrationId() : 'root';
$originalName = $name;
$counter = 1;
while (isset($this->seenNames[$key][$name])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
$existingOU = $organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => $room]);
if ($existingOU && $existingOU->getMigrationId() !== $migrationId) {
while ($organizationalUnitRepository->findOneBy(['name' => $name, 'parent' => $room])) {
$name = $originalName . ' (' . $counter . ')';
$counter++;
}
}
$this->seenNames[$key][$name] = true;
$groupPcOrganizationalUnit->setName($name);
$groupPcOrganizationalUnit->setComments($clientGroup['comentarios']);
$this->entityManager->persist($groupPcOrganizationalUnit);
}
$this->entityManager->flush();
return Command::SUCCESS;
} catch (\Throwable $e) {
$output->writeln("<error>FATAL ERROR IN COMMAND: " . $e->getMessage() . "</error>");
$output->writeln($e->getTraceAsString());
return Command::FAILURE;
}
$this->entityManager->flush();
return 1;
}
}

View File

@ -31,7 +31,7 @@ class MigratePartitionClientCommand extends Command
ini_set('memory_limit', '512M');
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$clientRepository = $this->entityManager->getRepository(Client::class);
$operativeSystemRepository = $this->entityManager->getRepository(OperativeSystem::class);
@ -51,21 +51,17 @@ class MigratePartitionClientCommand extends Command
/** Particiones **/
$output->writeln("PARTICIONES TOTAL: ". count($partitions));
$count = 0;
foreach ($partitions as $partition){
$clientEntity = $clientRepository->findOneBy(['migrationId' => $partition['idordenador']]);
if(!$clientEntity){
$output->writeln("<error>No se ha encontrado el cliente con migrationId: ". $partition['idordenador'] . " en la tabla client de 2.0</error>");
$output->writeln("No se ha encontrado el cliente con id: ". $partition['idordenador']);
continue;
}
$operativeSystemEntity = null;
$legacyOsId = (int)$partition['idnombreso'];
if ($legacyOsId > 0) {
$operativeSystemEntity = $operativeSystemRepository->findOneBy(['migrationId' => $legacyOsId]);
if(!$operativeSystemEntity){
$output->writeln("No se ha encontrado el sistema operativo con id: ". $legacyOsId . " (se insertará con SO null)");
}
$operativeSystemEntity = $operativeSystemRepository->findOneBy(['migrationId' => $partition['idnombreso']]);
if(!$operativeSystemEntity){
$output->writeln("No se ha encontrado el sistema operativo con id: ". $partition['idnombreso']);
continue;
}
$partitionEntity = new Partition();
@ -78,14 +74,8 @@ class MigratePartitionClientCommand extends Command
$partitionEntity->setOperativeSystem($operativeSystemEntity);
$this->entityManager->persist($partitionEntity);
$count++;
if ($count % 100 === 0) {
$this->entityManager->flush();
$this->entityManager->clear(Partition::class);
}
$this->entityManager->flush();
}
$this->entityManager->flush();
return Command::SUCCESS;
return 1;
}
}

View File

@ -33,7 +33,7 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
$operativeSystemRepository = $this->entityManager->getRepository(OperativeSystem::class);
@ -71,18 +71,32 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
$softwareEntity->setType($type);
}
$migrationId = match ($software['softwares.grupoid']) {
0 => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT . '-' . $software['softwares.idcentro'],
default => OrganizationalUnitTypes::CLASSROOMS_GROUP . '-' . $software['softwares.grupoid'],
};
$organizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
/*
if ($organizationalUnit){
$softwareEntity->setOrganizationalUnit($organizationalUnit);
}*/
$this->entityManager->persist($softwareEntity);
}
$this->entityManager->flush();
/** Obtener los perfiles software de la base de datos antigua **/
$rsmSoftwareProfiles = new ResultSetMapping();
$rsmSoftwareProfiles->addScalarResult('idperfilsoft', 'idperfilsoft');
$rsmSoftwareProfiles->addScalarResult('descripcion', 'descripcion');
$rsmSoftwareProfiles->addScalarResult('comentarios', 'comentarios');
$rsmSoftwareProfiles->addScalarResult('idnombreso', 'idnombreso');
$rsmSoftwareProfiles->addScalarResult('comentarios', 'perfilessoft.comentarios');
$rsmSoftwareProfiles->addScalarResult('grupoid', 'perfilessoft.grupoid');
$rsmSoftwareProfiles->addScalarResult('idcentro', 'perfilessoft.idcentro');
$rsmSoftwareProfiles->addScalarResult('idnombreso', 'perfilessoft.idnombreso');
$softwareProfilesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilsoft, descripcion, comentarios, idnombreso FROM perfilessoft', $rsmSoftwareProfiles);
$softwareProfilesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilsoft, descripcion, grupos.comentarios, perfilessoft.grupoid, perfilessoft.idcentro, perfilessoft.idnombreso FROM perfilessoft LEFT JOIN grupos ON perfilessoft.grupoid = grupos.idgrupo', $rsmSoftwareProfiles);
$softwareProfiles = $softwareProfilesQuery->getResult();
/** Perfiles software **/
@ -94,10 +108,21 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
$softwareProfileEntity = new SoftwareProfile();
$softwareProfileEntity->setMigrationId($softwareProfile['idperfilsoft']);
$softwareProfileEntity->setDescription($softwareProfile['descripcion']);
$softwareProfileEntity->setComments($softwareProfile['comentarios']);
$softwareProfileEntity->setComments($softwareProfile['perfilessoft.comentarios']);
}
$operativeSystem = $operativeSystemRepository->findOneBy(['migrationId' => $softwareProfile['idnombreso']]);
$migrationId = match ($softwareProfile['perfilessoft.grupoid']) {
0 => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT . '-' . $softwareProfile['perfilessoft.idcentro'],
default => OrganizationalUnitTypes::CLASSROOMS_GROUP . '-' . $softwareProfile['perfilessoft.grupoid'],
};
$organizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);
if ($organizationalUnit){
$softwareProfileEntity->setOrganizationalUnit($organizationalUnit);
}
$operativeSystem = $operativeSystemRepository->findOneBy(['migrationId' => $softwareProfile['perfilessoft.idnombreso']]);
if ($operativeSystem){
$softwareProfileEntity->setOperativeSystem($operativeSystem);
@ -105,7 +130,6 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
$this->entityManager->persist($softwareProfileEntity);
}
$this->entityManager->flush();
/** Obtener los software, y asignarselos a los perfiles software **/
$rsmSoftwareProfilesRelation = new ResultSetMapping();

View File

@ -1,114 +0,0 @@
<?php
namespace App\Command;
use App\Controller\OgBoot\PxeBootFile\PostAction as PostPxeAction;
use App\Model\TraceStatus;
use App\Repository\ClientRepository;
use App\Repository\TraceRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'opengnsys:pxe:sync',
description: 'Sincroniza el fichero PXE de un cliente basándose en su plantilla asignada en BD.',
)]
class PxeSyncCommand extends Command
{
public function __construct(
private readonly ClientRepository $clientRepository,
private readonly TraceRepository $traceRepository,
private readonly EntityManagerInterface $entityManager,
private readonly PostPxeAction $postPxeAction
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('mac', InputArgument::REQUIRED, 'Dirección MAC del cliente')
->addArgument('delay', InputArgument::OPTIONAL, 'Tiempo de espera en segundos antes de sincronizar', 0)
->addOption('trace-id', null, InputOption::VALUE_OPTIONAL, 'ID de la traza asociada');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$mac = $input->getArgument('mac');
$delay = (int) $input->getArgument('delay');
$traceId = $input->getOption('trace-id');
$trace = null;
if ($traceId) {
$trace = $this->traceRepository->find($traceId);
if ($trace) {
$trace->setStatus(TraceStatus::IN_PROGRESS);
$this->entityManager->flush();
}
}
if ($delay > 0) {
$output->writeln("Esperando $delay segundos...");
sleep($delay);
}
$client = $this->clientRepository->findOneBy(['mac' => $mac]);
if (!$client) {
$msg = "Cliente con MAC $mac no encontrado";
$output->writeln("<error>$msg</error>");
if ($trace) {
$trace->setStatus(TraceStatus::FAILED);
$trace->setOutput($msg);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->flush();
}
return Command::FAILURE;
}
$template = $client->getTemplate();
if (!$template) {
$msg = "El cliente no tiene una plantilla asignada";
$output->writeln("<error>$msg</error>");
if ($trace) {
$trace->setStatus(TraceStatus::FAILED);
$trace->setOutput($msg);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->flush();
}
return Command::FAILURE;
}
$output->writeln("Sincronizando PXE para el cliente {$client->getName()} ({$mac}) con la plantilla {$template->getName()}...");
try {
$this->postPxeAction->__invoke($client, $template);
$output->writeln("<info>Sincronización completada con éxito</info>");
if ($trace) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setOutput("Sincronización completada con éxito");
$trace->setFinishedAt(new \DateTime());
$this->entityManager->flush();
}
return Command::SUCCESS;
} catch (\Exception $e) {
$msg = "Error durante la sincronización: " . $e->getMessage();
$output->writeln("<error>$msg</error>");
if ($trace) {
$trace->setStatus(TraceStatus::FAILED);
$trace->setOutput($msg);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->flush();
}
return Command::FAILURE;
}
}
}

View File

@ -17,10 +17,12 @@ use App\Entity\CommandTask;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\Partition;
use App\Entity\Trace;
use App\Model\ClientStatus;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use App\Repository\ClientRepository;
use App\Repository\CommandTaskRepository;
use App\Service\CommandTaskTraceCreator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
@ -39,7 +41,6 @@ class RunScheduledCommandTasksCommand extends Command
private readonly DeployImageAction $deployImageAction,
private readonly CreateImageAction $createImageAction,
private readonly PartitionAssistantAction $partitionAssistantAction,
private readonly CommandTaskTraceCreator $commandTaskTraceCreator,
)
{
parent::__construct();
@ -77,14 +78,14 @@ class RunScheduledCommandTasksCommand extends Command
if ($isDue && $notYetExecuted) {
$output->writeln("Ejecutando tarea: " . $task->getName());
if ($task->getScope() !== 'clients') {
$ou = $task->getOrganizationalUnit();
$clients = $ou ? $this->clientRepository->findClientsByOrganizationalUnitAndDescendants($ou->getId()) : [];
} else {
$clients = $task->getClients();
}
$scripts = $task->getCommandTaskScripts()->toArray();
usort($scripts, fn($a, $b) => $a->getExecutionOrder() <=> $b->getExecutionOrder());
$this->commandTaskTraceCreator->createPendingTraces($task, $clients);
foreach ($scripts as $script) {
$output->writeln(" - Creando traza para script de tipo {$script->getType()} con orden {$script->getExecutionOrder()}");
$this->createTraceForScript($script, $task, $output);
}
$task->setLastExecution(new \DateTimeImmutable('now', new \DateTimeZone('UTC')));
$task->setNextExecution($task->calculateNextExecutionDate());
@ -97,6 +98,127 @@ class RunScheduledCommandTasksCommand extends Command
return Command::SUCCESS;
}
private function createTraceForScript($script, CommandTask $task, OutputInterface $output): void
{
$scriptParameters = $script->getParameters();
if ($task->getScope() !== 'clients') {
$ou = $task->getOrganizationalUnit();
$clients = $ou ? $this->clientRepository->findClientsByOrganizationalUnitAndDescendants($ou->getId()) : [];
} else {
$clients = $task->getClients();
}
foreach ($clients as $client) {
$trace = new Trace();
$trace->setClient($client);
$trace->setStatus(TraceStatus::PENDING);
$trace->setExecutedAt(new \DateTime());
switch ($script->getType()) {
case 'run-script':
$trace->setCommand(CommandTypes::RUN_SCRIPT);
$trace->setInput([
'script' => $script->getContent()
]);
break;
case 'deploy-image':
$trace->setCommand(CommandTypes::DEPLOY_IMAGE);
$input = [
'imageImageRepository' => $scriptParameters['imageUuid']
];
if (isset($scriptParameters['method'])) {
$input['method'] = $scriptParameters['method'];
}
if (isset($scriptParameters['type'])) {
$input['type'] = $scriptParameters['type'];
}
if (isset($scriptParameters['diskNumber'])) {
$input['diskNumber'] = $scriptParameters['diskNumber'];
}
if (isset($scriptParameters['partitionNumber'])) {
$input['partitionNumber'] = $scriptParameters['partitionNumber'];
}
if (isset($scriptParameters['mcastMode'])) {
$input['mcastMode'] = $scriptParameters['mcastMode'];
}
if (isset($scriptParameters['mcastSpeed'])) {
$input['mcastSpeed'] = $scriptParameters['mcastSpeed'];
}
if (isset($scriptParameters['mcastPort'])) {
$input['mcastPort'] = $scriptParameters['mcastPort'];
}
if (isset($scriptParameters['mcastIp'])) {
$input['mcastIp'] = $scriptParameters['mcastIp'];
}
if (isset($scriptParameters['maxClients'])) {
$input['maxClients'] = $scriptParameters['maxClients'];
}
if (isset($scriptParameters['maxTime'])) {
$input['maxTime'] = $scriptParameters['maxTime'];
}
if (isset($scriptParameters['p2pMode'])) {
$input['p2pMode'] = $scriptParameters['p2pMode'];
}
if (isset($scriptParameters['p2pTime'])) {
$input['p2pTime'] = $scriptParameters['p2pTime'];
}
$trace->setInput($input);
break;
case 'create-image':
$trace->setCommand(CommandTypes::CREATE_IMAGE);
$trace->setInput([
'type' => $scriptParameters['type'],
'imageName' => $scriptParameters['imageName'],
'imageUuid' => $scriptParameters['imageUuid'] ?? null,
'diskNumber' => $scriptParameters['diskNumber'] ?? null,
'partitionNumber' => $scriptParameters['partitionNumber'] ?? null,
'gitRepositoryName' => $scriptParameters['gitRepositoryName'] ?? null,
'action' => $scriptParameters['action'] ?? 'create'
]);
break;
case 'partition-assistant':
$trace->setCommand(CommandTypes::PARTITION_AND_FORMAT);
$trace->setInput($scriptParameters);
break;
case 'power-on':
$trace->setCommand(CommandTypes::POWER_ON);
$trace->setInput($scriptParameters ?? []);
break;
case 'reboot':
$trace->setCommand(CommandTypes::REBOOT);
$trace->setInput($scriptParameters ?? []);
break;
case 'shutdown':
$trace->setCommand(CommandTypes::SHUTDOWN);
$trace->setInput($scriptParameters ?? []);
break;
case 'login':
$trace->setCommand(CommandTypes::LOGIN);
$trace->setInput($scriptParameters ?? []);
break;
default:
$output->writeln(" - Tipo de script no soportado: {$script->getType()}");
continue 2;
}
$this->entityManager->persist($trace);
$output->writeln(" - Traza creada para cliente {$client->getUuid()} con comando {$trace->getCommand()}");
}
}
private function executePartitionAssistant($script, CommandTask $task, OutputInterface $output): void
{
$scriptParameters = $script->getParameters();

View File

@ -86,8 +86,6 @@ class AssetManagerController extends AbstractController {
if (!$file) {
$response = new JsonResponse(['message' => 'No file uploaded.'], Response::HTTP_BAD_REQUEST);
} elseif (!$file->isValid()) {
$response = new JsonResponse(['message' => 'Error en la subida: ' . $file->getErrorMessage()], Response::HTTP_BAD_REQUEST);
} else {
$targetDir = $this->getSecureTargetPath($params->get('kernel.project_dir'), $requestedPath);
@ -110,25 +108,13 @@ class AssetManagerController extends AbstractController {
$filesystem->mkdir($extractDir, 0755);
}
if (!class_exists('ZipArchive')) {
$response = new JsonResponse(['message' => 'Falta la extensión php-zip en el servidor.'], Response::HTTP_INTERNAL_SERVER_ERROR);
$zip = new ZipArchive();
if ($zip->open($file->getPathname()) === true) {
$zip->extractTo($extractDir);
$zip->close();
$response = new JsonResponse(['message' => 'ZIP extraído correctamente.']);
} else {
try {
$zip = new ZipArchive();
if ($zip->open($file->getPathname()) === true) {
$success = $zip->extractTo($extractDir);
$zip->close();
if ($success) {
$response = new JsonResponse(['message' => 'ZIP extraído correctamente.']);
} else {
$response = new JsonResponse(['message' => 'Falló la extracción (posible falta de permisos).'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
$response = new JsonResponse(['message' => 'Error al abrir el ZIP.'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} catch (\Throwable $e) {
$response = new JsonResponse(['message' => 'Excepción al extraer: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
}
$response = new JsonResponse(['message' => 'Error al extraer ZIP.'], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
try {

View File

@ -5,9 +5,7 @@ namespace App\Controller;
use App\Dto\Input\CancelMultipleTracesInput;
use App\Entity\Trace;
use App\Model\TraceStatus;
use App\Service\Trace\KillJobService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
@ -16,45 +14,22 @@ class CancelMultipleTracesAction extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly KillJobService $killJobService,
private readonly LoggerInterface $logger,
)
{
}
public function __invoke(CancelMultipleTracesInput $input): JsonResponse
{
$cancelled = [];
$failed = [];
foreach ($input->traces as $traceOutput) {
foreach ($input->traces as $trace) {
/** @var Trace $trace */
$trace = $traceOutput->getEntity();
$trace = $trace->getEntity();
try {
if ($trace->getStatus() === TraceStatus::IN_PROGRESS) {
$this->killJobService->kill($trace, (string) $trace->getJobId());
} elseif ($trace->getStatus() === TraceStatus::PENDING) {
$trace->setStatus(TraceStatus::CANCELLED);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
} else {
$failed[] = ['trace' => $trace->getUuid(), 'reason' => 'not cancellable'];
continue;
}
$cancelled[] = $trace->getUuid();
} catch (\Throwable $e) {
$this->logger->error(sprintf('Error cancelling trace %s: %s', $trace->getUuid(), $e->getMessage()));
$failed[] = ['trace' => $trace->getUuid(), 'reason' => $e->getMessage()];
}
$trace->setStatus(TraceStatus::CANCELLED);
$this->entityManager->persist($trace);
}
$this->entityManager->flush();
return new JsonResponse(
data: ['cancelled' => $cancelled, 'failed' => $failed],
status: Response::HTTP_OK
);
return new JsonResponse(data: 'Traces cancelled successfully', status: Response::HTTP_OK);
}
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace App\Controller;
use App\Dto\Input\CommandTaskExecuteInput;
use App\Entity\CommandTask;
use App\Service\CommandTaskTraceCreator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class CommandTaskExecuteAction extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly CommandTaskTraceCreator $commandTaskTraceCreator,
)
{
}
public function __invoke(CommandTaskExecuteInput $input, CommandTask $commandTask): JsonResponse
{
$clients = array_map(fn($client) => $client->getEntity(), $input->clients);
$this->commandTaskTraceCreator->createPendingTraces($commandTask, $clients);
$this->entityManager->flush();
return new JsonResponse(data: 'Command task executed successfully', status: Response::HTTP_OK);
}
}

View File

@ -28,8 +28,6 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class DeployImageAction extends AbstractController
{
private const NO_REPOSITORY = '__no_repository__';
public function __construct(
protected readonly EntityManagerInterface $entityManager,
protected readonly HttpClientInterface $httpClient,
@ -89,209 +87,160 @@ class DeployImageAction extends AbstractController
private function handleUnicastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
{
return $this->processDeployments($input, $image, [], 'unicast', $trace);
}
private function handleMulticastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
{
$repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'multicast');
return $this->processDeployments($input, $image, $repositoryErrors, 'multicast', $trace);
}
private function handleTorrentDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
{
$repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'torrent');
return $this->processDeployments($input, $image, $repositoryErrors, 'torrent', $trace);
}
/**
* Reparte la orden de despliegue entre todos los equipos en dos fases: primero se lanzan todas
* las peticiones a los ogAgent (que viajan en paralelo, porque el HttpClient de Symfony no
* bloquea hasta que se lee la respuesta) y después se recogen los resultados.
*
* Antes se hacía equipo por equipo, así que el tiempo total era la suma de todos y cada equipo
* apagado se comía su timeout completo antes de pasar al siguiente.
*
* @param array<string, string> $repositoryErrors error de transmisión por clave de repositorio
*/
private function processDeployments(
DeployImageInput $input,
ImageImageRepository $image,
array $repositoryErrors,
string $methodLabel,
?Trace $trace = null
): array {
$clientJobs = [];
$pending = [];
// Fase 1: lanzar la orden a todos los ogAgent sin esperar su respuesta.
foreach ($input->clients as $clientOutput) {
$client = $clientOutput->getEntity();
$inputData = $this->createInputDataForMethod($input, $image, $client);
$repositoryError = $repositoryErrors[$this->getRepositoryKey($client)] ?? null;
if ($this->deployImageOgAgentAction->isClientOffline($client)) {
$this->logger->info(sprintf('Client is offline, queueing deployment directly (%s)', $methodLabel), [
'client_uuid' => $client->getUuid()
]);
$this->queueDeployment($client, $input, $inputData);
continue;
}
if ($repositoryError !== null) {
$this->logger->warning(sprintf('Error with OgRepository for client (%s)', $methodLabel), [
'client_uuid' => $client->getUuid(),
'error' => $repositoryError
]);
$this->queueDeployment($client, $input, $inputData);
continue;
}
foreach ($input->clients as $client) {
try {
$pending[] = [
'client' => $client,
'inputData' => $inputData,
'response' => $this->deployImageOgAgentAction->startDeploy($image, $input, $client),
];
$inputData = $this->createInputData($input, $image, $client->getEntity());
$jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::UNICAST, $trace);
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
}
} catch (\Exception $e) {
$this->logger->warning(sprintf('Error deploying to client (%s)', $methodLabel), [
'client_uuid' => $client->getUuid(),
$this->logger->warning('Error deploying to client (unicast)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
$this->queueDeployment($client, $input, $inputData);
}
}
// Fase 2: recoger las respuestas, que han ido avanzando en paralelo.
foreach ($pending as ['client' => $client, 'inputData' => $inputData, 'response' => $response]) {
try {
$jobId = $this->deployImageOgAgentAction->completeDeploy($response, $client);
} catch (\Exception $e) {
$this->logger->warning(sprintf('Error deploying to client (%s)', $methodLabel), [
'client_uuid' => $client->getUuid(),
'error' => $e->getMessage()
]);
$this->queueDeployment($client, $input, $inputData);
if ($input->queue) {
$inputData = $this->createInputData($input, $image, $client->getEntity());
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
continue;
}
$this->registerDeployment($client, $input, $inputData, $jobId, $trace);
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getUuid()] = $jobId;
}
}
return $clientJobs;
}
/** Deja el despliegue en cola para que lo reintente ExecutePendingTracesCommand. */
private function queueDeployment($client, DeployImageInput $input, array $inputData): void
private function handleMulticastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
{
if (!$input->queue) {
return;
$clientJobs = [];
foreach ($input->clients as $client) {
try {
$inputData = $this->createMulticastInputData($input, $image, $client->getEntity());
try {
$this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity());
} catch (\Exception $e) {
$this->logger->warning('Error with OgRepository for client (multicast)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
if ($input->queue) {
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
continue;
}
$jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::MULTICAST, $trace);
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
}
} catch (\Exception $e) {
$this->logger->warning('Error deploying to client (multicast)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
if ($input->queue) {
$inputData = $this->createMulticastInputData($input, $image, $client->getEntity());
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
continue;
}
}
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
return $clientJobs;
}
/** Anota la traza del despliegue: en curso si el ogAgent aceptó la orden, en cola si no. */
private function registerDeployment($client, DeployImageInput $input, array $inputData, ?string $jobId, ?Trace $trace = null): void
private function handleTorrentDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
{
if (!$jobId) {
if (!$input->queue) {
return;
}
$clientJobs = [];
if ($trace) {
$trace->setStatus(TraceStatus::PENDING);
$trace->setJobId(null);
$trace->setInput($inputData);
$this->entityManager->persist($trace);
$this->entityManager->flush();
} else {
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
foreach ($input->clients as $client) {
try {
$inputData = $this->createTorrentInputData($input, $image, $client->getEntity());
try {
$response = $this->deployImageOgRepositoryAction->__invoke($input, $image, $client->getEntity(), $this->httpClient);
if (is_array($response) && isset($response['code']) && $response['code'] === 500) {
throw new \Exception('Error del servidor OgRepository: ' . ($response['error'] ?? 'Error desconocido') . ' - ' . ($response['details'] ?? ''));
}
} catch (\Exception $e) {
$this->logger->warning('Error with OgRepository for client (torrent)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
if ($input->queue) {
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
continue;
}
return;
$jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::TORRENT, $trace);
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
}
} catch (\Exception $e) {
$this->logger->warning('Error deploying to client (torrent)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
if ($input->queue) {
$inputData = $this->createTorrentInputData($input, $image, $client->getEntity());
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
continue;
}
}
return $clientJobs;
}
private function processDeployment($client, DeployImageInput $input, ImageImageRepository $image, array $inputData, string $deployType, ?Trace $trace = null): ?string
{
$agentJobId = $this->deployImageOgAgentAction->__invoke($image, $input, $client, $deployType);
if (!$agentJobId) {
if ($input->queue) {
if ($trace) {
$trace->setStatus(TraceStatus::PENDING);
$trace->setJobId(null);
$trace->setInput($inputData);
$this->entityManager->persist($trace);
$this->entityManager->flush();
} else {
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
}
return null;
}
if ($trace) {
$trace->setStatus(TraceStatus::IN_PROGRESS);
$trace->setJobId($jobId);
$trace->setJobId($agentJobId);
$trace->setInput($inputData);
$this->entityManager->persist($trace);
$this->entityManager->flush();
} else {
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $jobId, $inputData);
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $agentJobId, $inputData);
}
}
private function createInputDataForMethod(DeployImageInput $input, ImageImageRepository $image, $client): array
{
return match ($input->method) {
DeployMethodTypes::MULTICAST, DeployMethodTypes::MULTICAST_UFTP, DeployMethodTypes::MULTICAST_UFTP_DIRECT,
DeployMethodTypes::MULTICAST_UDPCAST, DeployMethodTypes::MULTICAST_UDPCAST_DIRECT => $this->createMulticastInputData($input, $image, $client),
DeployMethodTypes::TORRENT => $this->createTorrentInputData($input, $image, $client),
default => $this->createInputData($input, $image, $client),
};
}
/**
* La transmisión (multicast/torrent) se levanta en el ogRepository una sola vez, no por cliente.
* Como cada cliente puede resolver a un repositorio distinto, se agrupan por repositorio y se
* lanza una única petición por repositorio implicado.
*
* @return array<string, string> error por clave de repositorio; sin entrada = transmisión creada
*/
private function prepareRepositoryTransmissions(DeployImageInput $input, ImageImageRepository $image, string $methodLabel): array
{
$clientsByRepository = [];
foreach ($input->clients as $client) {
$clientsByRepository[$this->getRepositoryKey($client->getEntity())][] = $client;
}
$errors = [];
foreach ($clientsByRepository as $repositoryKey => $clients) {
if ($repositoryKey === self::NO_REPOSITORY) {
$errors[$repositoryKey] = 'Client has no repository assigned';
continue;
}
try {
$this->deployImageOgRepositoryAction->__invoke($input, $image, $clients[0]->getEntity());
} catch (\Exception $e) {
$errors[$repositoryKey] = $e->getMessage();
$this->logger->warning('Error creating transmission in OgRepository', [
'method' => $methodLabel,
'repository' => $repositoryKey,
'affected_clients' => count($clients),
'error' => $e->getMessage()
]);
}
}
return $errors;
}
private function getRepositoryKey($client): string
{
$repository = $client->getRepository();
return $repository ? (string) $repository->getUuid() : self::NO_REPOSITORY;
return $agentJobId;
}
private function createInputData(DeployImageInput $input, ImageImageRepository $image, $client): array

View File

@ -1,198 +0,0 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use OpenApi\Attributes as OA;
#[Route('/migration/import', name: 'api_migration_import')]
#[IsGranted('ROLE_SUPER_ADMIN')]
class ImportLegacyDbController extends AbstractController
{
#[Route('', methods: ['POST'])]
#[OA\Post(
summary: "Import legacy OpenGnsys 1.1 database",
description: "Imports data from an OG 1.1 database. It accepts either a .sql file upload via multipart/form-data or database credentials via JSON.",
responses: [
new OA\Response(response: 200, description: "Import completed successfully"),
new OA\Response(response: 400, description: "Invalid input or import failure"),
new OA\Response(response: 500, description: "Server error during import")
]
)]
public function __invoke(Request $request, KernelInterface $kernel): JsonResponse
{
// Set no time limit for this specific long-running controller
set_time_limit(0);
$inputArgs = ['command' => 'opengnsys:import-legacy'];
$tempFiles = [];
// Check if we received a file upload
$file = $request->files->get('sql_file');
if ($file) {
$extension = strtolower($file->getClientOriginalExtension());
if (!in_array($extension, ['sql', 'zip'])) {
return new JsonResponse(['error' => 'Uploaded file must be a .sql or .zip file'], 400);
}
$uploadDir = sys_get_temp_dir();
if ($extension === 'zip') {
$zipPath = $uploadDir . DIRECTORY_SEPARATOR . uniqid('legacy_import_', true) . '.zip';
$file->move($uploadDir, basename($zipPath));
$tempFiles[] = $zipPath;
$zip = new \ZipArchive();
if ($zip->open($zipPath) === true) {
$sqlFileName = null;
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
if (pathinfo($stat['name'], PATHINFO_EXTENSION) === 'sql') {
$sqlFileName = $stat['name'];
break;
}
}
if ($sqlFileName) {
$zip->extractTo($uploadDir, $sqlFileName);
$filePath = $uploadDir . DIRECTORY_SEPARATOR . $sqlFileName;
$tempFiles[] = $filePath;
$zip->close();
} else {
$zip->close();
foreach ($tempFiles as $f) { if (file_exists($f)) unlink($f); }
return new JsonResponse(['error' => 'No .sql file found inside the uploaded ZIP archive'], 400);
}
} else {
foreach ($tempFiles as $f) { if (file_exists($f)) unlink($f); }
return new JsonResponse(['error' => 'Failed to open the uploaded ZIP archive'], 500);
}
} else {
$fileName = uniqid('legacy_import_', true) . '.sql';
$file->move($uploadDir, $fileName);
$filePath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
$tempFiles[] = $filePath;
}
$inputArgs['--file'] = $filePath;
} else {
// Check for JSON payload with DB credentials
$data = json_decode($request->getContent(), true);
if (!$data || !isset($data['legacyHost']) || !isset($data['legacyUser']) || !isset($data['legacyDb'])) {
return new JsonResponse([
'error' => 'You must provide either an "sql_file" or a JSON payload with legacyHost, legacyUser, and legacyDb'
], 400);
}
$inputArgs['--legacy-host'] = $data['legacyHost'];
$inputArgs['--legacy-user'] = $data['legacyUser'];
if (!empty($data['legacyPassword'])) {
$inputArgs['--legacy-password'] = $data['legacyPassword'];
}
$inputArgs['--legacy-db'] = $data['legacyDb'];
}
try {
$logFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'opengnsys_migration_latest.log';
$pidFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'opengnsys_migration.pid';
// Check if already running
if (file_exists($pidFile)) {
$existingPid = trim(file_get_contents($pidFile));
if (file_exists('/proc/' . $existingPid)) {
return new JsonResponse(['error' => 'Ya hay una migración en curso. Por favor, espera a que termine.'], 409);
} else {
@unlink($pidFile); // Cleanup orphaned PID
}
}
$consolePath = $kernel->getProjectDir() . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . 'console';
if (!file_exists($consolePath)) {
return new JsonResponse(['error' => 'System error: bin/console not found.'], 500);
}
$commandArray = ['php', escapeshellarg($consolePath), 'opengnsys:import-legacy'];
foreach ($inputArgs as $key => $value) {
if ($key !== 'command') {
$commandArray[] = $key . '=' . escapeshellarg($value);
}
}
// Add cleanup files
foreach ($tempFiles as $f) {
$commandArray[] = '--cleanup-file=' . escapeshellarg($f);
}
// Log file for Mercure
$commandArray[] = '--log-file=' . escapeshellarg($logFile);
$commandArray[] = '--cleanup-file=' . escapeshellarg($logFile);
$commandArray[] = '--cleanup-file=' . escapeshellarg($pidFile); // Let command delete PID when done
$commandStr = implode(' ', $commandArray);
// Run detached OS process and get PID
exec("$commandStr > " . escapeshellarg($logFile) . " 2>&1 & echo $!", $output);
if (isset($output[0]) && is_numeric($output[0])) {
file_put_contents($pidFile, $output[0]);
}
return new JsonResponse([
'status' => 'started',
'message' => 'Migration started in background'
], 200);
} catch (\Exception $e) {
// Clean up the uploaded files in case of exception
foreach ($tempFiles as $f) {
if (file_exists($f)) {
unlink($f);
}
}
return new JsonResponse([
'error' => 'An error occurred while executing the migration process',
'details' => $e->getMessage()
], 500);
}
}
#[Route('/status', name: 'api_migration_status', methods: ['GET'])]
public function status(): JsonResponse
{
$pidFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'opengnsys_migration.pid';
$logFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'opengnsys_migration_latest.log';
$isRunning = false;
if (file_exists($pidFile)) {
$pid = trim(file_get_contents($pidFile));
if (file_exists('/proc/' . $pid)) {
$isRunning = true;
} else {
@unlink($pidFile);
}
}
$log = '';
if (file_exists($logFile)) {
$log = file_get_contents($logFile);
}
return new JsonResponse([
'isRunning' => $isRunning,
'log' => $log
]);
}
}

View File

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace App\Controller;
use App\Entity\Client;
use App\Entity\Menu;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
@ -28,6 +27,8 @@ class MenuBrowserController extends AbstractController
{
$host = $request->getClientIp();
$partitions = [];
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $host]);
$disks = []; // Array nuevo estructurado
@ -67,74 +68,15 @@ class MenuBrowserController extends AbstractController
}
}
$menu = $this->resolveMenu($client);
$menuName = $client->getMenu()->getPublicUrl();
$rawPublicUrl = $menu?->getPublicUrl() ?? 'main';
$menuName = preg_replace('#^/menu/#', '', parse_url($rawPublicUrl, PHP_URL_PATH) ?? $rawPublicUrl);
if (empty($menuName)) {
$menuName = 'main';
}
$templatePath = 'browser/' . $menuName . '.html.twig';
if (!$this->twig->getLoader()->exists($templatePath)) {
$templatePath = 'browser/main.html.twig';
}
return $this->render($templatePath, [
return $this->render('browser/' . $menuName . '.html.twig', [
'ip' => $host,
'mac' => $client ? $client->getMac() : null,
'disks' => $disks,
]);
}
private function resolveMenu(?Client $client): ?Menu
{
if (!$client) {
return $this->getDefaultOrFirstMenu();
}
if ($client->getMenu()) {
return $client->getMenu();
}
// 1. Buscar en la jerarquía de Unidades Organizativas (de hijo a padre)
$currentOu = $client->getOrganizationalUnit();
while ($currentOu !== null) {
if ($currentOu->getNetworkSettings() && $currentOu->getNetworkSettings()->getMenu()) {
$menu = $currentOu->getNetworkSettings()->getMenu();
$this->assignAndPersistMenu($client, $menu);
return $menu;
}
$currentOu = $currentOu->getParent();
}
// 2. Buscar el menú por defecto o el primer menú disponible
$menu = $this->getDefaultOrFirstMenu();
if ($menu) {
$this->assignAndPersistMenu($client, $menu);
return $menu;
}
return null;
}
private function getDefaultOrFirstMenu(): ?Menu
{
return $this->entityManager->getRepository(Menu::class)->findOneBy(['isDefault' => true])
?? $this->entityManager->getRepository(Menu::class)->findOneBy([]);
}
private function assignAndPersistMenu(Client $client, Menu $menu): void
{
$client->setMenu($menu);
if (!$client->getResolution() && $menu->getResolution()) {
$client->setResolution($menu->getResolution());
}
$this->entityManager->persist($client);
$this->entityManager->flush();
}
#[Route('/menu/{templateName}', name: 'render_menu_template', requirements: ['templateName' => '.+'])]
public function renderMenu(string $templateName, Request $request): Response
{
@ -144,18 +86,10 @@ class MenuBrowserController extends AbstractController
throw $this->createNotFoundException(sprintf('La plantilla "%s" no existe.', $templateName));
}
$html = $this->renderView($templatePath, [
return $this->render($templatePath, [
'ip' => 'invitado',
'disks' => [],
]);
if ($request->query->get('gui')) {
$base = rtrim($request->query->get('baseUrl') ?: ($request->getSchemeAndHttpHost() . $request->getBasePath()), '/');
// Rewrite both assets/ and /assets/ to the absolute API URL
$html = preg_replace('#([\'"(])/?assets/#i', '$1' . $base . '/assets/', $html);
}
return new Response($html);
}
#[Route('/menu-raw/{templateName}', name: 'get_raw_menu_template', requirements: ['templateName' => '.+'], methods: ['GET'])]
@ -194,10 +128,6 @@ class MenuBrowserController extends AbstractController
'mac' => '00:00:00:00:00:00',
'disks' => [],
]);
// Rewrite both assets/ and /assets/ to the absolute API URL
$base = rtrim($data['baseUrl'] ?? ($request->getSchemeAndHttpHost() . $request->getBasePath()), '/');
$rendered = preg_replace('#([\'"(])/?assets/#i', '$1' . $base . '/assets/', $rendered);
return new Response($rendered, Response::HTTP_OK, ['Content-Type' => 'text/html; charset=utf-8']);
} catch (\Exception $e) {
return new JsonResponse(['message' => 'Error al compilar la plantilla Twig: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);

View File

@ -4,8 +4,6 @@ namespace App\Controller\OgAgent;
use App\Controller\OgRepository\Git\CreateRepositoryAction;
use App\Controller\OgRepository\Git\SshKeyAction;
use App\Entity\Client;
use App\Model\ClientStatus;
use App\Service\CreatePartitionService;
use App\Service\Trace\CreateService;
use Doctrine\ORM\EntityManagerInterface;
@ -19,7 +17,6 @@ use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
#[AsController]
abstract class AbstractOgAgentController extends AbstractController
@ -38,41 +35,18 @@ abstract class AbstractOgAgentController extends AbstractController
{
}
public function isClientOffline(?Client $client): bool
{
if ($client === null) {
return true;
}
return in_array($client->getStatus(), [
ClientStatus::OFF,
ClientStatus::DISCONNECTED,
ClientStatus::TURNING_OFF,
], true);
}
protected function buildRequestOptions(array $params = [], ?string $token = null): array
{
$defaultHeaders = [
'accept' => 'application/json',
'Content-Type' => 'application/json',
];
if ($token !== null) {
$defaultHeaders['Authorization'] = $token;
}
$defaultOptions = [
'headers' => $defaultHeaders,
$options = array_merge($params, [
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => $token,
],
'verify_peer' => false,
'verify_host' => false,
'timeout' => 10,
];
$options = array_merge($defaultOptions, $params);
if (isset($params['headers'])) {
$options['headers'] = array_merge($defaultHeaders, $params['headers']);
}
]);
if ($this->sslEnabled === 'true') {
$options['verify_peer'] = true;
@ -85,13 +59,6 @@ abstract class AbstractOgAgentController extends AbstractController
return $options;
}
public function sendAsyncRequest(string $method, string $url, array $params = [], ?string $token = null): ResponseInterface
{
$options = $this->buildRequestOptions($params, $token);
return $this->httpClient->request($method, $url, $options);
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
@ -104,26 +71,6 @@ abstract class AbstractOgAgentController extends AbstractController
try {
$response = $this->httpClient->request($method, $url, $params);
} catch (TransportExceptionInterface $e) {
$this->logger->error(sprintf('Transport error in request to %s: %s', $url, $e->getMessage()));
return [
'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
'error' => 'Transport error',
'details' => $e->getMessage(),
];
}
return $this->readResponse($response, $url);
}
/**
* Interpreta la respuesta del ogAgent. Está separado de createRequest() para poder lanzar
* varias peticiones a la vez y leerlas después, en vez de esperar a cada una por turno.
*/
public function readResponse(ResponseInterface $response, string $url): array
{
try {
return json_decode($response->getContent(), true);
} catch (ClientExceptionInterface | ServerExceptionInterface $e) {
if ($e->getResponse() && $e->getResponse()->getStatusCode() === 409) {

View File

@ -63,10 +63,8 @@ class CreateImageAction extends AbstractOgAgentController
$partitionInfo = json_decode($image->getPartitionInfo(), true);
}
$effectiveClient = $client ?? $image->getClient();
if ($image->getType() === 'monolithic') {
$repository = $effectiveClient->getRepository();
$repository = $image->getClient()->getRepository();
$latestImageRepo = $this->entityManager->getRepository(ImageImageRepository::class)->findLatestVersionByImageAndRepository($image, $repository);
$imageImageRepository = new ImageImageRepository();
@ -79,11 +77,11 @@ class CreateImageAction extends AbstractOgAgentController
$this->entityManager->persist($imageImageRepository);
return $this->createMonolithicImage($imageImageRepository, $partitionInfo, $image, $repository, $effectiveClient, $queue, $existingTrace);
return $this->createMonolithicImage($imageImageRepository, $partitionInfo, $image, $repository, $client, $queue, $existingTrace);
} else {
$repository = $effectiveClient->getRepository();
$repository = $image->getClient()->getRepository();
return $this->createGitImage($image, $partitionInfo, $repository, $effectiveClient, $queue, $gitRepositoryName, $existingTrace);
return $this->createGitImage($image, $partitionInfo, $repository, $queue, $gitRepositoryName, $existingTrace);
}
}
@ -206,7 +204,7 @@ class CreateImageAction extends AbstractOgAgentController
$this->entityManager->flush();
} else {
$this->createService->__invoke(
$client,
$image->getClient(),
CommandTypes::CREATE_IMAGE,
TraceStatus::IN_PROGRESS,
$jobId,
@ -239,7 +237,6 @@ class CreateImageAction extends AbstractOgAgentController
Image $image,
array $partitionInfo,
ImageRepository $repository,
?Client $client = null,
bool $queue = false,
?string $gitRepositoryName = null,
?Trace $existingTrace = null
@ -249,7 +246,7 @@ class CreateImageAction extends AbstractOgAgentController
throw new BadRequestHttpException('Missing required partition information');
}
$client = $client ?? $image->getClient();
$client = $image->getClient();
if (!$client->getIp() || !$client->getToken()) {
throw new BadRequestHttpException('Client IP or token is missing');
}

View File

@ -14,8 +14,7 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
class DeployImageAction extends AbstractOgAgentController
{
@ -26,22 +25,6 @@ class DeployImageAction extends AbstractOgAgentController
* @throws ServerExceptionInterface
*/
public function __invoke(ImageImageRepository $imageImageRepository, DeployImageInput $input, Client $client, ?string $method = null)
{
return $this->completeDeploy(
$this->startDeploy($imageImageRepository, $input, $client),
$client
);
}
/**
* Envía la orden al ogAgent sin esperar la respuesta. El HttpClient de Symfony gestiona las
* peticiones de forma concurrente mientras no se lea su contenido, así que lanzando primero
* todas las de un despliegue el coste total pasa de ser la suma de todos los equipos a ser
* el del equipo más lento.
*
* @throws TransportExceptionInterface
*/
public function startDeploy(ImageImageRepository $imageImageRepository, DeployImageInput $input, Client $client): ResponseInterface
{
$image = $imageImageRepository->getImage();
@ -94,32 +77,26 @@ class DeployImageAction extends AbstractOgAgentController
$url = 'https://'.$client->getIp().':8000/opengnsys/RestaurarImagen';
$this->logger->info('Deploying image', [
'image' => $imageImageRepository->getName(),
$response = $this->createRequest(
method: 'POST',
url: $url,
params: [
'json' => $data,
],
token: $client->getToken(),
);
$this->logger->info('Deploying image', [
'image' => $imageImageRepository->getName(),
'repository' => $repository->getIp(),
'client' => $client->getIp()
]);
return $this->httpClient->request(
method: 'POST',
url: $url,
options: $this->buildRequestOptions(['json' => $data], $client->getToken()),
);
}
/**
* Lee la respuesta de un ogAgent y devuelve su job_id, o null si el equipo no ha aceptado la
* orden (por ejemplo un 409 porque ya está ocupado).
*/
public function completeDeploy(ResponseInterface $response, Client $client): ?string
{
$content = $this->readResponse($response, (string) $response->getInfo('url'));
if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
throw new BadRequestHttpException('Error deploying image');
}
$jobId = $content['job_id'] ?? null;
$jobId = $response['job_id'];
$client->setStatus(ClientStatus::BUSY);
$this->entityManager->persist($client);

View File

@ -167,25 +167,20 @@ class HardwareInventoryAction extends AbstractOgAgentController
$hardwareProfile = $client->getHardwareProfile();
$isNewProfile = false;
$isSharedProfile = $hardwareProfile !== null && $hardwareProfile->getClients()->count() > 1;
if (!$hardwareProfile) {
$hardwareProfile = new HardwareProfile();
$hardwareProfile->setDescription('Perfil de hardware generado automáticamente para ' . $client->getIp());
$hardwareProfile->setClient($client);
$this->entityManager->persist($hardwareProfile);
$isNewProfile = true;
$this->logger->info('Nuevo perfil de hardware creado', [
'client' => $client->getId(),
'client_ip' => $client->getIp()
]);
$client->setHardwareProfile($hardwareProfile);
} elseif ($isSharedProfile) {
$this->logger->info('Perfil de hardware compartido con otros clientes del aula, no se sobrescribe con el inventario individual', [
'client' => $client->getId(),
'profile_id' => $hardwareProfile->getId()
]);
} else {
$this->logger->info('Actualizando perfil de hardware existente', [
'client' => $client->getId(),
@ -193,17 +188,16 @@ class HardwareInventoryAction extends AbstractOgAgentController
]);
}
if (!$isSharedProfile) {
foreach ($hardwareItems as $hardware) {
$hardwareProfile->addHardwareCollection($hardware);
}
$this->logger->debug('Nuevo hardware añadido al perfil', [
'client' => $client->getId(),
'added_hardware_count' => count($hardwareItems)
]);
foreach ($hardwareItems as $hardware) {
$hardwareProfile->addHardwareCollection($hardware);
}
$this->logger->debug('Nuevo hardware añadido al perfil', [
'client' => $client->getId(),
'added_hardware_count' => count($hardwareItems)
]);
$client->setHardwareProfile($hardwareProfile);
$this->entityManager->persist($client);
$this->entityManager->flush();

View File

@ -6,27 +6,66 @@ namespace App\Controller\OgAgent;
use App\Dto\Input\KillJobInput;
use App\Entity\Trace;
use App\Service\Trace\KillJobService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Model\ClientStatus;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use App\Service\Trace\CreateService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
#[AsController]
class KillJobAction extends AbstractController
class KillJobAction extends AbstractOgAgentController
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly KillJobService $killJobService,
) {
}
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __invoke(Trace $trace, KillJobInput $input): JsonResponse
{
$this->killJobService->kill($trace, $input->jobId);
$client = $trace->getClient();
if (!$client->getIp()) {
throw new BadRequestHttpException('IP is required');
}
$data = [
'job_id' => $input->jobId
];
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/opengnsys/KillJob',
params: [
'json' => $data,
],
token: $client->getToken(),
);
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
throw new BadRequestHttpException('Error killing job: '.$response['error']);
}
$this->logger->info('Killing job', ['client' => $client->getId(), 'job_id' => $input->jobId]);
$trace->setStatus(TraceStatus::CANCELLED);
$this->entityManager->persist($trace);
$this->entityManager->flush();
$inputData = [
'job_id' => $input->jobId,
'client' => $client->getId(),
'trace' => $trace->getUuid(),
'command' => $trace->getCommand(),
];
//$this->createService->__invoke($client, CommandTypes::KILL_JOB, TraceStatus::CANCELLED, $input->jobId, $inputData);
return new JsonResponse(data: $trace, status: Response::HTTP_OK);
}
}

View File

@ -47,8 +47,6 @@ class OrganizationalUnitStatusAction extends AbstractOgAgentController
}
$options = $this->buildRequestOptions(['json' => ['full-config' => false]]);
$options['timeout'] = 5.0;
$options['max_duration'] = 5.0;
$skippedStatuses = [
ClientStatus::DISCONNECTED,

View File

@ -79,24 +79,6 @@ class PartitionAssistantAction extends AbstractOgAgentController
];
}
// Detección temprana: si el equipo está offline y se solicita encolado, registrar traza PENDING sin esperar red
if ($this->isClientOffline($client)) {
if ($input->queue) {
foreach ($disks as $diskNumber => $diskInfo) {
$data = [];
if (!empty($diskInfo['diskData'])) {
$data[] = $diskInfo['diskData'];
}
$data = array_merge($data, $diskInfo['partitionData']);
$this->createService->__invoke($client, CommandTypes::PARTITION_AND_FORMAT, TraceStatus::PENDING, null, $data);
}
$this->logger->info('Partition assistant queued (PENDING) for offline client', ['client' => $client->getId()]);
}
continue;
}
$pending = [];
foreach ($disks as $diskNumber => $diskInfo) {
$data = [];
if (!empty($diskInfo['diskData'])) {
@ -110,36 +92,28 @@ class PartitionAssistantAction extends AbstractOgAgentController
"cfg" => $data,
"ids" => "0"
];
$url = 'https://' . $client->getIp() . ':8000/opengnsys/Configurar';
try {
$pending[] = [
'client' => $client,
'data' => $data,
'url' => $url,
'response' => $this->sendAsyncRequest('POST', $url, ['json' => $result], $client->getToken()),
];
} catch (\Exception $e) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::PARTITION_AND_FORMAT, TraceStatus::PENDING, null, $data);
}
}
}
foreach ($pending as $item) {
$response = $this->readResponse($item['response'], $item['url']);
$data = $item['data'];
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/opengnsys/Configurar',
params: [
'json' => $result,
],
token: $client->getToken(),
);
$this->logger->info('Partition assistant', ['client' => $client->getId()]);
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::PARTITION_AND_FORMAT, TraceStatus::PENDING, null, $data);
continue;
}
continue;
}
$jobId = $response['job_id'] ?? null;
$jobId = $response['job_id'];
$client->setStatus(ClientStatus::BUSY);
$this->entityManager->persist($client);
@ -154,9 +128,7 @@ class PartitionAssistantAction extends AbstractOgAgentController
$this->createService->__invoke($client, CommandTypes::PARTITION_AND_FORMAT, TraceStatus::IN_PROGRESS, $jobId, $data);
}
if ($jobId) {
$clientJobs['/clients/' . $client->getUuid()] = $jobId;
}
$clientJobs['/clients/' . $client->getUuid()] = $jobId;
}
}

View File

@ -39,8 +39,6 @@ class PowerOffAction extends AbstractOgAgentController
*/
public function __invoke(MultipleClientsInput $input): JsonResponse
{
$pending = [];
foreach ($input->clients as $clientEntity) {
/** @var Client $client */
$client = $clientEntity->getEntity();
@ -49,10 +47,7 @@ class PowerOffAction extends AbstractOgAgentController
throw new BadRequestHttpException('IP is required');
}
if ($this->isClientOffline($client)) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::SHUTDOWN, TraceStatus::PENDING, null, []);
}
if ($client->getStatus() === ClientStatus::OFF || $client->getStatus() === ClientStatus::TURNING_OFF || $client->getStatus() === ClientStatus::DISCONNECTED) {
continue;
}
@ -60,41 +55,30 @@ class PowerOffAction extends AbstractOgAgentController
'nfn' => 'Apagar',
'ids' => '0'
];
$url = 'https://' . $client->getIp() . ':8000/opengnsys/Apagar';
try {
$pending[] = [
'client' => $client,
'url' => $url,
'response' => $this->sendAsyncRequest('POST', $url, ['json' => $data], $client->getToken()),
];
} catch (\Exception $e) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::SHUTDOWN, TraceStatus::PENDING, null, []);
}
}
}
foreach ($pending as $item) {
$client = $item['client'];
$response = $this->readResponse($item['response'], $item['url']);
$isBusy = isset($response['code']) && $response['code'] === Response::HTTP_CONFLICT;
$isError = isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR;
if ($isBusy || $isError) {
if ($isError) {
$this->logger->error('Error powering off client', ['client' => $client->getId(), 'error' => $response['error']]);
}
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/opengnsys/Apagar',
params: [
'json' => $data,
],
token: $client->getToken(),
);
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
$this->logger->error('Error powering off client', ['client' => $client->getId(), 'error' => $response['error']]);
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::SHUTDOWN, TraceStatus::PENDING, null, []);
continue;
}
continue;
}
$this->logger->info('Powering off client', ['client' => $client->getId()]);
$jobId = $response['job_id'] ?? null;
$jobId = $response['job_id'];
$client->setStatus(ClientStatus::TURNING_OFF);
$this->entityManager->persist($client);

View File

@ -27,61 +27,41 @@ class RebootAction extends AbstractOgAgentController
*/
public function __invoke(MultipleClientsInput $input): JsonResponse
{
$pending = [];
foreach ($input->clients as $clientEntity) {
/** @var Client $client */
$client = $clientEntity->getEntity();
if (!$client->getIp()) {
throw new BadRequestHttpException('IP is required');
}
// Detección temprana: equipos apagados o desconectados
if ($this->isClientOffline($client)) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::REBOOT, TraceStatus::PENDING, null, []);
$this->logger->info('Reboot queued (PENDING) for offline client', ['client' => $client->getId()]);
}
continue;
}
$data = [
'nfn' => 'Reiniciar',
'ids' => '0'
];
$url = 'https://' . $client->getIp() . ':8000/opengnsys/Reiniciar';
try {
$pending[] = [
'client' => $client,
'url' => $url,
'response' => $this->sendAsyncRequest('POST', $url, ['json' => $data], $client->getToken()),
];
} catch (\Exception $e) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::REBOOT, TraceStatus::PENDING, null, []);
}
}
}
foreach ($pending as $item) {
$client = $item['client'];
$response = $this->readResponse($item['response'], $item['url']);
$isBusy = isset($response['code']) && $response['code'] === Response::HTTP_CONFLICT;
$isError = isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR;
if ($isBusy || $isError) {
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/opengnsys/Reiniciar',
params: [
'json' => $data,
],
token: $client->getToken(),
);
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::REBOOT, TraceStatus::PENDING, null, []);
continue;
}
continue;
}
$this->logger->info('Rebooting client', ['client' => $client->getId()]);
$jobId = $response['job_id'] ?? null;
$jobId = $response['job_id'];
$client->setStatus(ClientStatus::INITIALIZING);
$this->entityManager->persist($client);
@ -90,6 +70,6 @@ class RebootAction extends AbstractOgAgentController
$this->createService->__invoke($client, CommandTypes::REBOOT, TraceStatus::SUCCESS, $jobId, []);
}
return new JsonResponse(data: [], status: Response::HTTP_OK);
return new JsonResponse(data: $client, status: Response::HTTP_OK);
}
}

View File

@ -39,8 +39,6 @@ class RefreshAction extends AbstractOgAgentController
*/
public function __invoke(MultipleClientsInput $input): JsonResponse
{
$pending = [];
foreach ($input->clients as $clientEntity) {
/** @var Client $client */
$client = $clientEntity->getEntity();
@ -59,31 +57,24 @@ class RefreshAction extends AbstractOgAgentController
'nfn' => 'Actualizar',
'ids' => '0'
];
$url = 'https://' . $client->getIp() . ':8000/ogAdmClient/Actualizar';
try {
$pending[] = [
'client' => $client,
'url' => $url,
'response' => $this->sendAsyncRequest('POST', $url, ['json' => $data], $client->getToken()),
];
} catch (\Exception $e) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::REFRESH, TraceStatus::PENDING, null, []);
}
}
}
foreach ($pending as $item) {
$client = $item['client'];
$response = $this->readResponse($item['response'], $item['url']);
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/ogAdmClient/Actualizar',
params: [
'json' => $data,
],
token: $client->getToken(),
);
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
$this->logger->error('Error refreshing client', ['client' => $client->getId(), 'error' => $response['error']]);
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::REFRESH, TraceStatus::PENDING, null, []);
continue;
}
continue;
}
@ -91,6 +82,9 @@ class RefreshAction extends AbstractOgAgentController
$jobId = $response['job_id'] ?? null;
// We do not change the status here, it remains OG_LIVE
// $client->setStatus(ClientStatus::OG_LIVE);
$this->createService->__invoke($client, CommandTypes::REFRESH, TraceStatus::SUCCESS, $jobId, []);
}

View File

@ -42,7 +42,7 @@ class RemoveCacheImageAction extends AbstractOgAgentController
continue;
}
$script = 'ogMountCache && rm -r /opt/opengnsys/cache/opt/opengnsys/images/' . escapeshellarg($input->imageName) . '*';
$script = 'rm -r /opt/opengnsys/cache/opt/opengnsys/images/' . escapeshellarg($input->imageName) . '*';
$data = [
'nfn' => 'EjecutarScript',

View File

@ -27,7 +27,6 @@ class RunScriptAction extends AbstractOgAgentController
public function __invoke(CommandExecuteInput $input, ?Trace $existingTrace = null): JsonResponse
{
$clientJobs = [];
$pending = [];
/** @var Client $clientEntity */
foreach ($input->clients as $clientEntity) {
@ -38,112 +37,10 @@ class RunScriptAction extends AbstractOgAgentController
throw new BadRequestHttpException('IP is required');
}
$traceInput = ['script' => $input->script];
if ($input->targetOs) {
$traceInput['target_os'] = $input->targetOs;
}
// Detección temprana: si el equipo está apagado o desconectado, no esperar timeout de red
if ($this->isClientOffline($client)) {
if ($input->queue) {
$this->createService->__invoke(
$client,
CommandTypes::RUN_SCRIPT,
TraceStatus::PENDING,
null,
$traceInput
);
$this->logger->info('Script queued (PENDING) for offline client', [
'client_ip' => $client->getIp(),
'target_os' => $input->targetOs
]);
} else {
$this->logger->info('Script skipped for offline client (queue disabled)', [
'client_ip' => $client->getIp()
]);
}
continue;
}
// Si se especificó un SO destino y el equipo encendido no está en ese SO:
if ($input->targetOs && !$this->isClientMatchingTargetOs($client, $input->targetOs)) {
if ($input->queue) {
$this->createService->__invoke(
$client,
CommandTypes::RUN_SCRIPT,
TraceStatus::PENDING,
null,
$traceInput
);
$this->logger->info('Script queued (PENDING) because client is not in target OS', [
'client_ip' => $client->getIp(),
'client_status' => $client->getStatus(),
'target_os' => $input->targetOs
]);
} else {
$this->logger->info('Script skipped because client is not in target OS (queue disabled)', [
'client_ip' => $client->getIp(),
'client_status' => $client->getStatus(),
'target_os' => $input->targetOs
]);
}
continue;
}
// Para equipos encendidos, lanzar la petición asíncrona concurrente
$data = $this->buildRequestData($client, $input->script, $input->runAsAdmin);
$url = 'https://' . $client->getIp() . ':8000/opengnsys/EjecutarScript';
try {
$pending[] = [
'client' => $client,
'url' => $url,
'response' => $this->sendAsyncRequest('POST', $url, ['json' => $data], $client->getToken()),
];
} catch (\Exception $e) {
$this->handleError($client, $input, [
'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
'error' => $e->getMessage()
]);
}
}
// Fase 2: Recolectar las respuestas de los equipos que estaban en línea
foreach ($pending as $item) {
$client = $item['client'];
$url = $item['url'];
$response = $this->readResponse($item['response'], $url);
$response = $this->executeScript($client, $data);
if (isset($response['code']) && $response['code'] === 409) {
$busyTraceInput = ['script' => $input->script];
if ($input->targetOs) {
$busyTraceInput['target_os'] = $input->targetOs;
}
if ($input->queue) {
$this->createService->__invoke(
$client,
CommandTypes::RUN_SCRIPT,
TraceStatus::PENDING,
null,
$busyTraceInput
);
$this->logger->info('Trace queued (PENDING) due to 409 busy response', [
'client_ip' => $client->getIp(),
'target_os' => $input->targetOs
]);
} else {
$this->createService->__invoke(
$client,
CommandTypes::RUN_SCRIPT,
TraceStatus::BUSY,
null,
$busyTraceInput,
'Some job is already running, refusing to launch another one'
);
$this->logger->info('Trace created as busy due to 409 response', [
'client_ip' => $client->getIp()
]);
}
continue;
}
@ -152,10 +49,8 @@ class RunScriptAction extends AbstractOgAgentController
continue;
}
$jobId = $response['job_id'] ?? null;
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getUuid()] = $jobId;
}
$jobId = $response['job_id'];
$clientJobs[(string) '/clients/' . $client->getUuid()] = $jobId;
$this->handleSuccess($client, $input, $response, $existingTrace);
}
@ -163,33 +58,6 @@ class RunScriptAction extends AbstractOgAgentController
return new JsonResponse(data: $clientJobs, status: Response::HTTP_OK);
}
private function isClientMatchingTargetOs(Client $client, ?string $targetOs): bool
{
if (!$targetOs) {
return true;
}
$targets = array_map('trim', explode(',', strtolower($targetOs)));
$clientStatus = strtolower((string) $client->getStatus());
foreach ($targets as $target) {
if ($target === 'windows' && in_array($clientStatus, [ClientStatus::WINDOWS, ClientStatus::WINDOWS_SESSION], true)) {
return true;
}
if ($target === 'linux' && in_array($clientStatus, [ClientStatus::LINUX, ClientStatus::LINUX_SESSION], true)) {
return true;
}
if (($target === 'og-live' || $target === 'oglive') && $clientStatus === ClientStatus::OG_LIVE) {
return true;
}
if ($target === $clientStatus) {
return true;
}
}
return false;
}
private function buildRequestData(Client $client, string $script, bool $runAsAdmin = false): array
{
$scriptBase64 = base64_encode($script);
@ -218,6 +86,35 @@ class RunScriptAction extends AbstractOgAgentController
return $client->getStatus() === ClientStatus::LINUX_SESSION || $client->getStatus() === ClientStatus::WINDOWS_SESSION;
}
private function executeScript(Client $client, array $data): array
{
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/opengnsys/EjecutarScript',
params: [
'json' => $data,
],
token: $client->getToken(),
);
if (isset($response['code']) && $response['code'] === 409) {
$this->createService->__invoke(
$client,
CommandTypes::RUN_SCRIPT,
TraceStatus::BUSY,
null,
['script' => $data['script'] ?? $data['scp'] ?? ''],
'Some job is already running, refusing to launch another one'
);
$this->logger->info('Trace created as busy due to 409 response', [
'client_ip' => $client->getIp()
]);
}
return $response;
}
private function isErrorResponse(array $response): bool
{
return isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR;
@ -232,9 +129,6 @@ class RunScriptAction extends AbstractOgAgentController
if ($input->queue) {
$inputData = ['script' => $input->script];
if ($input->targetOs) {
$inputData['target_os'] = $input->targetOs;
}
$this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, TraceStatus::PENDING, null, $inputData);
}
}
@ -253,29 +147,17 @@ class RunScriptAction extends AbstractOgAgentController
$this->entityManager->persist($client);
$this->entityManager->flush();
// Check if START_SCRIPT webhook already created a trace for this job
$webhookTrace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $jobId]);
if ($webhookTrace) {
$webhookTrace->setInput($inputData);
$this->entityManager->persist($webhookTrace);
if ($existingTrace && $existingTrace->getId() !== $webhookTrace->getId()) {
$this->entityManager->remove($existingTrace);
}
$this->entityManager->flush();
if ($existingTrace) {
$this->updateExistingTrace($existingTrace, $jobId, $inputData, $client);
} else {
if ($existingTrace) {
$this->updateExistingTrace($existingTrace, $jobId, $inputData, $client);
} else {
$status = TraceStatus::IN_PROGRESS;
$this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, $status, $jobId, $inputData);
}
$status = ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) ? TraceStatus::SENT : TraceStatus::IN_PROGRESS;
$this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, $status, $jobId, $inputData);
}
}
private function updateExistingTrace(Trace $trace, string $jobId, array $inputData, Client $client): void
{
$status = TraceStatus::IN_PROGRESS;
$status = ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) ? TraceStatus::SENT : TraceStatus::IN_PROGRESS;
$trace->setStatus($status);
$trace->setJobId($jobId);
$this->entityManager->persist($trace);

View File

@ -20,7 +20,6 @@ use App\Model\SoftwareTypes;
use App\Model\TraceStatus;
use App\Service\CreatePartitionService;
use App\Service\Trace\CreateService;
use App\Service\PendingTraceExecutionService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@ -57,7 +56,6 @@ class StatusController extends AbstractController
protected readonly LoggerInterface $logger,
protected readonly CreateService $createService,
protected readonly HttpClientInterface $httpClient,
protected readonly PendingTraceExecutionService $pendingTraceExecutionService,
)
{
}
@ -83,58 +81,47 @@ class StatusController extends AbstractController
}
$client->setUpdatedAt(new \DateTime());
if (isset($data['busy'])) {
$previousStatus = $client->getStatus();
$protectedStatuses = [ClientStatus::INITIALIZING, ClientStatus::TURNING_OFF];
if (in_array($previousStatus, $protectedStatuses)) {
$this->logger->info('Heartbeat ignored because client is in a protected transitional state', [
'ip' => $data['iph'], 'current_status' => $previousStatus, 'busy' => $data['busy'], 'st' => $data['st'] ?? null,
]);
} else {
if ($data['busy'] === true) {
$client->setStatus(ClientStatus::BUSY);
$this->logger->info('Heartbeat: client marked as busy', [
'ip' => $data['iph'], 'previous_status' => $previousStatus, 'st' => $data['st'] ?? null,
]);
} elseif ($data['busy'] === false) {
$idleStatusMap = [
'OGL' => ClientStatus::OG_LIVE,
'LNX' => ClientStatus::LINUX,
'WIN' => ClientStatus::WINDOWS,
'OSX' => ClientStatus::MACOS,
];
if (isset($data['loggedin']) && $data['loggedin'] === true) {
$idleStatusMap = [
'OGL' => ClientStatus::OG_LIVE,
'LNX' => ClientStatus::LINUX_SESSION,
'WIN' => ClientStatus::WINDOWS_SESSION,
'OSX' => ClientStatus::MACOS_SESSION,
];
}
$newStatus = $idleStatusMap[$data['st'] ?? ''] ?? ClientStatus::OG_LIVE;
if ($previousStatus !== $newStatus) {
$client->setStatus($newStatus);
$this->logger->info('Heartbeat: client status updated based on ping OS', [
'ip' => $data['iph'], 'previous_status' => $previousStatus, 'new_status' => $newStatus, 'st' => $data['st'] ?? null,
]);
} else {
$this->logger->info('Heartbeat: no status change', [
'ip' => $data['iph'], 'current_status' => $previousStatus, 'busy' => $data['busy'], 'st' => $data['st'] ?? null,
]);
}
}
}
}
$this->entityManager->persist($client);
$this->entityManager->flush();
}
if (isset($data['nfn']) && $data['nfn'] === 'START_SCRIPT') {
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if (!$trace) {
$clientIp = $data['iph'] ?? $request->getClientIp();
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]);
if ($client) {
$this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, TraceStatus::IN_PROGRESS, $data['job_id'], ['script' => $data['command'] ?? 'Local script']);
$this->logger->info('Trace automatically created for local script', ['job_id' => $data['job_id']]);
$client->setStatus(ClientStatus::BUSY);
$this->entityManager->persist($client);
$this->entityManager->flush();
}
}
}
if (isset($data['nfn']) && in_array($data['nfn'], ['REBOOT', 'POWEROFF'], true)) {
$clientIp = $data['iph'] ?? $request->getClientIp();
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]);
if ($client) {
$traces = $this->entityManager->getRepository(Trace::class)->findBy(['client' => $client, 'status' => TraceStatus::IN_PROGRESS]);
foreach ($traces as $trace) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
}
if ($client->getStatus() === ClientStatus::BUSY) {
$newStatus = ($data['nfn'] === 'REBOOT') ? ClientStatus::INITIALIZING : ClientStatus::TURNING_OFF;
$client->setStatus($newStatus);
$this->entityManager->persist($client);
}
$this->entityManager->flush();
$this->logger->info('Reboot/Poweroff webhook received. Automatically resolved in-progress traces.', ['num_traces' => count($traces), 'nfn' => $data['nfn']]);
}
}
if (isset($data['progress'])){
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace){
@ -143,312 +130,265 @@ class StatusController extends AbstractController
$this->entityManager->flush();
}
}
if (isset($data['nfn']) && $data['nfn'] === self::CREATE_IMAGE_GIT) {
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
$nfn = $data['nfn'] ?? null;
if ($nfn) {
switch ($nfn) {
case 'START_SCRIPT':
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if (!$trace) {
$clientIp = $data['iph'] ?? $request->getClientIp();
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]);
if ($client) {
$this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, TraceStatus::IN_PROGRESS, $data['job_id'], ['script' => $data['command'] ?? 'Local script']);
$this->logger->info('Trace automatically created for local script', ['job_id' => $data['job_id']]);
$client->setStatus(ClientStatus::BUSY);
$this->entityManager->persist($client);
$this->entityManager->flush();
}
} else {
if ($trace->getStatus() !== TraceStatus::SUCCESS && $trace->getStatus() !== TraceStatus::ERROR) {
$trace->setStatus(TraceStatus::IN_PROGRESS);
$this->entityManager->persist($trace);
$this->entityManager->flush();
}
}
break;
if (!$trace) {
$this->logger->error('Trace not found', $data);
return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND);
}
if ($data['res'] === 1) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
} else {
$trace->setStatus(TraceStatus::FAILED);
$trace->setFinishedAt(new \DateTime());
$trace->setOutput($data['der']);
}
case 'REBOOT':
case 'POWEROFF':
$clientIp = $data['iph'] ?? $request->getClientIp();
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]);
if ($client) {
$traces = $this->entityManager->getRepository(Trace::class)->findBy(['client' => $client, 'status' => TraceStatus::IN_PROGRESS]);
foreach ($traces as $trace) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
}
$previousStatus = $client->getStatus();
if ($previousStatus === ClientStatus::BUSY) {
$newStatus = ($nfn === 'REBOOT') ? ClientStatus::INITIALIZING : ClientStatus::TURNING_OFF;
$client->setStatus($newStatus);
$this->entityManager->persist($client);
$this->logger->info('Reboot/Poweroff received while client was busy, changing status', [
'ip' => $clientIp, 'nfn' => $nfn, 'previous_status' => $previousStatus, 'new_status' => $newStatus,
]);
} else {
$this->logger->info('Reboot/Poweroff received but client was not busy, status unchanged', [
'ip' => $clientIp, 'nfn' => $nfn, 'current_status' => $previousStatus,
]);
}
$this->entityManager->flush();
$this->logger->info('Reboot/Poweroff webhook received. Automatically resolved in-progress traces.', ['num_traces' => count($traces), 'nfn' => $nfn]);
}
break;
$client = $trace->getClient();
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
$this->entityManager->persist($trace);
$this->entityManager->flush();
$this->logger->info('Git image creation completed.', ['job_id' => $data['job_id'], 'success' => $data['res'] === 1]);
}
case self::CREATE_IMAGE_GIT:
case self::UPDATE_IMAGE_GIT:
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if (isset($data['nfn']) && $data['nfn'] === self::UPDATE_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);
}
if ($data['res'] === 1) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
} else {
$trace->setStatus(TraceStatus::FAILED);
$trace->setFinishedAt(new \DateTime());
$trace->setOutput($data['der']);
}
if (!$trace) {
$this->logger->error('Trace not found', $data);
return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND);
}
if ($data['res'] === 1) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
} else {
$trace->setStatus(TraceStatus::FAILED);
$trace->setFinishedAt(new \DateTime());
$trace->setOutput($data['der']);
}
$client = $trace->getClient();
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
$this->entityManager->persist($trace);
$this->entityManager->flush();
$msg = $nfn === self::CREATE_IMAGE_GIT ? 'Git image creation completed.' : 'Git image update completed.';
$this->logger->info($msg, ['job_id' => $data['job_id'], 'success' => $data['res'] === 1]);
break;
$client = $trace->getClient();
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
$this->entityManager->persist($trace);
$this->entityManager->flush();
$this->logger->info('Git image update completed.', ['job_id' => $data['job_id'], 'success' => $data['res'] === 1]);
}
case self::CREATE_IMAGE:
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
/** @var ImageImageRepository $imageImageRepository */
$imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $data['idi']]);
if (isset($data['nfn']) && $data['nfn'] === self::CREATE_IMAGE) {
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
/** @var ImageImageRepository $imageImageRepository */
$imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $data['idi']]);
if (!$imageImageRepository) {
$this->logger->error('Image not found', $data);
return new JsonResponse(['message' => 'Image not found'], Response::HTTP_NOT_FOUND);
}
if (!$imageImageRepository) {
$this->logger->error('Image not found', $data);
return new JsonResponse(['message' => 'Image not found'], Response::HTTP_NOT_FOUND);
}
if (!$trace) {
$this->logger->error('Trace not found', $data);
return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND);
}
if ($data['res'] === 1) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$imageImageRepository->setStatus(ImageStatus::AUX_FILES_PENDING);
$imageImageRepository->setCreated(true);
$this->entityManager->persist($imageImageRepository);
$this->logger->info('Start partition creation. ', ['image' => (string) $imageImageRepository->getUuid()]);
if (isset($data['cfg'])) {
$this->createPartitionService->__invoke($data, $imageImageRepository->getImage()->getClient());
}
$this->logger->info('Starting software profile creation. ', ['image' => (string) $imageImageRepository->getUuid()]);
$this->createSoftwareProfile($data['inv_sft'], $imageImageRepository);
$this->logger->info('Start aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]);
try {
$this->createAuxFilesAction->__invoke($imageImageRepository);
} catch (\Exception $e) {
$this->logger->error('Error creating aux files', ['image' => (string) $imageImageRepository->getUuid(), 'error' => $e->getMessage()]);
}
$this->logger->info('End aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]);
} else {
$trace->setStatus(TraceStatus::FAILED);
$trace->setFinishedAt(new \DateTime());
$trace->setOutput($data['der']);
$imageImageRepository->setCreated(false);
$imageImageRepository->setStatus(ImageStatus::FAILED);
$this->logger->error('Image updated failed', $data);
}
if (!$trace) {
$this->logger->error('Trace not found', $data);
return new JsonResponse(['message' => 'Trace not found'], Response::HTTP_NOT_FOUND);
}
if ($data['res'] === 1) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$imageImageRepository->setStatus(ImageStatus::AUX_FILES_PENDING);
$imageImageRepository->setCreated(true);
$this->entityManager->persist($imageImageRepository);
$client = $trace->getClient();
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
$this->logger->info('Start partition creation. ', ['image' => (string) $imageImageRepository->getUuid()]);
if (isset($data['cfg'])) {
$this->createPartitionService->__invoke($data, $imageImageRepository->getImage()->getClient());
}
$this->logger->info('Starting software profile creation. ', ['image' => (string) $imageImageRepository->getUuid()]);
$this->createSoftwareProfile($data['inv_sft'], $imageImageRepository);
$this->logger->info('Start aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]);
try {
$this->createAuxFilesAction->__invoke($imageImageRepository);
} catch (\Exception $e) {
$this->logger->error('Error creating aux files', ['image' => (string) $imageImageRepository->getUuid(), 'error' => $e->getMessage()]);
}
$this->logger->info('End aux files ogrepo API ', ['image' => (string) $imageImageRepository->getUuid()]);
} else {
$trace->setStatus(TraceStatus::FAILED);
$trace->setFinishedAt(new \DateTime());
$trace->setOutput($data['der']);
$imageImageRepository->setCreated(false);
$imageImageRepository->setStatus(ImageStatus::FAILED);
$this->logger->error('Image updated failed', $data);
}
$this->entityManager->persist($imageImageRepository);
$client = $trace->getClient();
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
$this->entityManager->persist($trace);
$this->entityManager->flush();
$this->logger->info('Image updated. Success.', ['image' => (string) $imageImageRepository->getUuid()]);
}
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) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
if (isset($data['cfg'])) {
$this->createPartitionService->__invoke($data,$client);
}
} else {
$trace->setStatus(TraceStatus::FAILED);
$trace->setFinishedAt(new \DateTime());
$trace->setOutput($data['der']);
}
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
$this->entityManager->persist($trace);
if ($data['nfn'] === self::RESTORE_IMAGE) {
$partitionData = json_decode(json_encode($trace->getInput()), true);
$numDisk = (int) $partitionData['numDisk'] ?? null;
$numPartition = (int) $partitionData['numPartition'] ?? null;
$imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $partitionData['image']]);
$partition = $this->entityManager->getRepository(Partition::class)
->findOneBy(['diskNumber' => $numDisk, 'partitionNumber' => $numPartition, 'client' => $client]);
if ($partition) {
$partition->setImage($imageImageRepository);
$this->entityManager->persist($partition);
}
}
$this->entityManager->flush();
}
if (isset($data['nfn']) && $data['nfn'] === self::RUN_SCRIPT) {
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
$this->logger->info('Image updated. Success.', ['image' => (string) $imageImageRepository->getUuid()]);
break;
case self::RESTORE_IMAGE:
case self::CONFIGURE_IMAGE:
case 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) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
if (isset($data['cfg'])) {
$this->createPartitionService->__invoke($data,$client);
}
} else {
$trace->setStatus(TraceStatus::FAILED);
$trace->setFinishedAt(new \DateTime());
$trace->setOutput($data['der']);
}
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
$this->entityManager->persist($trace);
if ($nfn === self::RESTORE_IMAGE) {
$partitionData = json_decode(json_encode($trace->getInput()), true);
$numDisk = (int) ($partitionData['numDisk'] ?? null);
$numPartition = (int) ($partitionData['numPartition'] ?? null);
$imageImageRepository = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $partitionData['image']]);
$partition = $this->entityManager->getRepository(Partition::class)
->findOneBy(['diskNumber' => $numDisk, 'partitionNumber' => $numPartition, 'client' => $client]);
if ($partition) {
$partition->setImage($imageImageRepository);
$this->entityManager->persist($partition);
}
}
$this->entityManager->flush();
break;
case self::RUN_SCRIPT:
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace) {
$client = $trace->getClient();
if ($data['res'] === 1) {
$trace->setStatus(TraceStatus::SUCCESS);
} else {
$trace->setStatus(TraceStatus::FAILED);
}
$trace->setOutput($data['der'] ?? '');
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
} else {
$clientIp = $data['iph'] ?? $request->getClientIp();
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]);
}
if ($client) {
if ($client && $client->getStatus() === ClientStatus::BUSY) {
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
if (isset($data['cfg'])) {
$this->createPartitionService->__invoke($data, $client);
$this->logger->info('Partition configuration updated via RUN_SCRIPT', ['job_id' => $data['job_id'] ?? 'none']);
}
}
$this->entityManager->flush();
break;
case self::HARDWARE_INVENTORY:
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace) {
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$this->entityManager->flush();
}
break;
case self::SOFTWARE_INVENTORY:
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace) {
$client = $trace->getClient();
$dataInput = json_decode(json_encode($trace->getInput()), true);
$imageUuid = $dataInput['image'] ?? null;
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$image = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $imageUuid]);
$this->createSoftwareProfile($data['contents'], $image);
$this->entityManager->flush();
}
break;
case self::REFRESH:
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id'] ?? '']);
if ($trace) {
$client = $trace->getClient();
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
} else {
$clientIp = $data['iph'] ?? $request->getClientIp();
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]);
}
if ($client) {
$this->entityManager->persist($client);
if (isset($data['cfg'])) {
$this->createPartitionService->__invoke($data, $client);
$this->logger->info('Partition configuration updated via REFRESH', ['job_id' => $data['job_id'] ?? 'none']);
}
}
$this->entityManager->flush();
break;
case 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) {
$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 {
$this->logger->warning('RESPUESTA_IniciarSesion: agent reported failure', [
'ip' => $clientIp,
'job_id' => $data['job_id'] ?? null,
'res' => $res,
]);
}
}
break;
}
}
if (isset($client) && $client) {
try {
$this->pendingTraceExecutionService->executeNextTraceForClient($client);
} catch (\Exception $e) {
$this->logger->error('Error proactively processing next trace for client', [
'ip' => $client->getIp(),
'error' => $e->getMessage()
]);
if (isset($data['nfn']) && $data['nfn'] === self::HARDWARE_INVENTORY) {
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace) {
$client = $trace->getClient();
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
//$client->setHardwareProfile();
$this->entityManager->flush();
}
}
if (isset($data['nfn']) && $data['nfn'] === self::SOFTWARE_INVENTORY) {
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id']]);
if ($trace) {
$client = $trace->getClient();
$dataInput = json_decode(json_encode($trace->getInput()), true);
$imageUuid = $dataInput['image'] ?? null;
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
$image = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $imageUuid]);
$this->createSoftwareProfile($data['contents'], $image);
$this->entityManager->flush();
}
}
if (isset($data['nfn']) && $data['nfn'] === self::REFRESH) {
$trace = $this->entityManager->getRepository(Trace::class)->findOneBy(['jobId' => $data['job_id'] ?? '']);
if ($trace) {
$client = $trace->getClient();
$trace->setStatus(TraceStatus::SUCCESS);
$trace->setFinishedAt(new \DateTime());
$this->entityManager->persist($trace);
} else {
$clientIp = $data['iph'] ?? $request->getClientIp();
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $clientIp]);
}
if ($client) {
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
if (isset($data['cfg'])) {
$this->createPartitionService->__invoke($data, $client);
$this->logger->info('Partition configuration updated via RESPUESTA_Actualizar', ['job_id' => $data['job_id'] ?? 'none']);
}
}
$this->entityManager->flush();
}
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,
]);
}
}
}
@ -465,13 +405,11 @@ class StatusController extends AbstractController
$existingNames = array_map(fn($software) => $software->getName(), $existingSoftware);
$newSoftwareNames = array_diff($softwareList, $existingNames);
$newSoftware = [];
foreach ($newSoftwareNames as $software) {
$softwareEntity = new Software();
$softwareEntity->setName($software);
$softwareEntity->setType(SoftwareTypes::APPLICATION);
$this->entityManager->persist($softwareEntity);
$newSoftware[] = $softwareEntity;
}
$image = $imageImageRepository?->getImage();
@ -479,12 +417,13 @@ class StatusController extends AbstractController
$softwareProfile = new SoftwareProfile();
$softwareProfile->setDescription('SW Profile - ' . $image->getClient()->getName());
foreach ([...$existingSoftware, ...$newSoftware] as $softwareEntity) {
foreach ($existingSoftware as $softwareEntity) {
$softwareEntity->addSoftwareProfile($softwareProfile);
}
$imageImageRepository->setSoftwareProfile($softwareProfile);
$image->setSoftwareProfile($softwareProfile);
$this->entityManager->persist($image);
$this->entityManager->persist($imageImageRepository);
$this->entityManager->persist($softwareProfile);
$this->entityManager->flush();

View File

@ -7,7 +7,6 @@ use App\Entity\Client;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
@ -22,30 +21,12 @@ class DeleteAction extends AbstractOgBootController
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __invoke(string $mac, ?Client $client = null): JsonResponse
public function __invoke(string $mac): JsonResponse
{
$mac = strtolower($mac);
$response = $this->createRequest('DELETE', '/ogboot/v1/pxes/'.$mac);
// Intentamos obtener el servidor de boot asociado al cliente
$bootServer = null;
if ($client !== null) {
$bootServer = $client->getBootServer() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getBootServer();
}
try {
if ($bootServer) {
// Si el cliente tiene un servidor de boot específico, borramos de ahí
$this->createRequestFromBootServer($bootServer, 'DELETE', '/ogboot/v1/pxes/'.$mac);
} else {
// Si no tiene (o si no se pasó el cliente), usamos el servidor por defecto
$this->createRequest('DELETE', '/ogboot/v1/pxes/'.$mac);
}
} catch (HttpException $e) {
if ($e->getStatusCode() === Response::HTTP_NOT_FOUND) {
// Si el archivo ya no existe, consideramos el borrado como exitoso
return new JsonResponse(data: [], status: Response::HTTP_OK);
}
throw $e;
if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
return new JsonResponse( data: 'An error occurred', status: Response::HTTP_INTERNAL_SERVER_ERROR);
}
return new JsonResponse( data: [], status: Response::HTTP_OK);

View File

@ -47,8 +47,8 @@ class PostAction extends AbstractOgBootController
'server_ip' => $bootServer->getIp(),
'server_api_port' => $bootServer->getApiPort(),
'server_pxe_port' => $bootServer->getPxePort(),
'router' => $client->getSubnet()?->getRouter() ?? $client->getOrganizationalUnit()->getNetworkSettings()?->getRouter() ?? '',
'netmask' => $client->getSubnet()?->getNetmask() ?? $client->getOrganizationalUnit()->getNetworkSettings()?->getNetmask() ?? '255.255.255.0',
'router' => $client->getOrganizationalUnit()->getNetworkSettings()?->getRouter(),
'netmask' => $client->getOrganizationalUnit()->getNetworkSettings() ? $client->getOrganizationalUnit()->getNetworkSettings()->getNetmask() : '255.255.255.0',
'computer_name' => $client->getName(),
'netiface' => $client->getNetiface() ? $client->getNetiface() : $client->getOrganizationalUnit()->getNetworkSettings()?->getNetiface(),
'group' => $client->getOrganizationalUnit()->getName(),

View File

@ -1,148 +0,0 @@
<?php
namespace App\Controller\OgBoot;
use App\Controller\OgBoot\PxeBootFile\PostAction as PostPxeAction;
use App\Entity\Client;
use App\Entity\PxeTemplate;
use App\Entity\Trace;
use App\Model\TraceStatus;
use App\Repository\ClientRepository;
use App\Repository\OrganizationalUnitRepository;
use App\Repository\PxeTemplateRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class SetClientBootModeAction extends AbstractController
{
public function __construct(
private readonly ClientRepository $clientRepository,
private readonly OrganizationalUnitRepository $ouRepository,
private readonly PxeTemplateRepository $pxeTemplateRepository,
private readonly PostPxeAction $postPxeAction,
private readonly EntityManagerInterface $entityManager
) {}
#[Route('/clients/set-boot-mode', name: 'api_clients_set_boot_mode', methods: ['POST'])]
#[IsGranted('ROLE_OGCLIENT_API')]
public function __invoke(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$clientData = $data['client'] ?? null;
$ouData = $data['ou'] ?? null;
$templateName = $data['template'] ?? null;
$mode = $data['mode'] ?? 0; // 0: TEMP, 1: PERM
if ((!$clientData && !$ouData) || !$templateName) {
return new JsonResponse(['error' => 'Faltan parámetros: se requiere "client" u "ou", y "template"'], Response::HTTP_BAD_REQUEST);
}
// 1. Obtener la lista de clientes afectados de forma explícita
$clients = [];
if ($clientData) {
// Búsqueda específica de cliente (Prioridad: MAC > Nombre > IP)
if (isset($clientData['mac'])) {
$c = $this->clientRepository->findOneBy(['mac' => $clientData['mac']]);
if ($c) $clients[] = $c;
} elseif (isset($clientData['name'])) {
$c = $this->clientRepository->findOneBy(['name' => $clientData['name']]);
if ($c) $clients[] = $c;
} elseif (isset($clientData['ip'])) {
$c = $this->clientRepository->findOneBy(['ip' => $clientData['ip']]);
if ($c) $clients[] = $c;
}
} elseif ($ouData) {
// Búsqueda específica de Aula (OU)
if (isset($ouData['name'])) {
$ou = $this->ouRepository->findOneBy(['name' => $ouData['name']]);
if ($ou) {
$clients = $this->clientRepository->findBy(['organizationalUnit' => $ou]);
}
} elseif (isset($ouData['id'])) {
$ou = $this->ouRepository->find($ouData['id']);
if ($ou) {
$clients = $this->clientRepository->findBy(['organizationalUnit' => $ou]);
}
}
}
if (empty($clients)) {
return new JsonResponse(['error' => "No se encontró ningún cliente que coincida con los criterios."], Response::HTTP_NOT_FOUND);
}
$count = 0;
$errors = [];
foreach ($clients as $client) {
/** @var Client $client */
$bootServer = $client->getBootServer() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getBootServer();
if (!$bootServer) {
$errors[] = "El cliente {$client->getName()} no tiene un servidor de arranque asignado.";
continue;
}
/** @var PxeTemplate|null $template */
$template = $this->pxeTemplateRepository->findOneBy([
'name' => $templateName,
'bootServer' => $bootServer
]);
if (!$template) {
$errors[] = "No se encontró la plantilla '$templateName' en el servidor {$bootServer->getName()} para el cliente {$client->getName()}.";
continue;
}
if ($mode == 1) {
// MODO PERMANENTE: Actualizamos el objeto (PostAction hará el flush)
$client->setTemplate($template);
}
// Generar el fichero PXE
try {
$this->postPxeAction->__invoke($client, $template);
$count++;
if ($mode == 0) {
$projectDir = $this->getParameter('kernel.project_dir');
$mac = $client->getMac();
// Crear traza para el proceso en segundo plano
$trace = new Trace();
$trace->setClient($client);
$trace->setCommand('opengnsys:pxe:sync');
$trace->setStatus(TraceStatus::PENDING);
$trace->setExecutedAt(new \DateTime());
$trace->setInput(['mac' => $mac, 'delay' => 60]);
$this->entityManager->persist($trace);
$this->entityManager->flush();
$cmd = sprintf(
'php %s/bin/console opengnsys:pxe:sync %s 60 --trace-id=%d > /dev/null 2>&1 &',
$projectDir,
escapeshellarg($mac),
$trace->getId()
);
exec($cmd);
}
} catch (\Exception $e) {
$errors[] = "Error en {$client->getName()}: " . $e->getMessage();
}
}
return new JsonResponse([
'status' => count($errors) > 0 && $count == 0 ? 'error' : 'success',
'clients_processed' => $count,
'errors' => $errors,
'mode' => ($mode == 1 ? 'PERMANENT' : 'TEMPORARY')
]);
}
}

View File

@ -15,15 +15,11 @@ class DeleteAction extends AbstractOgRepositoryController
{
public function __invoke(ImageRepository $repository, DeleteRepositoryInput $input): JsonResponse
{
if (empty($input->repositoryName)) {
throw new BadRequestHttpException('Repository name is required');
}
$content = $this->createRequest('DELETE', 'http://'.$repository->getIp().':8006/ogrepository/v1/git/repositories/'.$input->repositoryName, [
$content = $this->createRequest('DELETE', 'http://'.$repository->getIp().':8006/ogrepository/v1/git/repositories/'.$input->repository, [
]);
if (isset($content['error'])) {
throw new BadRequestHttpException($content['details'] ?? $content['error']);
if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
throw new BadRequestHttpException('Error deleting repository');
}
return new JsonResponse(data: [], status: Response::HTTP_OK);

View File

@ -41,6 +41,7 @@ class ConvertAction extends AbstractOgRepositoryController
$imageEntity = new Image();
$imageEntity->setName($image);
$imageEntity->setType('monolithic');
$imageEntity->setRemotePc(false);
$imageEntity->setIsGlobal(false);
$this->entityManager->persist($imageEntity);
@ -58,7 +59,6 @@ class ConvertAction extends AbstractOgRepositoryController
$imageImageRepositoryEntity->setImage($imageEntity);
$imageImageRepositoryEntity->setRepository($repository);
$imageImageRepositoryEntity->setVersion(1);
$imageImageRepositoryEntity->setRemotePc(false);
$this->entityManager->persist($imageImageRepositoryEntity);

View File

@ -78,6 +78,7 @@ class ImportAction extends AbstractOgRepositoryController
$imageEntity = new Image();
$imageEntity->setName($imageName);
$imageEntity->setType('monolithic');
$imageEntity->setRemotePc(false);
$imageEntity->setIsGlobal(false);
$this->entityManager->persist($imageEntity);

View File

@ -50,6 +50,7 @@ class SyncAction extends AbstractOgRepositoryController
if (!$imageEntity) {
$imageEntity = new Image();
$imageEntity->setName($image['name']);
$imageEntity->setRemotePc(false);
$imageEntity->setIsGlobal(false);
$imageEntity->setType('monolithic');
@ -67,7 +68,6 @@ class SyncAction extends AbstractOgRepositoryController
$imageImageRepositoryEntity->setDatasize(isset($image['datasize']) ? (string) $image['datasize'] : null);
$imageImageRepositoryEntity->setSize(isset($image['size']) ? (string) $image['size'] : null);
$imageImageRepositoryEntity->setStatus(ImageStatus::SUCCESS);
$imageImageRepositoryEntity->setRemotePc(false);
$this->entityManager->persist($imageImageRepositoryEntity);
}
@ -80,18 +80,6 @@ class SyncAction extends AbstractOgRepositoryController
$this->entityManager->flush();
$orphanImages = $imageRepo->createQueryBuilder('i')
->leftJoin('i.imageImageRepositories', 'iir')
->andWhere('iir.id IS NULL')
->getQuery()
->getResult();
foreach ($orphanImages as $orphanImage) {
$this->entityManager->remove($orphanImage);
}
$this->entityManager->flush();
return new JsonResponse(data: $content, status: Response::HTTP_OK);
}

View File

@ -48,33 +48,19 @@ class WoLAction extends AbstractOgRepositoryController
throw new BadRequestHttpException('IP is required');
}
// 1. Buscamos la máscara. Si no hay por ningún lado, devolverá null.
$netmask = $client->getSubnet()?->getNetmask()?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getNetmask();
// 2. Broadcast por defecto (global)
$broadcastIp = "255.255.255.255";
// 3. Si encontramos una máscara válida, calculamos el broadcast específico
if ($netmask) {
$ipLong = ip2long($client->getIp());
$netmaskLong = ip2long($netmask);
$broadcastIp = long2ip($ipLong | (~$netmaskLong));
}
$params = [
'json' => [
'broadcast_ip' => $broadcastIp,
'broadcast_ip' => '255.255.255.255',
'mac' => $client->getMac()
]
];
$this->logger->info('Sending WoL to client', ['mac' => $client->getMac(), 'broadcast_ip' => $broadcastIp]);
$this->logger->info('Sending WoL to client', ['mac' => $client->getMac()]);
$content = $this->createRequest('POST', 'http://'.$repository->getIp(). ':8006/ogrepository/v1/wol', $params);
if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) {
$this->logger->error('Error sending WoL to client', ['mac' => $client->getMac(), 'broadcast_ip' => $broadcastIp]);
$this->logger->error('Error sending WoL to client', ['mac' => $client->getMac()]);
continue;
}

View File

@ -1,111 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Entity\Plugin;
use App\Repository\PluginRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route(path: '/{_prefix}plugins', requirements: ['_prefix' => '(api/)?'], defaults: ['_prefix' => ''])]
#[IsGranted('ROLE_USER')]
class PluginController extends AbstractController
{
public function __construct(
private readonly PluginRepository $pluginRepository,
) {
}
#[Route('', methods: ['GET'])]
public function list(Request $request): JsonResponse
{
$all = $request->query->getBoolean('all', false);
$criteria = $all ? [] : ['enabled' => true];
$plugins = $this->pluginRepository->findBy($criteria, ['name' => 'ASC']);
$data = array_map(static fn(Plugin $plugin) => $plugin->toArray(), $plugins);
return new JsonResponse($data);
}
#[Route('/{name}/toggle', name: 'api_plugins_toggle', methods: ['POST', 'PATCH'])]
public function toggle(string $name, Request $request): JsonResponse
{
$plugin = $this->pluginRepository->findOneBy(['name' => $name]);
if (!$plugin) {
return new JsonResponse(['message' => sprintf('Plugin "%s" no encontrado.', $name)], Response::HTTP_NOT_FOUND);
}
$body = json_decode($request->getContent(), true) ?? [];
$enabled = isset($body['enabled']) ? (bool) $body['enabled'] : !$plugin->isEnabled();
$plugin->setEnabled($enabled);
$this->pluginRepository->save($plugin, true);
return new JsonResponse([
'message' => sprintf('Plugin "%s" %s correctamente.', $name, $enabled ? 'activado' : 'desactivado'),
'enabled' => $enabled,
'plugin' => $plugin->toArray(),
]);
}
#[Route('/{name}', name: 'api_plugins_get', methods: ['GET'])]
public function getOne(string $name): JsonResponse
{
$plugin = $this->pluginRepository->findOneBy(['name' => $name]);
if (!$plugin) {
return new JsonResponse(['message' => sprintf('Plugin "%s" no encontrado.', $name)], Response::HTTP_NOT_FOUND);
}
return new JsonResponse($plugin->toArray());
}
#[Route('/{name}/config', name: 'api_plugins_get_config', methods: ['GET'])]
public function getConfig(string $name): JsonResponse
{
$plugin = $this->pluginRepository->findOneBy(['name' => $name]);
if (!$plugin) {
return new JsonResponse(['message' => sprintf('Plugin "%s" no encontrado.', $name)], Response::HTTP_NOT_FOUND);
}
$config = $plugin->getConfigData() ?? [];
$defaultConfig = $plugin->toArray()['defaultConfig'] ?? [];
return new JsonResponse(array_merge($defaultConfig, $config));
}
#[Route('/{name}/config', name: 'api_plugins_update_config', methods: ['POST', 'PUT'])]
public function updateConfig(string $name, Request $request): JsonResponse
{
$plugin = $this->pluginRepository->findOneBy(['name' => $name]);
if (!$plugin) {
return new JsonResponse(['message' => sprintf('Plugin "%s" no encontrado.', $name)], Response::HTTP_NOT_FOUND);
}
$body = json_decode($request->getContent(), true);
if (!is_array($body)) {
return new JsonResponse(['message' => 'Cuerpo de la petición inválido (debe ser un objeto JSON).'], Response::HTTP_BAD_REQUEST);
}
$currentConfig = $plugin->getConfigData() ?? [];
$newConfig = array_merge($currentConfig, $body);
$plugin->setConfigData($newConfig);
$this->pluginRepository->save($plugin, true);
return new JsonResponse([
'message' => 'Configuración actualizada correctamente.',
'config' => $newConfig,
]);
}
}

View File

@ -1,84 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controller\System;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class DiskLogsAction extends AbstractController
{
private const REMOTE_JOURNAL_DIR = '/var/log/journal/remote';
#[Route('/opengnsys/system/disk-logs', name: 'api_system_disk_logs', methods: ['GET'])]
#[IsGranted('ROLE_USER')]
public function __invoke(Request $request): JsonResponse
{
// Acepta SYSLOG_IDENTIFIER como valor único, array (?SYSLOG_IDENTIFIER[]=a&SYSLOG_IDENTIFIER[]=b)
// o lista separada por comas (?SYSLOG_IDENTIFIER=a,b)
$rawIdentifiers = $request->query->all()['SYSLOG_IDENTIFIER'] ?? $request->query->get('SYSLOG_IDENTIFIER');
if (is_string($rawIdentifiers)) {
$rawIdentifiers = array_map('trim', explode(',', $rawIdentifiers));
}
$identifiers = array_values(array_filter((array) $rawIdentifiers));
$host = $request->query->get('host');
$lines = $request->query->getInt('lines', 100);
if (empty($identifiers)) {
return new JsonResponse(['error' => 'El parámetro SYSLOG_IDENTIFIER es obligatorio.'], Response::HTTP_BAD_REQUEST);
}
$lines = max(1, min(1000, $lines));
$args = ['--no-pager', '--output=json', sprintf('-n %d', $lines)];
if ($host) {
// Host remoto: leer del directorio journal nombrado por IP
$journalDir = sprintf('%s/%s', self::REMOTE_JOURNAL_DIR, $host);
if (!is_dir($journalDir)) {
return new JsonResponse(
['error' => sprintf('No se encontró el journal para el host %s', $host)],
Response::HTTP_NOT_FOUND
);
}
$args[] = sprintf('--directory=%s', escapeshellarg($journalDir));
}
// Múltiples SYSLOG_IDENTIFIER se pasan como matches separados → journalctl los aplica con OR
foreach ($identifiers as $identifier) {
$args[] = sprintf('SYSLOG_IDENTIFIER=%s', escapeshellarg($identifier));
}
$command = sprintf('journalctl %s 2>&1', implode(' ', $args));
$output = [];
$returnVar = 0;
exec($command, $output, $returnVar);
if ($returnVar !== 0) {
return new JsonResponse([
'error' => 'Error al ejecutar journalctl',
'output' => implode("\n", $output)
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Parsear cada línea como JSON (formato --output=json de journalctl)
$entries = array_values(array_filter(array_map(
static fn(string $line) => json_decode($line, true),
$output
)));
return new JsonResponse([
'identifiers' => $identifiers,
'host' => $host ?? 'local',
'lines' => count($entries),
'entries' => $entries,
]);
}
}

View File

@ -183,11 +183,7 @@ class RemotePcController extends AbstractController
->setParameter('status', TraceStatus::PENDING)
->execute();
if ($client->getOrganizationalUnit() && $client->getOrganizationalUnit()->isRemotePcRebootOnUnreserve()) {
$this->sendReboot($client);
} else {
$this->sendPowerOff($client);
}
$this->sendPowerOff($client);
$this->logger->info('RemotePC: client unreserved', ['client_id' => $client->getId()]);
@ -379,20 +375,6 @@ class RemotePcController extends AbstractController
}
}
private function sendReboot(Client $client): void
{
try {
$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 | HttpExceptionInterface $e) {
$this->logger->warning('RemotePC: reboot failed', ['client_id' => $client->getId(), 'error' => $e->getMessage()]);
}
}
private function createQueueEntry(Client $client, \DateTimeInterface $execTime, string $operation): void
{
$entry = new AgentQueue();

View File

@ -7,9 +7,7 @@ use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use App\Entity\OrganizationalUnit;
use App\Entity\Trace;
use App\Entity\User;
use App\Model\UserGroupPermissions;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;
@ -22,74 +20,31 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection
}
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void
{
$this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass);
$this->addWhere($queryBuilder, $resourceClass);
}
public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void
{
$this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass);
$this->addWhere($queryBuilder, $resourceClass);
}
private function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass): void
private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
{
/** @var User $user */
$user = $this->security->getUser();
if (null === $user || in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $user->getRoles())) {
if (OrganizationalUnit::class !== $resourceClass || null === $user || in_array('ROLE_SUPER_ADMIN', $user->getRoles())) {
return;
}
switch ($resourceClass) {
case OrganizationalUnit::class:
$this->addOrganizationalUnitWhere($queryBuilder, $user);
break;
case Trace::class:
$this->addTraceWhere($queryBuilder, $queryNameGenerator, $user);
break;
}
}
private function addOrganizationalUnitWhere(QueryBuilder $queryBuilder, User $user): void
{
$rootAlias = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere(sprintf('%s.id in (:ou)', $rootAlias));
$queryBuilder->setParameter('ou', $this->getAllowedOrganizationalUnitIds($user));
}
/**
* Una traza pertenece a un cliente, y el cliente a una unidad organizativa: el usuario solo puede
* ver las trazas de los equipos de las unidades organizativas que tiene asignadas (y sus hijas).
*/
private function addTraceWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, User $user): void
{
$rootAlias = $queryBuilder->getRootAliases()[0];
$organizationalUnitIds = $this->getAllowedOrganizationalUnitIds($user);
if (empty($organizationalUnitIds)) {
$queryBuilder->andWhere('1 = 0');
return;
}
$clientAlias = $queryNameGenerator->generateJoinAlias('client');
$queryBuilder->innerJoin(sprintf('%s.client', $rootAlias), $clientAlias);
$queryBuilder->andWhere(sprintf('%s.organizationalUnit in (:trace_ou)', $clientAlias));
$queryBuilder->setParameter('trace_ou', $organizationalUnitIds);
}
/**
* @return int[]
*/
private function getAllowedOrganizationalUnitIds(User $user): array
{
$organizationalUnitIds = [];
foreach ($user->getAllowedOrganizationalUnits() as $allowedOrganizationalUnit) {
$this->addOrganizationalUnitAndChildrenIds($allowedOrganizationalUnit, $organizationalUnitIds);
}
return $organizationalUnitIds;
$rootAlias = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere(sprintf('%s.id in (:ou)', $rootAlias));
$queryBuilder->setParameter('ou', $organizationalUnitIds);
}
private function addOrganizationalUnitAndChildrenIds(OrganizationalUnit $organizationalUnit, array &$organizationalUnitIds): void
@ -103,4 +58,4 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection
}
}
}
}

View File

@ -13,10 +13,10 @@ final class ChangeOrganizationalUnitInput
/**
* @var ClientOutput[]
*/
#[Assert\Count(min: 1)]
#[Assert\GreaterThan(1)]
#[Groups(['client:write'])]
#[ApiProperty(
description: 'Los clientes a mover (mínimo 1)',
description: 'Los clientes a mover (mínimo 2)',
example: []
)]
public ?array $clients = [];

View File

@ -86,13 +86,7 @@ final class ClientInput
#[ApiProperty(
description: 'La plantilla PXE del cliente'
)]
public ?PxeTemplateOutput $pxeTemplate = null;
#[Groups(['client:write'])]
#[ApiProperty(
description: 'El perfil de hardware del cliente'
)]
public ?HardwareProfileOutput $hardwareProfile = null;
public ?PxeTemplateOutput $pxeTemplate = null;
#[Groups(['client:write'])]
#[ApiProperty(
@ -168,10 +162,6 @@ final class ClientInput
$this->pxeTemplate = new PxeTemplateOutput($client->getTemplate());
}
if ($client->getHardwareProfile()) {
$this->hardwareProfile = new HardwareProfileOutput($client->getHardwareProfile(), includeClients: false);
}
if ($client->getRepository()) {
$this->repository = new ImageRepositoryOutput($client->getRepository());
}
@ -189,7 +179,6 @@ final class ClientInput
$menu = $this->menu?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getMenu();
$ogLive = $this->ogLive?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getOgLive();
$hardwareProfile = $this->hardwareProfile?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getHardwareProfile();
$repository = $this->repository?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getRepository();
$template = $this->pxeTemplate?->getEntity() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getPxeTemplate();
@ -202,7 +191,6 @@ final class ClientInput
$client->setIp($this->ip);
$client->setMenu($menu);
$client->setOgLive($ogLive);
$client->setHardwareProfile($hardwareProfile);
$client->setRepository($repository);
$client->setTemplate($template);
$client->setPosition($this->position);

View File

@ -41,11 +41,4 @@ final class CommandExecuteInput
example: false
)]
public bool $runAsAdmin = false;
#[Groups(['command:write'])]
#[ApiProperty(
description: 'Sistema operativo requerido para la ejecución (ej: windows, linux, og-live)',
example: 'windows'
)]
public ?string $targetOs = null;
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\ClientOutput;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
final class CommandTaskExecuteInput
{
/**
* @var ClientOutput[]
*/
#[Assert\NotNull]
#[Groups(['command-task:write'])]
#[ApiProperty(
description: 'Los clientes donde ejecutar la tarea',
example: []
)]
public array $clients = [];
}

View File

@ -74,18 +74,20 @@ final class CommandTaskScheduleInput
$commandTaskSchedule = new CommandTaskSchedule();
}
$utc = new \DateTimeZone('UTC');
if ($this->commandTask) {
$commandTaskSchedule->setCommandTask($this->commandTask->getEntity());
}
$commandTaskSchedule->setRecurrenceType($this->recurrenceType);
$commandTaskSchedule->setExecutionTime(
$this->executionTime
? \DateTime::createFromInterface($this->executionTime)->setTimezone(new \DateTimeZone('UTC'))
? \DateTime::createFromInterface($this->executionTime)->setTimezone($utc)
: null
);
$commandTaskSchedule->setExecutionDate(
$this->executionDate
? \DateTime::createFromInterface($this->executionDate)
? \DateTime::createFromInterface($this->executionDate)->setTimezone($utc)
: null
);
$commandTaskSchedule->setRecurrenceDetails($this->recurrenceDetails);

View File

@ -7,7 +7,7 @@ use Symfony\Component\Serializer\Annotation\Groups;
final class DeleteRepositoryInput
{
#[Groups(['repository:write'])]
#[Groups(['image-image-repository:write'])]
#[ApiProperty(description: 'The repository name', example: "")]
public ?string $repositoryName = null;
public ?string $repository = null;
}

View File

@ -6,8 +6,10 @@ namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\ClientOutput;
use App\Validator\Constraints\ClientsHaveSamePartitionSize;
use Symfony\Component\Serializer\Annotation\Groups;
#[ClientsHaveSamePartitionSize]
class DeployGitImageInput
{
#[Groups(['git-repository:write'])]

View File

@ -4,11 +4,13 @@ namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\ClientOutput;
use App\Validator\Constraints\ClientsHaveSamePartitionSize;
use App\Validator\Constraints\OrganizationalUnitMulticastMode;
use App\Validator\Constraints\OrganizationalUnitMulticastPort;
use App\Validator\Constraints\OrganizationalUnitP2PMode;
use Symfony\Component\Serializer\Annotation\Groups;
#[ClientsHaveSamePartitionSize]
class DeployImageInput
{
#[Groups(['image-image-repository:write'])]

View File

@ -5,6 +5,7 @@ namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Entity\HardwareProfile;
use Symfony\Component\Serializer\Annotation\Groups;
use App\Dto\Output\ClientOutput;
final class HardwareProfileInput
{
@ -16,6 +17,10 @@ final class HardwareProfileInput
#[ApiProperty(description: 'Comments of the hardware profile', example: "Hardware 1")]
public ?string $comments = null;
#[Groups(['hardware-profile:write'])]
#[ApiProperty(description: 'The client of the hardware profile', readableLink: true)]
public ?ClientOutput $client = null;
public function __construct(?HardwareProfile $hardwareProfile = null)
{
if (!$hardwareProfile) {
@ -24,6 +29,7 @@ final class HardwareProfileInput
$this->description = $hardwareProfile->getDescription();
$this->comments = $hardwareProfile->getComments();
$this->client = new ClientOutput($hardwareProfile->getClient());
}
public function createOrUpdateEntity(?HardwareProfile $hardwareProfile = null): HardwareProfile
@ -34,6 +40,7 @@ final class HardwareProfileInput
$hardwareProfile->setDescription($this->description);
$hardwareProfile->setComments($this->comments);
$hardwareProfile->setClient($this->client->getEntity());
return $hardwareProfile;
}

View File

@ -5,7 +5,6 @@ namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\ImageOutput;
use App\Dto\Output\ImageRepositoryOutput;
use App\Dto\Output\SoftwareProfileOutput;
use App\Entity\ImageImageRepository;
use App\Entity\PxeTemplate;
use Symfony\Component\Serializer\Annotation\Groups;
@ -20,10 +19,6 @@ final class ImageImageRepositoryInput
#[ApiProperty(description: 'Whether this image is available for Remote PC in this repository', example: false)]
public ?bool $remotePc = false;
#[Groups(['image-image-repository:write'])]
#[ApiProperty(description: 'El perfil de software detectado en esta versión de la imagen')]
public ?SoftwareProfileOutput $softwareProfile = null;
public function __construct(?ImageImageRepository $imageImageRepository = null)
{
if (!$imageImageRepository) {
@ -32,10 +27,6 @@ final class ImageImageRepositoryInput
$this->description = $imageImageRepository->getDescription();
$this->remotePc = $imageImageRepository->isRemotePc();
if ($imageImageRepository->getSoftwareProfile()) {
$this->softwareProfile = new SoftwareProfileOutput($imageImageRepository->getSoftwareProfile(), false);
}
}
public function createOrUpdateEntity(?ImageImageRepository $imageImageRepository = null): ImageImageRepository
@ -46,7 +37,6 @@ final class ImageImageRepositoryInput
$imageImageRepository->setDescription($this->description);
$imageImageRepository->setRemotePc($this->remotePc);
$imageImageRepository->setSoftwareProfile($this->softwareProfile?->getEntity());
return $imageImageRepository;
}

View File

@ -10,6 +10,7 @@ use App\Dto\Output\ImageRepositoryOutput;
use App\Dto\Output\OrganizationalUnitOutput;
use App\Dto\Output\PartitionOutput;
use App\Dto\Output\RemoteCalendarRuleOutput;
use App\Dto\Output\SoftwareProfileOutput;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\OrganizationalUnit;
@ -32,6 +33,10 @@ final class ImageInput
#[ApiProperty(description: 'The optional selected image')]
public ?ImageOutput $selectedImage = null;
#[Groups(['image:write'])]
#[ApiProperty(description: 'The software profile of the image')]
public ?SoftwareProfileOutput $softwareProfile = null;
/**
* @var ImageRepositoryOutput[]
*/
@ -78,6 +83,10 @@ final class ImageInput
$this->isGlobal = $image->isGlobal();
$this->version = $image->getVersion();
if ($image->getSoftwareProfile()) {
$this->softwareProfile = new SoftwareProfileOutput($image->getSoftwareProfile());
}
if ($image->getClient()) {
$this->client = new ClientOutput($image->getClient());
}
@ -100,6 +109,10 @@ final class ImageInput
$image->setName($this->name);
$image->setType($this->type);
if ($this->softwareProfile) {
$image->setSoftwareProfile($this->softwareProfile->getEntity());
}
if ($this->client) {
$image->setClient($this->client->getEntity());
}

View File

@ -102,13 +102,6 @@ class OrganizationalUnitInput
)]
public ?bool $remotePc = false;
#[Groups(['organizational-unit:write'])]
#[ApiProperty(
description: 'Indica si RemotePC debe reiniciar el equipo al liberar la reserva',
example: false
)]
public ?bool $remotePcRebootOnUnreserve = false;
#[Groups(['organizational-unit:write'])]
#[ApiProperty(
description: 'Si excluir cambios del padre',
@ -135,7 +128,6 @@ class OrganizationalUnitInput
$this->comments = $organizationalUnit->getComments();
$this->type = $organizationalUnit->getType();
$this->remotePc = $organizationalUnit->isRemotePc();
$this->remotePcRebootOnUnreserve = $organizationalUnit->isRemotePcRebootOnUnreserve();
if ($organizationalUnit->getNetworkSettings()){
$this->networkSettings = new NetworkSettingsInput($organizationalUnit->getNetworkSettings());
}
@ -163,7 +155,6 @@ class OrganizationalUnitInput
$organizationalUnit->setComments($this->comments);
$organizationalUnit->setType($this->type);
$organizationalUnit->setRemotePc($this->remotePc);
$organizationalUnit->setRemotePcRebootOnUnreserve($this->remotePcRebootOnUnreserve ?? false);
$organizationalUnit->setExcludeParentChanges($this->excludeParentChanges);
if ($this->networkSettings){

View File

@ -5,8 +5,6 @@ namespace App\Dto\Input;
use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\ImageOutput;
use App\Dto\Output\OperativeSystemOutput;
use App\Dto\Output\SoftwareOutput;
use App\Entity\Software;
use App\Entity\SoftwareProfile;
use Symfony\Component\Serializer\Annotation\Groups;
@ -28,12 +26,6 @@ final class SoftwareProfileInput
#[ApiProperty(description: 'The operative system of the software profile')]
public ?OperativeSystemOutput $operativeSystem = null;
/**
* @var SoftwareOutput[]
*/
#[Groups(['software-profile:write'])]
#[ApiProperty(description: 'The software collection of the software profile', readableLink: true)]
public array $softwareCollection = [];
public function __construct(?SoftwareProfile $softwareProfile = null)
{
@ -50,11 +42,6 @@ final class SoftwareProfileInput
if($softwareProfile->getOperativeSystem()) {
$this->operativeSystem = new OperativeSystemOutput($softwareProfile->getOperativeSystem());
}
$this->softwareCollection = array_map(
fn(Software $software) => new SoftwareOutput($software),
$softwareProfile->getSoftwareCollection()->toArray()
);
}
public function createOrUpdateEntity(?SoftwareProfile $softwareProfile = null): SoftwareProfile
@ -71,18 +58,6 @@ final class SoftwareProfileInput
$softwareProfile->setOperativeSystem($this->operativeSystem->getEntity());
}
$selectedSoftware = array_map(fn(SoftwareOutput $software) => $software->getEntity(), $this->softwareCollection);
foreach ($softwareProfile->getSoftwareCollection()->toArray() as $existingSoftware) {
if (!in_array($existingSoftware, $selectedSoftware, true)) {
$softwareProfile->removeSoftwareCollection($existingSoftware);
}
}
foreach ($selectedSoftware as $software) {
$softwareProfile->addSoftwareCollection($software);
}
return $softwareProfile;
}
}

View File

@ -56,13 +56,6 @@ final class UserInput
)]
public ?int $clientsPerPage = null;
#[Groups('user:write')]
#[ApiProperty(
description: 'Idioma preferido del usuario',
example: 'es'
)]
public ?string $language = null;
#[Assert\NotNull]
#[Groups('user:write')]
#[ApiProperty(
@ -120,7 +113,6 @@ final class UserInput
$this->enabled= $user->isEnabled();
$this->groupsView = $user->getGroupsView();
$this->clientsPerPage = $user->getClientsPerPage();
$this->language = $user->getLanguage();
if ($user->getUserGroups()) {
foreach ($user->getUserGroups() as $userGroup) {
@ -145,7 +137,6 @@ final class UserInput
$user->setEnabled($this->enabled);
$user->setGroupsView($this->groupsView);
$user->setClientsPerPage($this->clientsPerPage);
$user->setLanguage($this->language);
foreach ($this->userGroups as $userGroup) {
$userGroupsToAdd[] = $userGroup->getEntity();

View File

@ -8,7 +8,6 @@ use App\Entity\Client;
use App\Entity\Partition;
use Symfony\Component\Serializer\Annotation\Groups;
use App\Dto\Output\BootServerOutput;
use App\Dto\Output\HardwareProfileOutput;
#[Get(shortName: 'Client')]
final class ClientOutput extends AbstractOutput
@ -71,13 +70,6 @@ final class ClientOutput extends AbstractOutput
)]
public ?string $netDriver = '';
#[Groups(['client:read'])]
#[ApiProperty(
description: 'La velocidad de la red',
example: 1000
)]
public ?int $netSpeed = null;
#[Groups(['client:read'])]
#[ApiProperty(
description: 'La unidad organizativa a la que pertenece el cliente',
@ -99,13 +91,6 @@ final class ClientOutput extends AbstractOutput
)]
public ?MenuOutput $menu = null;
#[Groups(['client:read'])]
#[ApiProperty(
description: 'El perfil de hardware asignado al cliente, normalmente heredado del aula y compartido con otros clientes de la misma',
example: null
)]
public ?HardwareProfileOutput $hardwareProfile = null;
#[Groups(['client:read'])]
#[ApiProperty(
description: 'El repositorio de imágenes asignado al cliente',
@ -214,7 +199,6 @@ final class ClientOutput extends AbstractOutput
$this->ip = $client->getIp();
$this->netiface = $client->getNetiface();
$this->netDriver = $client->getNetDriver();
$this->netSpeed = $client->getNetSpeed();
$this->firmwareType = $client->getFirmwareType();
if ($client->getOrganizationalUnit()) {
@ -226,9 +210,6 @@ final class ClientOutput extends AbstractOutput
)->toArray();
$this->menu = $client->getMenu() ? new MenuOutput($client->getMenu()) : null;
$this->hardwareProfile = $client->getHardwareProfile()
? new HardwareProfileOutput($client->getHardwareProfile(), includeClients: false)
: null;
$this->position = $client->getPosition();
$repository = $client->getRepository()

View File

@ -92,15 +92,8 @@ final class CommandTaskOutput extends AbstractOutput
}
$this->notes = $commandTask->getNotes();
$this->scope = $commandTask->getScope();
$rawLast = $commandTask->getLastExecution();
$this->lastExecution = $rawLast
? new \DateTime($rawLast->format('Y-m-d H:i:s'), new \DateTimeZone('UTC'))
: null;
$rawNext = $commandTask->getNextExecution();
$this->nextExecution = $rawNext
? new \DateTime($rawNext->format('Y-m-d H:i:s'), new \DateTimeZone('UTC'))
: null;
$this->lastExecution = $commandTask->getLastExecution();
$this->nextExecution = $commandTask->getNextExecution();
$this->createdAt = $commandTask->getCreatedAt();
$this->createdBy = $commandTask->getCreatedBy();
}

View File

@ -54,12 +54,7 @@ class CommandTaskScheduleOutput extends AbstractOutput
}
$this->recurrenceType = $commandTaskSchedule->getRecurrenceType();
$rawTime = $commandTaskSchedule->getExecutionTime();
$this->executionTime = $rawTime
? new \DateTime('1970-01-01 ' . $rawTime->format('H:i:s'), new \DateTimeZone('UTC'))
: null;
$this->executionTime = $commandTaskSchedule->getExecutionTime();
$this->executionDate = $commandTaskSchedule->getExecutionDate();
$this->recurrenceDetails = $commandTaskSchedule->getRecurrenceDetails();
$this->enabled = $commandTaskSchedule->isEnabled();

View File

@ -51,7 +51,7 @@ final class HardwareOutput extends AbstractOutput
$this->name = $hardware->getName();
$this->description = $hardware->getDescription();
$this->type = $hardware->getType() ? new HardwareTypeOutput($hardware->getType()) : null;
$this->type = new HardwareTypeOutput($hardware->getType());
$this->createdAt = $hardware->getCreatedAt();
$this->createdBy = $hardware->getCreatedBy();
}

View File

@ -4,7 +4,6 @@ namespace App\Dto\Output;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Get;
use App\Entity\Client;
use App\Entity\Hardware;
use App\Entity\HardwareProfile;
use Symfony\Component\Serializer\Annotation\Groups;
@ -28,10 +27,10 @@ final class HardwareProfileOutput extends AbstractOutput
#[Groups(['hardware-profile:read'])]
#[ApiProperty(
description: 'Los clientes que tienen asignado este perfil de hardware',
example: []
description: 'El cliente asociado a este perfil de hardware',
example: null
)]
public array $clients = [];
public ?ClientOutput $client = null;
#[Groups(['hardware-profile:read'])]
#[ApiProperty(
@ -54,16 +53,14 @@ final class HardwareProfileOutput extends AbstractOutput
)]
public ?string $createdBy = null;
public function __construct(HardwareProfile $hardwareProfile, bool $includeClients = true)
public function __construct(HardwareProfile $hardwareProfile, bool $includeClient = true)
{
parent::__construct($hardwareProfile);
$this->description = $hardwareProfile->getDescription();
$this->comments = $hardwareProfile->getComments();
if ($includeClients) {
$this->clients = $hardwareProfile->getClients()->map(
fn(Client $client) => new ClientOutput($client)
)->toArray();
if($includeClient && $hardwareProfile->getClient()) {
$this->client = new ClientOutput($hardwareProfile->getClient());
}
$this->hardwareCollection = $hardwareProfile->getHardwareCollection()->map(

View File

@ -24,13 +24,6 @@ class ImageImageRepositoryOutput extends AbstractOutput
)]
public ?ImageRepositoryOutput $imageRepository = null;
#[Groups(['image-image-repository:read', 'image:read'])]
#[ApiProperty(
description: 'El perfil de software detectado en esta versión de la imagen',
example: null
)]
public ?SoftwareProfileOutput $softwareProfile = null;
#[Groups(['image-image-repository:read', 'image:read'])]
#[ApiProperty(
description: 'El estado de la imagen en el repositorio',
@ -122,10 +115,6 @@ class ImageImageRepositoryOutput extends AbstractOutput
$this->imageRepository = new ImageRepositoryOutput($imageImageRepository->getRepository());
}
if ($imageImageRepository->getSoftwareProfile()) {
$this->softwareProfile = new SoftwareProfileOutput($imageImageRepository->getSoftwareProfile(), false);
}
$this->name = $imageImageRepository->getName();
$this->version = $imageImageRepository->getVersion();
$this->partitionInfo = json_decode($imageImageRepository->getPartitionInfo(), true);

View File

@ -34,6 +34,13 @@ final class ImageOutput extends AbstractOutput
)]
public ?string $type = '';
#[Groups(['image:read'])]
#[ApiProperty(
description: 'El perfil de software asociado a la imagen',
example: null
)]
public ?SoftwareProfileOutput $softwareProfile = null;
/**
* @var ImageRepositoryOutput[]|null
*/
@ -77,6 +84,7 @@ final class ImageOutput extends AbstractOutput
parent::__construct($image);
$this->name = $image->getName();
$this->softwareProfile = $image->getSoftwareProfile() ? new SoftwareProfileOutput($image->getSoftwareProfile(), false) : null;
$this->imageRepositories = $image->getImageImageRepositories()->map(
fn(ImageImageRepository $image) => new ImageImageRepositoryOutput($image)

View File

@ -109,13 +109,6 @@ final class OrganizationalUnitOutput extends AbstractOutput
)]
public ?bool $remotePc = null;
#[Groups(['organizational-unit:read'])]
#[ApiProperty(
description: 'Indica si RemotePC debe reiniciar el equipo al liberar la reserva',
example: false
)]
public ?bool $remotePcRebootOnUnreserve = null;
#[Groups(['organizational-unit:read'])]
#[ApiProperty(
description: 'Indica si está disponible según el calendario',
@ -157,7 +150,6 @@ final class OrganizationalUnitOutput extends AbstractOutput
$this->capacity = $organizationalUnit->getCapacity();
$this->type = $organizationalUnit->getType();
$this->remotePc = $organizationalUnit->isRemotePc();
$this->remotePcRebootOnUnreserve = $organizationalUnit->isRemotePcRebootOnUnreserve();
$this->available = $organizationalUnit->getRemoteCalendar() && $organizationalUnit->getRemoteCalendar()->isAvailable();
$this->networkSettings = $organizationalUnit->getNetworkSettings() ? new NetworkSettingsOutput($organizationalUnit->getNetworkSettings()) : null;
$this->remoteCalendar = $organizationalUnit->getRemoteCalendar() ? new RemoteCalendarOutput($organizationalUnit->getRemoteCalendar()) : null;

View File

@ -17,13 +17,6 @@ class PartitionOutput extends AbstractOutput
example: 1
)]
public ?int $diskNumber = null;
#[Groups(['partition:read', 'client:read'])]
#[ApiProperty(
description: 'El tipo de disco',
example: 'NVMe'
)]
public ?string $diskType = null;
#[Groups(['partition:read', 'client:read'])]
#[ApiProperty(
@ -93,7 +86,6 @@ class PartitionOutput extends AbstractOutput
parent::__construct($partition);
$this->diskNumber = $partition->getDiskNumber();
$this->diskType = $partition->getDiskType();
$this->partitionNumber = $partition->getPartitionNumber();
$this->partitionCode = $partition->getPartitionCode();
$this->size = $partition->getSize() / 1024 ;

View File

@ -12,7 +12,7 @@ use Symfony\Component\Serializer\Annotation\Groups;
#[Get(shortName: 'SoftwareProfile')]
final class SoftwareProfileOutput extends AbstractOutput
{
#[Groups(['software-profile:read', 'image:read', 'image-image-repository:read'])]
#[Groups(['software-profile:read', 'image:read'])]
#[ApiProperty(
description: 'La descripción del perfil de software',
example: 'Perfil estándar para aula de informática'

View File

@ -61,13 +61,6 @@ final class UserOutput extends AbstractOutput
)]
public ?int $clientsPerPage = null;
#[Groups(['user:read'])]
#[ApiProperty(
description: 'Idioma preferido del usuario',
example: 'es'
)]
public ?string $language = null;
#[Groups(['user:read'])]
#[ApiProperty(
description: 'Fecha de creación del usuario',
@ -91,7 +84,6 @@ final class UserOutput extends AbstractOutput
$this->enabled = $user->isEnabled();
$this->groupsView = $user->getGroupsView();
$this->clientsPerPage = $user->getClientsPerPage();
$this->language = $user->getLanguage();
$this->userGroups = $user->getUserGroups()->map(
fn(UserGroup $userGroup) => new UserGroupOutput($userGroup)

View File

@ -54,13 +54,9 @@ class Client extends AbstractEntity
#[ORM\JoinColumn( onDelete: 'SET NULL')]
private ?Menu $menu = null;
#[ORM\ManyToOne(inversedBy: 'clients')]
#[ORM\JoinColumn(onDelete: 'SET NULL')]
#[ORM\OneToOne(mappedBy: 'client', cascade: ['persist', 'remove'])]
private ?HardwareProfile $hardwareProfile = null;
#[ORM\Column(nullable: true)]
private ?int $netSpeed = null;
#[ORM\Column(nullable: true)]
private ?bool $validation = null;
@ -256,18 +252,6 @@ class Client extends AbstractEntity
return $this;
}
public function getNetSpeed(): ?int
{
return $this->netSpeed;
}
public function setNetSpeed(?int $netSpeed): static
{
$this->netSpeed = $netSpeed;
return $this;
}
public function getValidation(): ?bool
{
return $this->validation;

View File

@ -9,7 +9,7 @@ use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: CommandTaskScriptRepository::class)]
class CommandTaskScript extends AbstractEntity
{
#[ORM\Column(type: Types::TEXT, nullable: true)]
#[ORM\Column(length: 255, nullable: true)]
private ?string $content = null;
#[ORM\Column]

View File

@ -16,11 +16,9 @@ class HardwareProfile extends AbstractEntity
#[ORM\Column(length: 255, nullable: true)]
private ?string $comments = null;
/**
* @var Collection<int, Client>
*/
#[ORM\OneToMany(mappedBy: 'hardwareProfile', targetEntity: Client::class)]
private Collection $clients;
#[ORM\ManyToOne(targetEntity: Client::class, inversedBy: 'hardwareProfile')]
#[ORM\JoinColumn(nullable: false)]
private ?Client $client = null;
/**
* @var Collection<int, Hardware>
@ -32,7 +30,6 @@ class HardwareProfile extends AbstractEntity
{
parent::__construct();
$this->clients = new ArrayCollection();
$this->hardwareCollection = new ArrayCollection();
}
@ -65,31 +62,14 @@ class HardwareProfile extends AbstractEntity
return $this;
}
/**
* @return Collection<int, Client>
*/
public function getClients(): Collection
public function getClient(): ?Client
{
return $this->clients;
return $this->client;
}
public function addClient(Client $client): static
public function setClient(?Client $client): static
{
if (!$this->clients->contains($client)) {
$this->clients->add($client);
$client->setHardwareProfile($this);
}
return $this;
}
public function removeClient(Client $client): static
{
if ($this->clients->removeElement($client)) {
if ($client->getHardwareProfile() === $this) {
$client->setHardwareProfile(null);
}
}
$this->client = $client;
return $this;
}

Some files were not shown because too many files have changed in this diff Show More