Compare commits

...

151 Commits

Author SHA1 Message Date
Juan Manuel Bardallo 31fc4567ad chore(release): update changelog for 1.15.2
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
2026-10-26 15:39:25 +01:00
Juan Manuel Bardallo 3ae3bd68c5 fix(trace): trigger kill request with timeout and ignore failures to ensure cancellation 2026-10-26 15:38:00 +01:00
Juan Manuel Bardallo 28c1d48ed8 fix(trace): ignore agent error on kill and always cancel trace 2026-10-26 15:25:53 +01:00
Juan Manuel Bardallo 82b2a4e460 fix(trace): fallback to terminatescript and ensure cancellation persists even if agent is unreachable 2026-10-26 15:21:50 +01:00
Juan Manuel Bardallo d171ddb22b fix(traces): use executing client instead of image client in CreateImageAction (1.15.1)
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/tag This commit looks good Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-10-26 13:27:55 +01:00
Juan Manuel Bardallo f6311694e0 feat(plugins): add ?all=true parameter to list and toggle endpoint
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-10-23 14:35:37 +02:00
Juan Manuel Bardallo e860cf872c fix(traces): unify script execution trace status to IN_PROGRESS and restore cancel restrictions
ogcore-debian-package/pipeline/tag There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-10-22 13:56:07 +02:00
Juan Manuel Bardallo f6ff7c1e7d fix(traces): allow cancelling SENT traces and resolve SENT traces on reboot/poweroff
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-10-22 13:27:42 +02:00
Juan Manuel Bardallo 90605c7b11 feat(traces): add target_os support to pending task queue and execution service
ogcore-debian-package/pipeline/tag This commit looks good Details
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-10-22 12:55:50 +02:00
Juan Manuel Bardallo de3bd7a93a fix(plugins): support both /plugins and /api/plugins routes behind reverse proxy
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/tag This commit looks good Details
2026-10-22 11:02:03 +02:00
Juan Manuel Bardallo 7f0953b6d1 feat(plugins): implement modular plugin infrastructure and bump version to 1.13.0
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-10-22 09:40:35 +02:00
Juan Manuel Bardallo 35b75c5823 feat(agent): implement early offline detection and async command dispatching
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-10-20 10:14:29 +02:00
Juan Manuel Bardallo 4ec0603624 fix(menu-browser): resolve and persist menu fallback for clients and bump version to 1.11.3
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-10-14 12:40:43 +02:00
Juan Manuel Bardallo e5fbb0a24c fix(clients): use Count constraint instead of GreaterThan for moving clients payload validation
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
2026-10-06 14:16:32 +02:00
Juan Manuel Bardallo e8f5fe12d3 fix(remotepc): properly evaluate negative and positive calendar rules
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-10-02 14:20:20 +02:00
Juan Manuel Bardallo 6d63ca00df feat(remotepc): add reboot on unreserve configuration for UDS
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-10-02 13:57:44 +02:00
Juan Manuel Bardallo 803ce6568a docs: release version 1.10.0
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/tag This commit looks good Details
2026-09-23 14:12:14 +02:00
Juan Manuel Bardallo ea451f2f5b feat: Implement reactive task push queue in ogcore
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-09-23 13:23:36 +02:00
Juan Manuel Bardallo c486196f72 Merge branch 'devel'
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-09-18 10:33:57 +02:00
Juan Manuel Bardallo fdda972cd9 docs: update CHANGELOG.md for version 1.9.7
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-09-18 10:28:00 +02:00
Juan Manuel Bardallo 39838ff837 fix(menu): use baseUrl from query param for GET render requests to bypass proxy issues 2026-09-17 15:03:05 +02:00
Juan Manuel Bardallo ddecae613f fix(menu): replace base tag logic with direct regex rewriting of assets URLs to bypass leading slash limitations 2026-09-17 15:00:01 +02:00
Juan Manuel Bardallo 409ba24245 fix(menu): use baseUrl from frontend to avoid reverse proxy URL resolution issues 2026-09-17 14:55:23 +02:00
Juan Manuel Bardallo 7820ffe096 fix(menu): inject absolute base href in previewMenu for gui data URLs 2026-09-17 14:48:28 +02:00
Juan Manuel Bardallo e7d6398283 fix(menu): use relative base href for gui preview to bypass proxy url resolution issues 2026-09-17 14:42:30 +02:00
Juan Manuel Bardallo 6343f44305 fix(menu): inject base tag when requested by gui for proper asset preview 2026-09-17 14:36:42 +02:00
Juan Manuel Bardallo 8785aed98d fix(assets): check UploadedFile validity to prevent empty pathname errors 2026-09-17 14:27:53 +02:00
Juan Manuel Bardallo 7844d452a4 fix(assets): add error handling and check for php-zip extension during zip upload 2026-09-17 14:25:52 +02:00
Juan Manuel Bardallo de12c711b1 Merge branch 'devel'
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
ogcore-debian-package/pipeline/tag This commit looks good Details
2026-09-10 14:10:08 +02:00
Juan Manuel Bardallo a8240c5287 Fix ogboot 404 delete issue (1.9.6)
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-09-10 14:10:08 +02:00
Juan Manuel Bardallo 290cba022e Merge pull request 'Fix status webhook freezing and add TraceService finishedAt tracking' (#128) from devel into main
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/tag This commit looks good Details
Reviewed-on: #128
2026-09-04 09:54:54 +02:00
Juan Manuel Bardallo 3aa0861b84 Fix status webhook freezing and add TraceService finishedAt tracking
testing/ogcore-api/pipeline/pr-main Build queued... Details
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-09-04 09:53:25 +02:00
Juan Manuel Bardallo 3ab24ee3ef Merge pull request 'devel 1.9.4 Se guarda informacion del tipo de disco y de la velocidad de red de cada cliente' (#127) from devel into main
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/tag This commit looks good Details
Reviewed-on: #127
2026-09-01 09:42:27 +02:00
Juan Manuel Bardallo e28c8a683f Merge branch 'main' into devel
testing/ogcore-api/pipeline/pr-main Build queued... Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-09-01 09:41:52 +02:00
Juan Manuel Bardallo 3cb8ebde16 chore(release): bump version and update changelog for 1.9.4
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main Build started... Details
2026-07-31 13:46:52 +02:00
Juan Manuel Bardallo 33609081bf refactor(inventory): optimize extraction of fwt and spd in CreatePartitionService
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-31 13:40:29 +02:00
Juan Manuel Bardallo 809ecd0d37 feat(inventory): add disk_type to partition and net_speed to client
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-31 13:36:04 +02:00
Juan Manuel Bardallo a7eabc108f Merge pull request 'devel 1.9.3' (#126) from devel into main
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/tag This commit looks good Details
Reviewed-on: #126
2026-07-31 11:12:37 +02:00
Juan Manuel Bardallo 4a7034798f fix(image): prevent getRepository() on null when updating image
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-31 11:07:16 +02:00
Manuel Aranda Rosales 41e05f3824 Merge pull request 'Minor version, several changes. New release.' (#125) from devel into main
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/tag This commit looks good Details
Reviewed-on: #125
2026-07-30 13:31:11 +02:00
Manuel Aranda Rosales 8547a46779 Merge branch 'main' into devel
testing/ogcore-api/pipeline/pr-main Build started... Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-07-30 13:30:46 +02:00
Juan Manuel Bardallo 5abf8b9335 Fix(image): correct property path in repository filter
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/pr-main There was a failure building this commit Details
2026-07-30 13:11:44 +02:00
Manuel Aranda Rosales 6dd428412f Updated deploy torrent. Refactor.
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-30 13:00:02 +02:00
Juan Manuel Bardallo c29af77466 Feat(mercure): broadcast output and finishedAt in trace events for real-time logs
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-07-30 11:40:23 +02:00
Juan Manuel Bardallo bca1f4392f Fix(browser): run bootOs silently by changing command+output to command
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-30 09:49:04 +02:00
Manuel Aranda Rosales e5d6f468e3 Updated Trace role view
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-29 21:23:01 +02:00
Manuel Aranda Rosales 09eadaaad5 Updated mercure fields. Added finished_at
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-29 00:04:11 +02:00
Juan Manuel Bardallo 3ced3ced8b Docs: update CHANGELOG for git repository deletion fix
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-28 12:32:41 +02:00
Juan Manuel Bardallo 59be9044e4 Fix(OgRepository): fix serialization group in DeleteRepositoryInput
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-28 12:28:44 +02:00
Juan Manuel Bardallo cd1f7c0f23 Fix(OgRepository): fix repo deletion payload mismatch and error handling
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-28 11:02:37 +02:00
Juan Manuel Bardallo 7df739c17f Docs: update CHANGELOG for OgBoot router extraction logic and trace race condition fix
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-28 00:34:17 +02:00
Juan Manuel Bardallo f2f0e41179 Feat(OgBoot): prioritize client subnet over OU network settings for router and netmask extraction
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-28 00:32:15 +02:00
Juan Manuel Bardallo ddeea59173 Fix(RunScriptAction): default trace status to IN_PROGRESS for Windows/Linux to prevent duplicate traces in combination with ogagent
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-27 18:52:06 +02:00
Juan Manuel Bardallo e2d1483134 Fix(agent-api): prevent duplicate traces due to webhook race condition for START_SCRIPT
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-23 14:23:51 +02:00
Juan Manuel Bardallo 55ec37d024 Docs(CHANGELOG): document Trace output length fix
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-07-22 13:13:17 +02:00
Juan Manuel Bardallo 4c2e43940a Fix: change Trace output column to LONGTEXT to avoid 500 errors on large output
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-22 10:59:48 +02:00
Juan Manuel Bardallo f87ebe5c9a Fix: support mapping agent loggedin status to OS session status
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-22 10:32:13 +02:00
Juan Manuel Bardallo 2bebae09c1 Fix: unconditionally update client status on ping if it doesn't match
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-22 09:34:19 +02:00
Juan Manuel Bardallo 5144aed0df Fix: avoid hardcoding OG_LIVE status on REFRESH and RUN_SCRIPT completion
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-21 14:42:33 +02:00
Juan Manuel Bardallo a9228b0047 Fix: save script output for successful ExecScript webhooks
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-21 14:40:54 +02:00
Juan Manuel Bardallo f08f3f6ff9 fix(webhook): restaurar gestion de progreso y corregir error de sintaxis
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-20 11:25:50 +02:00
Manuel Aranda Rosales f2566bb9c9 ref 3018. Cancel multiple task
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-19 17:35:29 +02:00
Juan Manuel Bardallo d2cbc51336 refactor(webhook): consolidar procesamiento de comandos en un bloque switch
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-18 01:41:08 +02:00
Juan Manuel Bardallo 17c5c603f1 fix(webhook): restaurar parseo de particiones en EjecutarScript borrado accidentalmente
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-18 01:30:37 +02:00
Manuel Aranda Rosales cc0e45eae9 ref 3017. Fixed bug EjecutarScript webhook
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-17 11:56:39 +02:00
Manuel Aranda Rosales 52515633af ref 3016. Updated ogRepository sync
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-17 11:44:44 +02:00
Juan Manuel Bardallo 1b24414c0c docs: actualizar CHANGELOG para la version 1.9.1
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-17 10:54:52 +02:00
Juan Manuel Bardallo 170ff14bd9 feat(webhook): procesar cfg en respuestas de EjecutarScript
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
Permite que la configuración de particiones y caché se actualice automáticamente en la BBDD cuando termina la ejecución de un script en el cliente, evitando tener que encadenar refrescos manuales.
2026-07-17 10:48:55 +02:00
Manuel Aranda Rosales 22947fd44d ref 3009. Execute task right now
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-15 11:18:36 +02:00
Manuel Aranda Rosales b4907bc5e6 ref 3006. Updated creation software profile bug. 2026-07-13 10:38:56 +02:00
Manuel Aranda Rosales 3390734b10 ref 3007. Updated software profile image entity. 2026-07-13 10:38:22 +02:00
Manuel Aranda Rosales 8b78296a86 ref 2994. Hardware profile network settings . 2026-07-13 10:36:01 +02:00
Manuel Aranda Rosales ec48baebd3 ref 3005. Fixed command scheldule bug. 2026-07-13 10:32:15 +02:00
Juan Manuel Bardallo 04068ce748 Merge branch 'devel' of https://ognproject.evlt.uma.es/gitea/opengnsys/ogcore into devel
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
# Please enter a commit message to explain why this merge is necessary,
# especially if it merges an updated upstream into a topic branch.
#
# Lines starting with '#' will be ignored, and an empty message aborts
# the commit.
2026-07-09 11:06:24 +02:00
Juan Manuel Bardallo af2fa11d9b feat(deploy): remove constraint restricting deployment to clients with different partition sizes 2026-07-09 11:04:17 +02:00
Manuel Aranda Rosales 8307844596 ref 2994. Propagacion con Hardware profile.
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-07-09 10:15:09 +02:00
Manuel Aranda Rosales 1bf33e73d1 ref 2995. Actualizar roles. 2026-07-09 10:15:09 +02:00
Manuel Aranda Rosales f00e5a1292 ref 2975. Cambio de tipo en bbdd para que queda texto msa grande en los scripts. 2026-07-09 10:15:09 +02:00
Manuel Aranda Rosales 92ee730bab ref 2995. Actualizas roles. 2026-07-09 10:15:09 +02:00
Juan Manuel Bardallo 6b8cd0834b feat(organizational-unit): order children alphabetically by name
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-07-09 09:50:58 +02:00
Juan Manuel Bardallo 0acf27c0e1 feat(user): add language preference field to user profile
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
- Add language column (VARCHAR 10) to User entity
- Add language field to UserInput and UserOutput DTOs
- Expose language in JWT payload via JWTCreatedListener
- Add Doctrine migration Version20260707091500
2026-07-07 13:59:56 +02:00
Nicolas Arenas 658c939161 Merge pull request 'docs(ogcore): actualizar CHANGELOG para versión 1.9.0' (#124) from devel into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #124
2026-06-16 17:56:07 +02:00
Nicolas Arenas 78a988fb8b docs(ogcore): actualizar CHANGELOG para versión 1.9.0
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-06-16 17:53:46 +02:00
Nicolas Arenas 87e9896aa6 Merge pull request 'fix(ogcore): sistema de permisos por rol + fixes de borrado y timezone' (#123) from devel into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #123
2026-06-16 17:51:44 +02:00
Nicolas Arenas 3d0883a0bd fix(ogcore): corregir rutas de firewall y provider de DELETE en OUs
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/pr-main Build started... Details
Dos bugs introducidos en fix_permissions:

1. access_control paths incorrectos: nginx elimina el prefijo /api/ antes
   de llegar a ogcore, por lo que las rutas reales son /clients y
   /organizational-units (sin /api/). Las reglas anteriores con ^/api/clients$
   y ^/api/organizational-units$ nunca coincidían.

2. OrganizationalUnitProvider no manejaba Delete: el switch del provider
   no tenía case para Delete, devolvía null implícitamente y API Platform
   respondía 404 a cualquier usuario que intentara borrar una OU.
   Quitando el provider del DELETE, el proveedor Doctrine por defecto carga
   la entidad correctamente y la expresión security: del YAML puede evaluarse.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 11:20:43 +02:00
Juan Manuel Bardallo 024f2ace6b Corregida asociacion de perfil hardware con cliente, se usa delete cascade para que al borrar un cliente, se borre su perfil hardware asociado
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-06-16 09:17:09 +02:00
Nicolas Arenas 9d5c230a2d Merge branch 'fix_permissions' into devel
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
- Bloqueo POST /api/clients y /api/organizational-units a ou-operator y ou-minimal
- Permiso a ogLive (ROLE_OGCLIENT_API) para GET /clients
- Suite de tests funcionales de permisos por rol (PermissionsTest.php)
2026-06-15 11:57:29 +02:00
Nicolas Arenas cb3a8aa58a fix(ogcore): permitir a ogLive consultar clientes vía API key
Añade regla access_control para que ROLE_OGCLIENT_API pueda hacer GET
en /clients. Sin esta regla, ogLive no puede consultar la configuración
del equipo por IP al arrancar (el catch-all ROLE_USER bloquearía la
petición porque ogclient_api_user no tiene ese rol).

Ya existía la misma excepción para /commands.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 11:57:15 +02:00
Nicolas Arenas 9baa1120a6 fix(ogcore): normalizar timezone UTC en CommandTask DTOs 2026-06-15 11:52:44 +02:00
Nicolas Arenas 7f56b6291a fix(ogcore): permisos DELETE de OUs y borrado de clientes sin plantilla 2026-06-15 11:52:44 +02:00
Nicolas Arenas 7979d3e81c Merge remote-tracking branch 'refs/remotes/origin/devel' into devel 2026-06-15 11:23:27 +02:00
Juan Manuel Bardallo 0284654f3e Añadido un timeout de 5 segundos para detectar el estado de cada equipo en el sondeo del aula completa
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-06-12 10:27:04 +02:00
Nicolas Arenas 5ce29848f1 test(ogcore): añadir suite de tests de permisos por rol
PermissionsTest.php cubre la matriz completa de permisos:

  Sección 1 — Clientes (POST):
    - super-admin / ou-admin pueden crear (201)
    - ou-operator / ou-minimal no pueden (403)

  Sección 2 — OUs (POST):
    - super-admin / ou-admin pueden crear (201)
    - ou-operator / ou-minimal no pueden (403)

  Sección 3 — OUs (DELETE con autoría):
    - ou-admin borra la suya propia (204)
    - ou-admin no borra la de otro usuario (403)
    - super-admin borra cualquiera (204)
    - ou-operator no borra ninguna (403)

  Sección 4 — DHCP Servers:
    - super-admin puede PATCH (200)
    - ou-admin / ou-operator no pueden PATCH ni DELETE (403)

  Sección 5 — Boot Servers:
    - super-admin puede PATCH (200)
    - ou-admin / ou-operator no pueden PATCH ni DELETE (403)

  Sección 6 — Image Repositories:
    - super-admin puede crear (201)
    - ou-admin / ou-operator no pueden crear ni borrar (403)

  Sección 7 — Commands:
    - super-admin puede crear (201)
    - ou-admin / ou-operator no pueden crear, editar ni borrar (403)

OrganizationalUnitTest: reemplaza testOuOperatorCanEditOrganizationalUnitTheyCreated
(que asumía que operadores podían crear OUs) por
testOuOperatorCannotCreateOrganizationalUnit (que verifica el comportamiento correcto).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 15:37:12 +02:00
Nicolas Arenas 06bca9395e fix(ogcore): bloquear creación de clientes y OUs a nivel de firewall
Añade reglas access_control al firewall de Symfony para los endpoints
POST /api/clients y POST /api/organizational-units, restringiendo el
acceso a ROLE_SUPER_ADMIN y ROLE_ORGANIZATIONAL_UNIT_ADMIN.

La comprobación a nivel de firewall se ejecuta antes de que API Platform
procese la petición (antes de deserialización y validación del DTO), lo
que garantiza un HTTP 403 inmediato sin necesidad de que el cuerpo de la
petición sea válido.

Las reglas usan el ancla $ para que no afecten a sub-rutas como
/api/clients/server/reboot, /api/clients/server/boot-client, etc.
2026-05-27 14:45:55 +02:00
Nicolas Arenas ab1a7c2d11 fix(ogcore): mover seguridad de creación/borrado a los processors
- ClientProcessor: añade comprobación inline en processCreateOrUpdate
  para bloquear (403) creación de clientes a ROLE_ORGANIZATIONAL_UNIT_OPERATOR
  y roles inferiores. Añade Security al constructor.

- OrganizationalUnitProcessor: mueve el bloqueo de creación al inicio de
  processCreateOrUpdate (antes de validate/save) para que el 403 se devuelva
  sin persistir datos. Separa la lógica de añadir la OU a la lista del usuario.

- OrganizationalUnitProcessor.processDelete: corrige bug de nombre de variable
  ($user apuntaba a una OU); añade comprobación de autoría via createdBy para
  que solo el creador o super-admin pueda borrar la OU (403 en caso contrario).

Motivo del cambio: la expresión security: de API Platform YAML no se evaluaba
antes de la validación del DTO en AP 3.4 para operaciones POST sin provider
explícito, resultando en 422 en lugar del esperado 403.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 14:20:02 +02:00
Nicolas Arenas b1903ea321 fix(ogcore): restringir creacion de OUs y clientes a ou-admin y superior
El POST de OrganizationalUnit y Client queda restringido a
ROLE_SUPER_ADMIN o ROLE_ORGANIZATIONAL_UNIT_ADMIN. Los operadores
(ROLE_ORGANIZATIONAL_UNIT_OPERATOR) ya no pueden crear aulas ni
clientes via API.
2026-05-27 12:03:43 +02:00
Nicolas Arenas 6d35163b3f fix(ogcore): restringir escritura de infraestructura a ROLE_SUPER_ADMIN
Las operaciones de creacion, edicion y eliminacion de servidores DHCP,
Boot, Subredes, Comandos y Repositorios de imagenes quedan restringidas
a ROLE_SUPER_ADMIN. Las operaciones de lectura siguen accesibles a
cualquier usuario autenticado.
2026-05-26 15:21:02 +02:00
Nicolas Arenas 203675e7ad fix(ogcore): corregir permisos de edición de aulas para ou-admin y ou-operator
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
- OrganizationalUnitProcessor: tras crear una OU (POST), añade
  automáticamente la nueva OU a allowedOrganizationalUnits del
  usuario creador (si no es SUPER_ADMIN), para que pueda verla
  y editarla de inmediato.
- OrganizationalUnitVoter: amplía la comprobación de
  ORGANIZATIONAL_UNIT_VIEW para incluir descendientes de las OUs
  permitidas, alineando el voter con la lógica de
  UserAllowedOrganizationalUnitExtension.
2026-05-26 14:34:26 +02:00
Nicolas Arenas a5f1434bc4 Merge pull request 'devel' (#122) from devel into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #122
2026-05-22 19:51:12 +02:00
Nicolas Arenas cb182d98e9 feat(ogcore): ordenar aulas y centros alfabéticamente por defecto
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/pr-main There was a failure building this commit Details
Añade orden ascendente por nombre en el recurso OrganizationalUnit
para que el listado de aulas y centros se devuelva siempre en orden
alfabético sin necesidad de parámetros adicionales en la petición.
2026-05-22 19:41:09 +02:00
Nicolas Arenas 0ea21e0414 devel (#121)
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
## feat(ogcore): devel → main — WoL broadcast mejorado y corrección journal-pull

## Resumen

- **Mejora WoL (Wake-on-LAN):** `WoLAction` ahora calcula la IP de broadcast correcta
  para `wakeonlan`. Prioriza la subred configurada en ogDHCP, luego la máscara de red
  de la OU, y finalmente usa el broadcast por defecto del comando. Evita envíos WoL a
  subredes incorrectas en entornos multi-subred.

- **Corrección journal-pull:** Se corrige la recogida de logs para máquinas con journal
  muy activo que producían el error `header out-of-date`. Cambios:
  - `journal-pull@.service`: modo `--split-mode=host` con salida por directorio (por IP),
    `boot=0` para descargar solo el boot actual (evita descargar histórico de GBs), y
    `Restart=always` para reconectar tras cierre limpio.
  - `DiskLogsAction`: adaptado a directorio (`--directory`) en lugar de fichero (`.journal`),
    usando `is_dir()` en lugar de `file_exists()`.

## Archivos modificados

| Archivo | Cambio |
|---|---|
| `src/Controller/OgRepository/WoLAction.php` | Cálculo dinámico de IP broadcast |
| `src/Controller/System/DiskLogsAction.php` | Adaptación a directorio de journal |
| `etc/systemd/system/journal-pull@.service` | Parámetros de reconexión y split-mode |
| `CHANGELOG.md` | Actualizado |

## Test plan

- [ ] Enviar WoL a una máquina en una subred distinta a la del servidor y verificar que llega correctamente
- [ ] Enviar WoL sin ogDHCP activo y verificar fallback a máscara de OU
- [ ] Verificar que `DiskLogsAction` descarga logs correctamente en máquinas con journal activo
- [ ] Comprobar que `journal-pull@.service` reconecta automáticamente tras cierre del stream

Co-authored-by: Nicolas Arenas <nicolas.arenas@qindel.com>
Co-authored-by: jmbardallo <juanmanuel.bardallo@sic.uhu.es>
Reviewed-on: #121
2026-05-22 17:22:30 +02:00
Juan Manuel Bardallo e5a8a43a4b 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
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main There was a failure building this commit Details
2026-05-22 12:59:52 +02:00
Nicolas Arenas 6082ac1281 Merge pull request 'fix(ogcore): corregir sistema journal-pull para máquinas con journal activo' (#120) from fix_logs into devel
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #120
2026-05-20 10:38:32 +02:00
Nicolas Arenas c05ccc4f37 fix(ogcore): corregir sistema journal-pull para máquinas con journal activo
testing/ogcore-api/pipeline/pr-devel Build started... Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
- journal-pull@.service: cambio a --split-mode=host con salida a directorio
  por IP para evitar "header out-of-date" en máquinas con journal muy activo;
  añadido boot=0 para descargar solo el boot actual y evitar descargar
  gigabytes de histórico; Restart=always para reconectar tras cierre limpio
- DiskLogsAction: adaptado a directorio (--directory) en lugar de fichero
  (.journal); usa is_dir() en lugar de file_exists()
2026-05-20 10:37:04 +02:00
Nicolas Arenas 0b82295fa1 Merge pull request 'feat(ogcore): infraestructura journal-pull y endpoint de logs de disco' (#119) from devel into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #119
2026-05-18 15:50:06 +02:00
Juan Manuel Bardallo 9ca7374847 Merge pull request 'Modificada acción RemoveCacheImage para montar la cache antes de intentar eliminar la imagen' (#118) from delete-cache-image into devel
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/pr-main There was a failure building this commit Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
Reviewed-on: #118
2026-05-18 14:12:07 +02:00
Juan Manuel Bardallo a164806a3d Modificada acción RemoveCacheImage para montar la cache antes de intentar eliminar la imagen
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-devel Build queued... Details
2026-05-18 14:07:31 +02:00
Juan Manuel Bardallo b04be50c1f Merge pull request 'import-legacy' (#117) from import-legacy into devel
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #117
2026-05-18 13:44:42 +02:00
Juan Manuel Bardallo 0016b96e77 Resuelve conflicto de fusión en CHANGELOG.md
testing/ogcore-api/pipeline/pr-devel Build started... Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-18 13:43:30 +02:00
Juan Manuel Bardallo 49efbaae1f Merge pull request 'Corregido fallo setRemotePc en la entidad Imagen al sincronizar un repositorio' (#116) from setRemotePc-problem into devel
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #116
2026-05-18 13:39:39 +02:00
Juan Manuel Bardallo 17f8a897fa Corregido fallo setRemotePc en la entidad Imagen al sincronizar un repositorio
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-devel Build started... Details
2026-05-18 13:32:48 +02:00
Nicolas Arenas 513a0cba81 Add logrotate for clients
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-18 12:58:15 +02:00
Nicolas Arenas 00107d04de Add clients log rotation
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-18 12:52:37 +02:00
Nicolas Arenas 11122db156 Revert logrotate change for components journal 2026-05-18 12:49:29 +02:00
Nicolas Arenas ebb6edf161 Update changelog
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-18 12:29:09 +02:00
Nicolas Arenas a35d49e483 Updted CHANGELOG.md
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-18 12:09:08 +02:00
Nicolas Arenas 34582d5199 Updated CHANGELOG.md
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-18 11:48:50 +02:00
Nicolas Arenas d20e1b2789 fix(ogcore): robustez y rotación de logs en infraestructura journal-pull
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
- journal-pull@.service: Restart=always para reconectar tras salida limpia,
  ExecStartPre elimina el fichero solo si está vacío para evitar cursor inválido
- JournalPullSubscriber: protección contra borrado de IP compartida entre
  componentes al eliminar un servidor; comprueba que ninguna otra entidad
  BootServer, DhcpServer o ImageRepository usa la misma IP antes de
  eliminarla de journal-pull-sources.conf
- logrotate.d/journal-pull: rotación diaria con 10 días de retención para
  los ficheros de journal remoto; nocompress para ficheros binarios;
  para/arranca los servicios journal-pull@ durante la rotación
- debian/control: añadidos logrotate y systemd-journal-remote como dependencias
- debian/ogcore.postinst: enlace de logrotate config, permisos 775 en api/var/
2026-05-18 11:31:37 +02:00
Nicolas Arenas 45bb270198 update CHANGELOG.md
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-14 21:46:34 +02:00
Nicolas Arenas 6099f6be4b feat(oggui): soporte de múltiples SYSLOG_IDENTIFIER en visor de logs de disco
- StatusLogsComponent: @Input identifiers[] en lugar de identifier string,
  parseo de entries JSON estructurado con formato [timestamp] ID: mensaje
- Templates ogboot, ogdhcp, ogrepository, ogcore-status: identifiers correctos
  por componente y host basado en IP en lugar de nombre del servidor
- Añadidos métodos getSelectedXxxIp() en ogboot, ogdhcp y ogrepository status
2026-05-14 21:39:33 +02:00
Nicolas Arenas 3c4d179c86 add remote journal as dependency
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-14 19:07:09 +02:00
Nicolas Arenas f23aeda308 Fix non_interaction problem in ogcore
ogcore-debian-package/pipeline/head This commit looks good Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-14 18:51:47 +02:00
Nicolas Arenas 98ba1ff94b fix Jenkins
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
2026-05-14 17:45:42 +02:00
Nicolas Arenas 341f10fc97 Testing devel
ogcore-debian-package/pipeline/head There was a failure building this commit Details
2026-05-14 17:36:12 +02:00
Juan Manuel Bardallo 2ac9d27d97 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
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-14 14:42:16 +02:00
Juan Manuel Bardallo 935561e399 Creado endpoint para mostrar logs desde disco de los distintos componentes de OG
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-14 13:24:15 +02:00
Juan Manuel Bardallo 02f5d5248a Creado endpoint para mostrar logs desde disco de los distintos componentes de OG 2026-05-14 13:22:57 +02:00
Juan Manuel Bardallo d2b7b0265a Creado endpoint para mostrar logs desde disco de los distintos componentes de OG
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-14 13:18:10 +02:00
Nicolas Arenas fb6e3c0e53 Merge pull request 'fix(ogcore): corregido error al importar imagen desde repositorio' (#115) from import_image into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #115
2026-05-14 10:27:42 +02:00
Nicolas Arenas 71e7b8a129 fix(ogcore): corregido error al importar imagen desde repositorio
testing/ogcore-api/pipeline/pr-main Build started... Details
testing/ogcore-api/pipeline/head There was a failure building this commit Details
- Eliminada llamada a setRemotePc() en ImportAction, método inexistente
  desde que la propiedad remotePc fue eliminada de la entidad Image en v1.7.0
- Actualizado CHANGELOG.md con entrada 1.7.11
2026-05-14 10:26:13 +02:00
Juan Manuel Bardallo 856080083b Merge pull request 'Modificado setClientBootMode para crear una traza en caso de ejecución en modo temporal,' (#114) from setbootmode into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #114
2026-05-13 15:00:28 +02:00
Juan Manuel Bardallo 65bfe26833 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
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
2026-05-13 14:51:48 +02:00
Juan Manuel Bardallo 01d39e00a5 Merge pull request '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.' (#113) from setbootmode into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #113
2026-05-12 14:57:15 +02:00
Juan Manuel Bardallo 14bfc44a38 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.
testing/ogcore-api/pipeline/head Build started... Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
2026-05-12 14:53:50 +02:00
Juan Manuel Bardallo 2d6419107a Merge pull request 'Al importar clientes se inicializan con estado off' (#112) from import-legacy into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #112
2026-05-11 10:32:20 +02:00
Juan Manuel Bardallo a013527f57 Al importar clientes se inicializan con estado off
testing/ogcore-api/pipeline/head Build started... Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
2026-05-11 10:30:41 +02:00
Juan Manuel Bardallo 1e322a5286 Merge pull request 'Mejorado comando ImportLegacy y creada ruta api para invocarlo desde la consola web, controla errores e informa de cambios a través de mercure' (#111) from import-legacy into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #111
2026-05-08 15:40:20 +02:00
Juan Manuel Bardallo a0c871add5 Mejorado comando ImportLegacy y creada ruta api para invocarlo desde la consola web, controla errores e informa de cambios a través de mercure
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
2026-05-08 15:36:57 +02:00
Juan Manuel Bardallo 7baacb820f Merge pull request 'import-legacy' (#110) from import-legacy into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #110
2026-05-08 10:39:34 +02:00
Juan Manuel Bardallo 53f22f3b21 eliminada relación de los perfiles software y los softwares con las OU, en la nueva version no existe dicha relacion
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
2026-05-08 10:37:41 +02:00
Juan Manuel Bardallo 1dca0f0194 Creado importador completo de la base de datos Og 1.1 a Og 3.0, usa los comandos migrate ya creados anteriormente
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-08 10:17:51 +02:00
Nicolas Arenas dbf54ed81a Merge pull request 'feat(ogcore): update client status from agent heartbeat busy field' (#109) from notify_ogagent_status into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #109
2026-05-08 07:10:05 +02:00
Nicolas Arenas 90f06de0a0 feat(ogcore): update client status from agent heartbeat busy field
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main There was a failure building this commit Details
- StatusController: process 'busy' and 'st' fields from agent heartbeat
  to keep client status in sync without waiting for a command response.
  busy:true sets BUSY; busy:false reverts to og-live/linux/windows/macos
  based on the 'st' field sent by the agent
- StatusController: add detailed logging for all status transitions
  (heartbeat and REBOOT/POWEROFF) visible via journalctl -t ogcore
- PowerOffAction, RebootAction: distinguish HTTP 409 (agent busy) from
  500 (agent error) and enqueue the command in both cases
2026-05-08 07:03:08 +02:00
Manuel Aranda Rosales c846a7b824 Merge pull request 'Updated changelog' (#108) from develop into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #108
2026-05-07 22:29:04 +02:00
Manuel Aranda Rosales e2fedd38a9 Merge branch 'main' into develop
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main Build queued... Details
2026-05-07 22:26:59 +02:00
Manuel Aranda Rosales 0225e9c0e7 updated changelog
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-07 22:24:58 +02:00
Manuel Aranda Rosales 15e9fa796d Merge pull request 'Fixed typo disk logs. Fixed scope in task.' (#107) from develop into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #107
2026-05-06 17:35:25 +02:00
Manuel Aranda Rosales 99e4c02411 Fixed OU scope task
testing/ogcore-api/pipeline/head There was a failure building this commit Details
testing/ogcore-api/pipeline/pr-main There was a failure building this commit Details
2026-05-06 17:34:21 +02:00
Manuel Aranda Rosales 4a97bc8aff Merge branch 'main' into develop
testing/ogcore-api/pipeline/head There was a failure building this commit Details
2026-05-06 17:28:29 +02:00
Manuel Aranda Rosales 1915649d17 Fixed typo disk logs 2026-05-06 17:28:11 +02:00
Manuel Aranda Rosales c1da9387da Merge pull request 'fix(ogcore): fix scheduled task execution and UTC timezone handling' (#106) from fix_scheduled_tasks into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details
Reviewed-on: #106
2026-05-06 17:26:56 +02:00
140 changed files with 6500 additions and 1749 deletions

View File

@ -1,5 +1,279 @@
# 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
- Corregido el scope de OU en tareas programadas
- Corregido error tipográfico en logs de disco
## [1.7.4] - 2026-05-05
### Added
- Nuevo endpoint para consultar logs de disco
### Fixed
- Eliminado el estado 'disconnected' del endpoint de estado de equipos
## [1.7.3] - 2026-05-05
### Fixed
- Modificada funcion para borrar imagen de cache, no se hace usando la partición que contenga un deploy de imagen, se borra el fichero real de la cache

View File

@ -61,6 +61,19 @@ 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 {
@ -96,6 +109,19 @@ 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 {
@ -108,6 +134,13 @@ 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,7 +54,8 @@
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
"App\\Tests\\": "tests/",
"Functional\\": "tests/Functional/"
}
},
"replace": {

View File

@ -13,17 +13,22 @@ 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: ~
ApiPlatform\Metadata\Delete: ~
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
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
@ -32,6 +37,7 @@ 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,7 +24,8 @@ resources:
provider: App\State\Provider\ClientProvider
validationContext:
groups: [ 'client:patch' ]
ApiPlatform\Metadata\Post: ~
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: ~
delete_multiple_clients:

View File

@ -20,11 +20,15 @@ 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: ~
ApiPlatform\Metadata\Delete: ~
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
command_execute:
class: ApiPlatform\Metadata\Post

View File

@ -24,6 +24,13 @@ 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,19 +15,24 @@ 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: ~
ApiPlatform\Metadata\Delete: ~
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
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,11 +18,15 @@ 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: ~
ApiPlatform\Metadata\Delete: ~
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
image_ogrepository_sync:
shortName: OgRepository Server

View File

@ -1,5 +1,6 @@
resources:
App\Entity\OrganizationalUnit:
order: { name: 'ASC' }
processor: App\State\Processor\OrganizationalUnitProcessor
output: App\Dto\Output\OrganizationalUnitOutput
input: App\Dto\Input\OrganizationalUnitInput
@ -25,8 +26,11 @@ resources:
provider: App\State\Provider\OrganizationalUnitProvider
validationContext:
groups: ['organizational-unit:patch' ]
ApiPlatform\Metadata\Post: ~
ApiPlatform\Metadata\Delete: ~
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.'
change_parent:
class: ApiPlatform\Metadata\Post
method: POST

View File

@ -17,11 +17,15 @@ 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: ~
ApiPlatform\Metadata\Delete: ~
ApiPlatform\Metadata\Post:
security: 'is_granted("ROLE_SUPER_ADMIN")'
ApiPlatform\Metadata\Delete:
security: 'is_granted("ROLE_SUPER_ADMIN")'
get_subnet:
@ -39,6 +43,7 @@ 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
@ -48,6 +53,7 @@ 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
@ -57,6 +63,7 @@ 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
@ -66,6 +73,7 @@ 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
@ -84,6 +92,7 @@ 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
@ -94,6 +103,7 @@ 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
@ -103,6 +113,7 @@ 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
@ -113,6 +124,7 @@ 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,6 +39,11 @@ 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' } ]
arguments: [ { 'id': 'exact', 'name': 'partial', 'clients.id': 'exact' } ]
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
php8.3-xml, php8.3-zip, mercure, systemd-journal-remote, logrotate
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
php bin/console lexik:jwt:generate-keypair --overwrite --no-interaction
echo ">>> Creando base de datos"
php bin/console doctrine:database:create --if-not-exists
@ -79,12 +79,28 @@ 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
@ -143,8 +159,21 @@ 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
@ -159,6 +188,10 @@ 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

@ -0,0 +1,30 @@
#!/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

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

View File

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

View File

@ -0,0 +1,7 @@
[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

@ -0,0 +1,15 @@
[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

@ -0,0 +1,26 @@
<?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

@ -0,0 +1,33 @@
<?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

@ -0,0 +1,26 @@
<?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

@ -0,0 +1,29 @@
<?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

@ -0,0 +1,42 @@
<?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

@ -0,0 +1,41 @@
<?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

@ -0,0 +1,26 @@
<?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

@ -0,0 +1,33 @@
<?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

@ -0,0 +1,31 @@
<?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

@ -0,0 +1,29 @@
<?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,26 +4,11 @@ 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;
@ -37,13 +22,7 @@ class ExecutePendingTracesCommand extends Command
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
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 PendingTraceExecutionService $pendingTraceExecutionService,
private readonly LoggerInterface $logger,
) {
parent::__construct();
@ -84,10 +63,15 @@ 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->executeTrace($trace);
$result = $this->pendingTraceExecutionService->executeTrace($trace);
if ($result) {
$processedCount++;
@ -99,11 +83,6 @@ 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);
}
}
@ -115,439 +94,4 @@ 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

@ -0,0 +1,356 @@
<?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,6 +3,7 @@
namespace App\Command\Migration;
use App\Entity\Client;
use App\Model\ClientStatus;
use App\Entity\HardwareProfile;
use App\Entity\OrganizationalUnit;
use App\Model\OrganizationalUnitTypes;
@ -28,7 +29,7 @@ class MigrateClientsCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$oldDatabaseEntityManager = $this->entityManager;
$clientRepository = $this->entityManager->getRepository(Client::class);
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
@ -43,52 +44,89 @@ class MigrateClientsCommand extends Command
$rsmClients->addScalarResult('ip', 'ip');
$rsmClients->addScalarResult('netiface', 'netiface');
$rsmClients->addScalarResult('netdriver', 'netdriver');
$rsmClients->addScalarResult('idperfilhard', 'ordenadores.idperfilhard');
$rsmClients->addScalarResult('grupoid', 'ordenadores.grupoid');
$rsmClients->addScalarResult('idaula', 'ordenadores.idaula');
$rsmClients->addScalarResult('idperfilhard', 'idperfilhard');
$rsmClients->addScalarResult('grupoid', 'grupoid');
$rsmClients->addScalarResult('idaula', 'idaula');
$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);
$clientsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idordenador, nombreordenador, numserie, ip, mac, netiface, netdriver, idaula, grupoid, idperfilhard FROM ordenadores', $rsmClients);
$clients = $clientsQuery->getResult();
/** Ordenadores **/
$output->writeln("CLIENTES TOTAL: ". count($clients));
$count = 0;
foreach ($clients as $client){
$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]);
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;
}
}
$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,6 +2,7 @@
namespace App\Command\Migration;
use App\Entity\Client;
use App\Entity\Hardware;
use App\Entity\HardwareProfile;
use App\Entity\HardwareType;
@ -29,8 +30,9 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
try {
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
$hardwareProfileRepository = $this->entityManager->getRepository(HardwareProfile::class);
@ -57,6 +59,7 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
$this->entityManager->persist($hardwareProfileEntity);
}
$this->entityManager->flush();
/** Obtener los hardware de la base de datos antigua **/
$rsmHardware = new ResultSetMapping();
@ -95,66 +98,79 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
$this->entityManager->persist($hardwareEntity);
}
$this->entityManager->flush();
/** 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');
/**
* 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.
**/
$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 **/
// 1. Get legacy profile-to-hardware relations
$rsmHardwareProfilesRelation = new ResultSetMapping();
$rsmHardwareProfilesRelation->addScalarResult('idperfilhard', 'idperfilhard');
$rsmHardwareProfilesRelation->addScalarResult('idhardware', 'idhardware');
$hardwareProfilesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilhard, idhardware FROM perfileshard_hardwares', $rsmHardwareProfilesRelation);
$hardwareProfileRelations = $hardwareProfilesQuery->getResult();
$hardwareProfileRelationsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilhard, idhardware FROM perfileshard_hardwares', $rsmHardwareProfilesRelation);
$hardwareProfileRelations = $hardwareProfileRelationsQuery->getResult();
$output->writeln("PERFILES HARDWARE RELACIONES TOTAL: ". count($hardwareProfileRelations));
foreach ($hardwareProfileRelations as $hardwareProfileRelation){
$hardwareProfileEntity = $hardwareProfileRepository->findOneBy(['migrationId' => $hardwareProfileRelation['idperfilhard']]);
$hardwareEntity = $hardwareRepository->findOneBy(['migrationId' => $hardwareProfileRelation['idhardware']]);
$profileItemsMap = [];
foreach ($hardwareProfileRelations as $rel) {
$profileItemsMap[$rel['idperfilhard']][] = $rel['idhardware'];
}
if ($hardwareProfileEntity && $hardwareEntity){
$hardwareProfileEntity->addHardwareCollection($hardwareEntity);
$this->entityManager->persist($hardwareProfileEntity);
// 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();
}
}
$this->entityManager->flush();
return Command::SUCCESS;
return Command::SUCCESS;
} catch (\Throwable $e) {
$output->writeln("<error>FATAL ERROR IN HARDWARE COMMAND: " . $e->getMessage() . "</error>");
$output->writeln($e->getTraceAsString());
return Command::FAILURE;
}
}
}

View File

@ -7,6 +7,7 @@ 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;
@ -32,7 +33,7 @@ class MigrateImagesCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$oldDatabaseEntityManager = $this->entityManager;
$imagesRepository = $this->entityManager->getRepository(Image::class);
$clientRepository = $this->entityManager->getRepository(Client::class);
@ -80,16 +81,20 @@ class MigrateImagesCommand extends Command
$imageEntity->setMigrationId((string) $image['idimagen']);
$imageEntity->setName($image['nombreca']);
$imageEntity->setClient($clientEntity);
//$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']);
}
$imageEntity->setType('monolithic');
$imageEntity->setIsGlobal(false);
$this->entityManager->persist($imageEntity);
$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);
}
$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->doctrine->getManager('og_1');
$oldDatabaseEntityManager = $this->entityManager;
$osRepository = $this->entityManager->getRepository(OperativeSystem::class);

View File

@ -24,172 +24,235 @@ class MigrateOrganizationalUnitCommand extends Command
parent::__construct();
}
private array $seenNames = [];
protected function execute(InputInterface $input, OutputInterface $output): int
{
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$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');
try {
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->entityManager;
$centersQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idcentro, nombrecentro, comentarios FROM centros', $rsmCenters);
$centers = $centersQuery->getResult();
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
/** 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');
/** Centros **/
$rsmCenters = new ResultSetMapping();
$rsmCenters->addScalarResult('idcentro', 'idcentro');
$rsmCenters->addScalarResult('nombrecentro', 'nombrecentro');
$rsmCenters->addScalarResult('comentarios', 'comentarios');
$groupsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idgrupo, nombregrupo, grupos.comentarios, grupos.idcentro FROM grupos LEFT JOIN centros ON grupos.idcentro = centros.idcentro', $rsmGroups);
$groups = $groupsQuery->getResult();
$centersQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idcentro, nombrecentro, comentarios FROM centros', $rsmCenters);
$centers = $centersQuery->getResult();
/** 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');
$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']);
$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;
$centerOrganizationalUnit->setName($name);
$centerOrganizationalUnit->setComments($center['comentarios']);
$this->entityManager->persist($centerOrganizationalUnit);
}
}
$this->entityManager->flush();
$this->entityManager->flush();
/** 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']);
/** 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);
}
$groupPcOrganizationalUnit->setType(OrganizationalUnitTypes::CLASSROOMS_GROUP);
$center = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$group['grupos.idcentro']]);
$center = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$group['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 **/
$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']);
/** 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']);
$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();
$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']);
}
/** Grupos de ordenadores **/
$rsmClientGroups = new ResultSetMapping();
$rsmClientGroups->addScalarResult('idgrupo', 'idgrupo');
$rsmClientGroups->addScalarResult('nombregrupoordenador', 'nombregrupoordenador');
$rsmClientGroups->addScalarResult('comentarios', 'comentarios');
$rsmClientGroups->addScalarResult('idaula', 'idaula');
$this->entityManager->flush();
$clientGroupsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idgrupo, nombregrupoordenador, comentarios, idaula FROM gruposordenadores', $rsmClientGroups);
$clientGroups = $clientGroupsQuery->getResult();
/** 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']);
$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);
}
$groupPcOrganizationalUnit->setType(OrganizationalUnitTypes::CLIENTS_GROUP);
$room = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::CLASSROOM.'-'.$clientGroup['gruposordenadores.idaula']]);
$room = $organizationalUnitRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::CLASSROOM.'-'.$clientGroup['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();
$this->entityManager->flush();
return 1;
return Command::SUCCESS;
} catch (\Throwable $e) {
$output->writeln("<error>FATAL ERROR IN COMMAND: " . $e->getMessage() . "</error>");
$output->writeln($e->getTraceAsString());
return Command::FAILURE;
}
}
}

View File

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

View File

@ -33,7 +33,7 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
/** @var EntityManagerInterface $oldDatabaseEntityManager */
$oldDatabaseEntityManager = $this->doctrine->getManager('og_1');
$oldDatabaseEntityManager = $this->entityManager;
$organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
$operativeSystemRepository = $this->entityManager->getRepository(OperativeSystem::class);
@ -71,32 +71,18 @@ 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', 'perfilessoft.comentarios');
$rsmSoftwareProfiles->addScalarResult('grupoid', 'perfilessoft.grupoid');
$rsmSoftwareProfiles->addScalarResult('idcentro', 'perfilessoft.idcentro');
$rsmSoftwareProfiles->addScalarResult('idnombreso', 'perfilessoft.idnombreso');
$rsmSoftwareProfiles->addScalarResult('comentarios', 'comentarios');
$rsmSoftwareProfiles->addScalarResult('idnombreso', 'idnombreso');
$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);
$softwareProfilesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idperfilsoft, descripcion, comentarios, idnombreso FROM perfilessoft', $rsmSoftwareProfiles);
$softwareProfiles = $softwareProfilesQuery->getResult();
/** Perfiles software **/
@ -108,21 +94,10 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
$softwareProfileEntity = new SoftwareProfile();
$softwareProfileEntity->setMigrationId($softwareProfile['idperfilsoft']);
$softwareProfileEntity->setDescription($softwareProfile['descripcion']);
$softwareProfileEntity->setComments($softwareProfile['perfilessoft.comentarios']);
$softwareProfileEntity->setComments($softwareProfile['comentarios']);
}
$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']]);
$operativeSystem = $operativeSystemRepository->findOneBy(['migrationId' => $softwareProfile['idnombreso']]);
if ($operativeSystem){
$softwareProfileEntity->setOperativeSystem($operativeSystem);
@ -130,6 +105,7 @@ 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

@ -0,0 +1,114 @@
<?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,11 +17,10 @@ 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;
@ -34,11 +33,13 @@ class RunScheduledCommandTasksCommand extends Command
{
public function __construct(
private readonly CommandTaskRepository $commandTaskRepository,
private readonly ClientRepository $clientRepository,
private readonly EntityManagerInterface $entityManager,
private readonly RunScriptAction $runScriptAction,
private readonly DeployImageAction $deployImageAction,
private readonly CreateImageAction $createImageAction,
private readonly PartitionAssistantAction $partitionAssistantAction,
private readonly CommandTaskTraceCreator $commandTaskTraceCreator,
)
{
parent::__construct();
@ -76,15 +77,15 @@ class RunScheduledCommandTasksCommand extends Command
if ($isDue && $notYetExecuted) {
$output->writeln("Ejecutando tarea: " . $task->getName());
$scripts = $task->getCommandTaskScripts()->toArray();
usort($scripts, fn($a, $b) => $a->getExecutionOrder() <=> $b->getExecutionOrder());
foreach ($scripts as $script) {
$output->writeln(" - Creando traza para script de tipo {$script->getType()} con orden {$script->getExecutionOrder()}");
$this->createTraceForScript($script, $task, $output);
if ($task->getScope() !== 'clients') {
$ou = $task->getOrganizationalUnit();
$clients = $ou ? $this->clientRepository->findClientsByOrganizationalUnitAndDescendants($ou->getId()) : [];
} else {
$clients = $task->getClients();
}
$this->commandTaskTraceCreator->createPendingTraces($task, $clients);
$task->setLastExecution(new \DateTimeImmutable('now', new \DateTimeZone('UTC')));
$task->setNextExecution($task->calculateNextExecutionDate());
@ -96,126 +97,6 @@ class RunScheduledCommandTasksCommand extends Command
return Command::SUCCESS;
}
private function createTraceForScript($script, CommandTask $task, OutputInterface $output): void
{
$scriptParameters = $script->getParameters();
if ($task->getScope() !== 'clients') {
$clients = $task->getOrganizationalUnit()?->getClients();
} 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,6 +86,8 @@ 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);
@ -108,13 +110,25 @@ class AssetManagerController extends AbstractController {
$filesystem->mkdir($extractDir, 0755);
}
$zip = new ZipArchive();
if ($zip->open($file->getPathname()) === true) {
$zip->extractTo($extractDir);
$zip->close();
$response = new JsonResponse(['message' => 'ZIP extraído correctamente.']);
if (!class_exists('ZipArchive')) {
$response = new JsonResponse(['message' => 'Falta la extensión php-zip en el servidor.'], Response::HTTP_INTERNAL_SERVER_ERROR);
} else {
$response = new JsonResponse(['message' => 'Error al extraer ZIP.'], Response::HTTP_INTERNAL_SERVER_ERROR);
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);
}
}
} else {
try {

View File

@ -5,7 +5,9 @@ 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;
@ -14,22 +16,45 @@ 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
{
foreach ($input->traces as $trace) {
/** @var Trace $trace */
$trace = $trace->getEntity();
$cancelled = [];
$failed = [];
$trace->setStatus(TraceStatus::CANCELLED);
$this->entityManager->persist($trace);
foreach ($input->traces as $traceOutput) {
/** @var Trace $trace */
$trace = $traceOutput->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()];
}
}
$this->entityManager->flush();
return new JsonResponse(data: 'Traces cancelled successfully', status: Response::HTTP_OK);
return new JsonResponse(
data: ['cancelled' => $cancelled, 'failed' => $failed],
status: Response::HTTP_OK
);
}
}
}

View File

@ -0,0 +1,32 @@
<?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,6 +28,8 @@ 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,
@ -87,160 +89,209 @@ class DeployImageAction extends AbstractController
private function handleUnicastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
{
$clientJobs = [];
foreach ($input->clients as $client) {
try {
$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('Error deploying to client (unicast)', [
'client_uuid' => $client->getEntity()->getUuid(),
'error' => $e->getMessage()
]);
if ($input->queue) {
$inputData = $this->createInputData($input, $image, $client->getEntity());
$this->createService->__invoke($client->getEntity(), CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
continue;
}
}
return $clientJobs;
return $this->processDeployments($input, $image, [], 'unicast', $trace);
}
private function handleMulticastDeployment(DeployImageInput $input, ImageImageRepository $image, ?Trace $trace = null): array
{
$clientJobs = [];
$repositoryErrors = $this->prepareRepositoryTransmissions($input, $image, 'multicast');
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;
}
}
return $clientJobs;
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 {
$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;
}
$jobId = $this->processDeployment($client->getEntity(), $input, $image, $inputData, DeployMethodTypes::TORRENT, $trace);
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
}
$pending[] = [
'client' => $client,
'inputData' => $inputData,
'response' => $this->deployImageOgAgentAction->startDeploy($image, $input, $client),
];
} catch (\Exception $e) {
$this->logger->warning('Error deploying to client (torrent)', [
'client_uuid' => $client->getEntity()->getUuid(),
$this->logger->warning(sprintf('Error deploying to client (%s)', $methodLabel), [
'client_uuid' => $client->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);
}
$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);
continue;
}
$this->registerDeployment($client, $input, $inputData, $jobId, $trace);
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getUuid()] = $jobId;
}
}
return $clientJobs;
}
private function processDeployment($client, DeployImageInput $input, ImageImageRepository $image, array $inputData, string $deployType, ?Trace $trace = null): ?string
/** Deja el despliegue en cola para que lo reintente ExecutePendingTracesCommand. */
private function queueDeployment($client, DeployImageInput $input, array $inputData): void
{
$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);
}
if (!$input->queue) {
return;
}
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
}
/** 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
{
if (!$jobId) {
if (!$input->queue) {
return;
}
return null;
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;
}
if ($trace) {
$trace->setStatus(TraceStatus::IN_PROGRESS);
$trace->setJobId($agentJobId);
$trace->setJobId($jobId);
$trace->setInput($inputData);
$this->entityManager->persist($trace);
$this->entityManager->flush();
} else {
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $agentJobId, $inputData);
$this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $jobId, $inputData);
}
return $agentJobId;
}
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;
}
private function createInputData(DeployImageInput $input, ImageImageRepository $image, $client): array

View File

@ -0,0 +1,198 @@
<?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,6 +5,7 @@ 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;
@ -27,8 +28,6 @@ class MenuBrowserController extends AbstractController
{
$host = $request->getClientIp();
$partitions = [];
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $host]);
$disks = []; // Array nuevo estructurado
@ -68,15 +67,74 @@ class MenuBrowserController extends AbstractController
}
}
$menuName = $client->getMenu()->getPublicUrl();
$menu = $this->resolveMenu($client);
return $this->render('browser/' . $menuName . '.html.twig', [
$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, [
'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
{
@ -86,10 +144,18 @@ class MenuBrowserController extends AbstractController
throw $this->createNotFoundException(sprintf('La plantilla "%s" no existe.', $templateName));
}
return $this->render($templatePath, [
$html = $this->renderView($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'])]
@ -128,6 +194,10 @@ 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,6 +4,8 @@ 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;
@ -17,6 +19,7 @@ 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
@ -35,18 +38,41 @@ 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
{
$options = array_merge($params, [
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => $token,
],
$defaultHeaders = [
'accept' => 'application/json',
'Content-Type' => 'application/json',
];
if ($token !== null) {
$defaultHeaders['Authorization'] = $token;
}
$defaultOptions = [
'headers' => $defaultHeaders,
'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;
@ -59,6 +85,13 @@ 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
@ -71,6 +104,26 @@ 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,8 +63,10 @@ class CreateImageAction extends AbstractOgAgentController
$partitionInfo = json_decode($image->getPartitionInfo(), true);
}
$effectiveClient = $client ?? $image->getClient();
if ($image->getType() === 'monolithic') {
$repository = $image->getClient()->getRepository();
$repository = $effectiveClient->getRepository();
$latestImageRepo = $this->entityManager->getRepository(ImageImageRepository::class)->findLatestVersionByImageAndRepository($image, $repository);
$imageImageRepository = new ImageImageRepository();
@ -77,11 +79,11 @@ class CreateImageAction extends AbstractOgAgentController
$this->entityManager->persist($imageImageRepository);
return $this->createMonolithicImage($imageImageRepository, $partitionInfo, $image, $repository, $client, $queue, $existingTrace);
return $this->createMonolithicImage($imageImageRepository, $partitionInfo, $image, $repository, $effectiveClient, $queue, $existingTrace);
} else {
$repository = $image->getClient()->getRepository();
$repository = $effectiveClient->getRepository();
return $this->createGitImage($image, $partitionInfo, $repository, $queue, $gitRepositoryName, $existingTrace);
return $this->createGitImage($image, $partitionInfo, $repository, $effectiveClient, $queue, $gitRepositoryName, $existingTrace);
}
}
@ -204,7 +206,7 @@ class CreateImageAction extends AbstractOgAgentController
$this->entityManager->flush();
} else {
$this->createService->__invoke(
$image->getClient(),
$client,
CommandTypes::CREATE_IMAGE,
TraceStatus::IN_PROGRESS,
$jobId,
@ -237,6 +239,7 @@ class CreateImageAction extends AbstractOgAgentController
Image $image,
array $partitionInfo,
ImageRepository $repository,
?Client $client = null,
bool $queue = false,
?string $gitRepositoryName = null,
?Trace $existingTrace = null
@ -246,7 +249,7 @@ class CreateImageAction extends AbstractOgAgentController
throw new BadRequestHttpException('Missing required partition information');
}
$client = $image->getClient();
$client = $client ?? $image->getClient();
if (!$client->getIp() || !$client->getToken()) {
throw new BadRequestHttpException('Client IP or token is missing');
}

View File

@ -14,7 +14,8 @@ 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\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
class DeployImageAction extends AbstractOgAgentController
{
@ -25,6 +26,22 @@ 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();
@ -77,26 +94,32 @@ class DeployImageAction extends AbstractOgAgentController
$url = 'https://'.$client->getIp().':8000/opengnsys/RestaurarImagen';
$response = $this->createRequest(
method: 'POST',
url: $url,
params: [
'json' => $data,
],
token: $client->getToken(),
);
$this->logger->info('Deploying image', [
'image' => $imageImageRepository->getName(),
$this->logger->info('Deploying image', [
'image' => $imageImageRepository->getName(),
'repository' => $repository->getIp(),
'client' => $client->getIp()
]);
if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
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) {
throw new BadRequestHttpException('Error deploying image');
}
$jobId = $response['job_id'];
$jobId = $content['job_id'] ?? null;
$client->setStatus(ClientStatus::BUSY);
$this->entityManager->persist($client);

View File

@ -15,7 +15,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
#[AsController]
class GetDiskLogsAction extends AbstractController
{
private const LOG_DIR = '/var/log/ogClients/';
private const LOG_DIR = '/var/log/ogclients/';
public function __construct(
private readonly LoggerInterface $logger,
@ -29,7 +29,7 @@ class GetDiskLogsAction extends AbstractController
}
$ip = $client->getIp();
$logPath = self::LOG_DIR . $ip . '/clieng.log';
$logPath = self::LOG_DIR . $ip . '/client.log';
if (!file_exists($logPath)) {
throw new NotFoundHttpException(sprintf('No disk log file found for client %s.', $ip));

View File

@ -167,20 +167,25 @@ 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(),
@ -188,16 +193,17 @@ class HardwareInventoryAction extends AbstractOgAgentController
]);
}
foreach ($hardwareItems as $hardware) {
$hardwareProfile->addHardwareCollection($hardware);
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)
]);
}
$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,66 +6,27 @@ namespace App\Controller\OgAgent;
use App\Dto\Input\KillJobInput;
use App\Entity\Trace;
use App\Model\ClientStatus;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use App\Service\Trace\CreateService;
use App\Service\Trace\KillJobService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
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\Component\HttpKernel\Attribute\AsController;
class KillJobAction extends AbstractOgAgentController
#[AsController]
class KillJobAction extends AbstractController
{
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly KillJobService $killJobService,
) {
}
public function __invoke(Trace $trace, KillJobInput $input): JsonResponse
{
$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->killJobService->kill($trace, $input->jobId);
$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,6 +47,8 @@ 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,6 +79,24 @@ 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'])) {
@ -92,28 +110,36 @@ class PartitionAssistantAction extends AbstractOgAgentController
"cfg" => $data,
"ids" => "0"
];
$url = 'https://' . $client->getIp() . ':8000/opengnsys/Configurar';
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/opengnsys/Configurar',
params: [
'json' => $result,
],
token: $client->getToken(),
);
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'];
$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'];
$jobId = $response['job_id'] ?? null;
$client->setStatus(ClientStatus::BUSY);
$this->entityManager->persist($client);
@ -128,7 +154,9 @@ class PartitionAssistantAction extends AbstractOgAgentController
$this->createService->__invoke($client, CommandTypes::PARTITION_AND_FORMAT, TraceStatus::IN_PROGRESS, $jobId, $data);
}
$clientJobs['/clients/' . $client->getUuid()] = $jobId;
if ($jobId) {
$clientJobs['/clients/' . $client->getUuid()] = $jobId;
}
}
}

View File

@ -39,6 +39,8 @@ class PowerOffAction extends AbstractOgAgentController
*/
public function __invoke(MultipleClientsInput $input): JsonResponse
{
$pending = [];
foreach ($input->clients as $clientEntity) {
/** @var Client $client */
$client = $clientEntity->getEntity();
@ -47,7 +49,10 @@ class PowerOffAction extends AbstractOgAgentController
throw new BadRequestHttpException('IP is required');
}
if ($client->getStatus() === ClientStatus::OFF || $client->getStatus() === ClientStatus::TURNING_OFF || $client->getStatus() === ClientStatus::DISCONNECTED) {
if ($this->isClientOffline($client)) {
if ($input->queue) {
$this->createService->__invoke($client, CommandTypes::SHUTDOWN, TraceStatus::PENDING, null, []);
}
continue;
}
@ -55,30 +60,41 @@ class PowerOffAction extends AbstractOgAgentController
'nfn' => 'Apagar',
'ids' => '0'
];
$url = 'https://' . $client->getIp() . ':8000/opengnsys/Apagar';
$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']]);
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']]);
}
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'];
$jobId = $response['job_id'] ?? null;
$client->setStatus(ClientStatus::TURNING_OFF);
$this->entityManager->persist($client);

View File

@ -27,41 +27,61 @@ 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';
$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) {
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) {
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'];
$jobId = $response['job_id'] ?? null;
$client->setStatus(ClientStatus::INITIALIZING);
$this->entityManager->persist($client);
@ -70,6 +90,6 @@ class RebootAction extends AbstractOgAgentController
$this->createService->__invoke($client, CommandTypes::REBOOT, TraceStatus::SUCCESS, $jobId, []);
}
return new JsonResponse(data: $client, status: Response::HTTP_OK);
return new JsonResponse(data: [], status: Response::HTTP_OK);
}
}

View File

@ -39,6 +39,8 @@ class RefreshAction extends AbstractOgAgentController
*/
public function __invoke(MultipleClientsInput $input): JsonResponse
{
$pending = [];
foreach ($input->clients as $clientEntity) {
/** @var Client $client */
$client = $clientEntity->getEntity();
@ -57,24 +59,31 @@ class RefreshAction extends AbstractOgAgentController
'nfn' => 'Actualizar',
'ids' => '0'
];
$url = 'https://' . $client->getIp() . ':8000/ogAdmClient/Actualizar';
$response = $this->createRequest(
method: 'POST',
url: 'https://'.$client->getIp().':8000/ogAdmClient/Actualizar',
params: [
'json' => $data,
],
token: $client->getToken(),
);
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']);
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;
}
@ -82,9 +91,6 @@ 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 = 'rm -r /opt/opengnsys/cache/opt/opengnsys/images/' . escapeshellarg($input->imageName) . '*';
$script = 'ogMountCache && rm -r /opt/opengnsys/cache/opt/opengnsys/images/' . escapeshellarg($input->imageName) . '*';
$data = [
'nfn' => 'EjecutarScript',

View File

@ -27,6 +27,7 @@ class RunScriptAction extends AbstractOgAgentController
public function __invoke(CommandExecuteInput $input, ?Trace $existingTrace = null): JsonResponse
{
$clientJobs = [];
$pending = [];
/** @var Client $clientEntity */
foreach ($input->clients as $clientEntity) {
@ -37,10 +38,112 @@ 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);
$response = $this->executeScript($client, $data);
$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);
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;
}
@ -49,8 +152,10 @@ class RunScriptAction extends AbstractOgAgentController
continue;
}
$jobId = $response['job_id'];
$clientJobs[(string) '/clients/' . $client->getUuid()] = $jobId;
$jobId = $response['job_id'] ?? null;
if ($jobId) {
$clientJobs[(string) '/clients/' . $client->getUuid()] = $jobId;
}
$this->handleSuccess($client, $input, $response, $existingTrace);
}
@ -58,6 +163,33 @@ 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);
@ -86,35 +218,6 @@ 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;
@ -129,6 +232,9 @@ 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);
}
}
@ -147,17 +253,29 @@ class RunScriptAction extends AbstractOgAgentController
$this->entityManager->persist($client);
$this->entityManager->flush();
if ($existingTrace) {
$this->updateExistingTrace($existingTrace, $jobId, $inputData, $client);
// 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();
} else {
$status = ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) ? TraceStatus::SENT : TraceStatus::IN_PROGRESS;
$this->createService->__invoke($client, CommandTypes::RUN_SCRIPT, $status, $jobId, $inputData);
if ($existingTrace) {
$this->updateExistingTrace($existingTrace, $jobId, $inputData, $client);
} else {
$status = 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 = ($this->isLinuxOrWindows($client) || $this->isLinuxOrWindowsSession($client)) ? TraceStatus::SENT : TraceStatus::IN_PROGRESS;
$status = TraceStatus::IN_PROGRESS;
$trace->setStatus($status);
$trace->setJobId($jobId);
$this->entityManager->persist($trace);

View File

@ -20,6 +20,7 @@ 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;
@ -56,6 +57,7 @@ class StatusController extends AbstractController
protected readonly LoggerInterface $logger,
protected readonly CreateService $createService,
protected readonly HttpClientInterface $httpClient,
protected readonly PendingTraceExecutionService $pendingTraceExecutionService,
)
{
}
@ -81,47 +83,58 @@ 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){
@ -130,265 +143,312 @@ 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']]);
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();
$this->logger->info('Git image creation completed.', ['job_id' => $data['job_id'], 'success' => $data['res'] === 1]);
}
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']);
}
$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]);
}
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 (!$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);
}
$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);
$client = $trace->getClient();
if ($client && $client->getStatus() === ClientStatus::BUSY) {
$client->setStatus(ClientStatus::OG_LIVE);
$this->entityManager->persist($client);
}
$this->entityManager->flush();
}
}
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()]);
}
$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 {
// 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,
]);
if ($trace->getStatus() !== TraceStatus::SUCCESS && $trace->getStatus() !== TraceStatus::ERROR) {
$trace->setStatus(TraceStatus::IN_PROGRESS);
$this->entityManager->persist($trace);
$this->entityManager->flush();
}
}
break;
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;
case self::CREATE_IMAGE_GIT:
case 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']);
}
$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;
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 (!$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);
}
$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()]);
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) {
$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()
]);
}
}
@ -405,11 +465,13 @@ 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();
@ -417,13 +479,12 @@ class StatusController extends AbstractController
$softwareProfile = new SoftwareProfile();
$softwareProfile->setDescription('SW Profile - ' . $image->getClient()->getName());
foreach ($existingSoftware as $softwareEntity) {
foreach ([...$existingSoftware, ...$newSoftware] as $softwareEntity) {
$softwareEntity->addSoftwareProfile($softwareProfile);
}
$image->setSoftwareProfile($softwareProfile);
$imageImageRepository->setSoftwareProfile($softwareProfile);
$this->entityManager->persist($image);
$this->entityManager->persist($imageImageRepository);
$this->entityManager->persist($softwareProfile);
$this->entityManager->flush();

View File

@ -7,6 +7,7 @@ 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;
@ -21,12 +22,30 @@ class DeleteAction extends AbstractOgBootController
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __invoke(string $mac): JsonResponse
public function __invoke(string $mac, ?Client $client = null): JsonResponse
{
$response = $this->createRequest('DELETE', '/ogboot/v1/pxes/'.$mac);
$mac = strtolower($mac);
if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
return new JsonResponse( data: 'An error occurred', status: Response::HTTP_INTERNAL_SERVER_ERROR);
// 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;
}
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->getOrganizationalUnit()->getNetworkSettings()?->getRouter(),
'netmask' => $client->getOrganizationalUnit()->getNetworkSettings() ? $client->getOrganizationalUnit()->getNetworkSettings()->getNetmask() : '255.255.255.0',
'router' => $client->getSubnet()?->getRouter() ?? $client->getOrganizationalUnit()->getNetworkSettings()?->getRouter() ?? '',
'netmask' => $client->getSubnet()?->getNetmask() ?? $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

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

View File

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

View File

@ -78,7 +78,6 @@ 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,7 +50,6 @@ class SyncAction extends AbstractOgRepositoryController
if (!$imageEntity) {
$imageEntity = new Image();
$imageEntity->setName($image['name']);
$imageEntity->setRemotePc(false);
$imageEntity->setIsGlobal(false);
$imageEntity->setType('monolithic');
@ -68,6 +67,7 @@ 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,6 +80,18 @@ 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,19 +48,33 @@ 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' => '255.255.255.255',
'broadcast_ip' => $broadcastIp,
'mac' => $client->getMac()
]
];
$this->logger->info('Sending WoL to client', ['mac' => $client->getMac()]);
$this->logger->info('Sending WoL to client', ['mac' => $client->getMac(), 'broadcast_ip' => $broadcastIp]);
$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()]);
$this->logger->error('Error sending WoL to client', ['mac' => $client->getMac(), 'broadcast_ip' => $broadcastIp]);
continue;
}

View File

@ -0,0 +1,111 @@
<?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

@ -0,0 +1,84 @@
<?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,7 +183,11 @@ class RemotePcController extends AbstractController
->setParameter('status', TraceStatus::PENDING)
->execute();
$this->sendPowerOff($client);
if ($client->getOrganizationalUnit() && $client->getOrganizationalUnit()->isRemotePcRebootOnUnreserve()) {
$this->sendReboot($client);
} else {
$this->sendPowerOff($client);
}
$this->logger->info('RemotePC: client unreserved', ['client_id' => $client->getId()]);
@ -375,6 +379,20 @@ 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,7 +7,9 @@ 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;
@ -20,31 +22,74 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection
}
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void
{
$this->addWhere($queryBuilder, $resourceClass);
$this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass);
}
public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void
{
$this->addWhere($queryBuilder, $resourceClass);
$this->addWhere($queryBuilder, $queryNameGenerator, $resourceClass);
}
private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
private function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass): void
{
/** @var User $user */
$user = $this->security->getUser();
if (OrganizationalUnit::class !== $resourceClass || null === $user || in_array('ROLE_SUPER_ADMIN', $user->getRoles())) {
if (null === $user || in_array(UserGroupPermissions::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);
}
$rootAlias = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere(sprintf('%s.id in (:ou)', $rootAlias));
$queryBuilder->setParameter('ou', $organizationalUnitIds);
return $organizationalUnitIds;
}
private function addOrganizationalUnitAndChildrenIds(OrganizationalUnit $organizationalUnit, array &$organizationalUnitIds): void
@ -58,4 +103,4 @@ readonly class UserAllowedOrganizationalUnitExtension implements QueryCollection
}
}
}
}

View File

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

View File

@ -86,7 +86,13 @@ final class ClientInput
#[ApiProperty(
description: 'La plantilla PXE del cliente'
)]
public ?PxeTemplateOutput $pxeTemplate = null;
public ?PxeTemplateOutput $pxeTemplate = null;
#[Groups(['client:write'])]
#[ApiProperty(
description: 'El perfil de hardware del cliente'
)]
public ?HardwareProfileOutput $hardwareProfile = null;
#[Groups(['client:write'])]
#[ApiProperty(
@ -162,6 +168,10 @@ 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());
}
@ -179,6 +189,7 @@ 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();
@ -191,6 +202,7 @@ 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,4 +41,11 @@ 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

@ -0,0 +1,22 @@
<?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,20 +74,18 @@ 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($utc)
? \DateTime::createFromInterface($this->executionTime)->setTimezone(new \DateTimeZone('UTC'))
: null
);
$commandTaskSchedule->setExecutionDate(
$this->executionDate
? \DateTime::createFromInterface($this->executionDate)->setTimezone($utc)
? \DateTime::createFromInterface($this->executionDate)
: null
);
$commandTaskSchedule->setRecurrenceDetails($this->recurrenceDetails);

View File

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

View File

@ -6,10 +6,8 @@ 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,13 +4,11 @@ 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,7 +5,6 @@ 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
{
@ -17,10 +16,6 @@ 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) {
@ -29,7 +24,6 @@ final class HardwareProfileInput
$this->description = $hardwareProfile->getDescription();
$this->comments = $hardwareProfile->getComments();
$this->client = new ClientOutput($hardwareProfile->getClient());
}
public function createOrUpdateEntity(?HardwareProfile $hardwareProfile = null): HardwareProfile
@ -40,7 +34,6 @@ final class HardwareProfileInput
$hardwareProfile->setDescription($this->description);
$hardwareProfile->setComments($this->comments);
$hardwareProfile->setClient($this->client->getEntity());
return $hardwareProfile;
}

View File

@ -5,6 +5,7 @@ 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;
@ -19,6 +20,10 @@ 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) {
@ -27,6 +32,10 @@ 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
@ -37,6 +46,7 @@ final class ImageImageRepositoryInput
$imageImageRepository->setDescription($this->description);
$imageImageRepository->setRemotePc($this->remotePc);
$imageImageRepository->setSoftwareProfile($this->softwareProfile?->getEntity());
return $imageImageRepository;
}

View File

@ -10,7 +10,6 @@ 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;
@ -33,10 +32,6 @@ 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[]
*/
@ -83,10 +78,6 @@ 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());
}
@ -109,10 +100,6 @@ 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,6 +102,13 @@ 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',
@ -128,6 +135,7 @@ 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());
}
@ -155,6 +163,7 @@ 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,6 +5,8 @@ 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;
@ -26,6 +28,12 @@ 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)
{
@ -42,6 +50,11 @@ 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
@ -58,6 +71,18 @@ 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,6 +56,13 @@ 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(
@ -113,6 +120,7 @@ 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) {
@ -137,6 +145,7 @@ 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,6 +8,7 @@ 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
@ -70,6 +71,13 @@ 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',
@ -91,6 +99,13 @@ 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',
@ -199,6 +214,7 @@ 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()) {
@ -210,6 +226,9 @@ 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,8 +92,15 @@ final class CommandTaskOutput extends AbstractOutput
}
$this->notes = $commandTask->getNotes();
$this->scope = $commandTask->getScope();
$this->lastExecution = $commandTask->getLastExecution();
$this->nextExecution = $commandTask->getNextExecution();
$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->createdAt = $commandTask->getCreatedAt();
$this->createdBy = $commandTask->getCreatedBy();
}

View File

@ -54,7 +54,12 @@ class CommandTaskScheduleOutput extends AbstractOutput
}
$this->recurrenceType = $commandTaskSchedule->getRecurrenceType();
$this->executionTime = $commandTaskSchedule->getExecutionTime();
$rawTime = $commandTaskSchedule->getExecutionTime();
$this->executionTime = $rawTime
? new \DateTime('1970-01-01 ' . $rawTime->format('H:i:s'), new \DateTimeZone('UTC'))
: null;
$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 = new HardwareTypeOutput($hardware->getType());
$this->type = $hardware->getType() ? new HardwareTypeOutput($hardware->getType()) : null;
$this->createdAt = $hardware->getCreatedAt();
$this->createdBy = $hardware->getCreatedBy();
}

View File

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

View File

@ -24,6 +24,13 @@ 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',
@ -115,6 +122,10 @@ 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,13 +34,6 @@ 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
*/
@ -84,7 +77,6 @@ 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,6 +109,13 @@ 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',
@ -150,6 +157,7 @@ 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,6 +17,13 @@ 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(
@ -86,6 +93,7 @@ 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'])]
#[Groups(['software-profile:read', 'image:read', 'image-image-repository:read'])]
#[ApiProperty(
description: 'La descripción del perfil de software',
example: 'Perfil estándar para aula de informática'

View File

@ -61,6 +61,13 @@ 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',
@ -84,6 +91,7 @@ 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,9 +54,13 @@ class Client extends AbstractEntity
#[ORM\JoinColumn( onDelete: 'SET NULL')]
private ?Menu $menu = null;
#[ORM\OneToOne(mappedBy: 'client', cascade: ['persist', 'remove'])]
#[ORM\ManyToOne(inversedBy: 'clients')]
#[ORM\JoinColumn(onDelete: 'SET NULL')]
private ?HardwareProfile $hardwareProfile = null;
#[ORM\Column(nullable: true)]
private ?int $netSpeed = null;
#[ORM\Column(nullable: true)]
private ?bool $validation = null;
@ -252,6 +256,18 @@ 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(length: 255, nullable: true)]
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $content = null;
#[ORM\Column]

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