From 7332a3fe8c187e9a8b1940c5a9dc03455bd74c9f Mon Sep 17 00:00:00 2001 From: ramon Date: Thu, 22 Feb 2018 13:36:00 +0000 Subject: #730: Copiar OpenGnsys 1.1.0 en rama {{{tags/opengnsys-1.1.0}}} git-svn-id: https://opengnsys.es/svn/tags/opengnsys-1.1.0@5607 a21b9725-9963-47de-94b9-378ad31fedc9 --- admin/Database/ogAdmBD-1.0.6a-1.0.6b.sql | 8 +- admin/Database/ogAdmBD-1.0.6b-1.1.0.sql | 161 +++ admin/Database/ogAdmBD-1.0.6b-postinst.sql | 41 - admin/Database/ogAdmBD-1.1.0-postinst.sql | 49 + admin/Database/ogAdmBD-1.1.0pre-1.1.0.sql | 270 ++++ admin/Database/ogAdmBD.sql | 443 ++++--- admin/Interface/CambiarAcceso | 8 +- admin/Interface/Configurar | 4 +- admin/Interface/CrearImagen | 18 +- admin/Interface/getConfiguration | 45 +- admin/Sources/Clients/README.es.txt | 9 + admin/Sources/Clients/ogAdmClient/Makefile | 6 +- .../Clients/ogAdmClient/sources/ogAdmClient.c | 92 +- admin/Sources/Clients/ogAdmLnxClient/Makefile | 34 - .../Clients/ogAdmLnxClient/ogAdmLnxClient.cfg | 4 - .../ogAdmLnxClient/sources/ogAdmLnxClient.c | 499 -------- .../ogAdmLnxClient/sources/ogAdmLnxClient.h | 54 - admin/Sources/Clients/ogAdmWinClient/Readme | 25 - .../ogAdmWinClient/sources/ogAdmWinClient.cpp | 713 ----------- .../ogAdmWinClient/sources/ogAdmWinClient.h | 60 - .../Clients/ogAdmWinClient/sources/servicio.c | 628 ---------- .../Clients/ogAdmWinClient/sources/servicio.h | 153 --- admin/Sources/Clients/ogagent/INSTALL.es.txt | 89 ++ admin/Sources/Clients/ogagent/linux/Makefile | 72 ++ .../Clients/ogagent/linux/build-packages.sh | 35 + .../Sources/Clients/ogagent/linux/debian/changelog | 12 + admin/Sources/Clients/ogagent/linux/debian/compat | 1 + admin/Sources/Clients/ogagent/linux/debian/control | 15 + .../Sources/Clients/ogagent/linux/debian/copyright | 26 + admin/Sources/Clients/ogagent/linux/debian/docs | 1 + .../Clients/ogagent/linux/debian/ogagent.init | 23 + .../Clients/ogagent/linux/debian/ogagent.links | 2 + .../Clients/ogagent/linux/debian/ogagent.postinst | 21 + .../linux/debian/ogagent.postinst.debhelper | 5 + .../Clients/ogagent/linux/debian/ogagent.postrm | 10 + .../ogagent/linux/debian/ogagent.postrm.debhelper | 12 + .../Clients/ogagent/linux/debian/ogagent.substvars | 2 + admin/Sources/Clients/ogagent/linux/debian/rules | 44 + .../Clients/ogagent/linux/debian/source/format | 1 + .../ogagent/linux/desktop/OGAgentTool.desktop | 12 + .../Clients/ogagent/linux/ogagent-template.spec | 65 + .../org.openuds.pkexec.UDSActorConfig.policy | 20 + admin/Sources/Clients/ogagent/linux/readme.txt | 3 + .../Clients/ogagent/linux/scripts/OGAgentTool | 6 + .../ogagent/linux/scripts/OGAgentTool-startup | 10 + .../Sources/Clients/ogagent/linux/scripts/ogagent | 6 + admin/Sources/Clients/ogagent/macos/build-pkg.sh | 87 ++ .../macos/scripts/es.opengnsys.ogagent.plist | 15 + .../Sources/Clients/ogagent/macos/scripts/ogagent | 6 + .../Clients/ogagent/macos/scripts/postinstall | 17 + admin/Sources/Clients/ogagent/requires.txt | 3 + .../Clients/ogagent/src/OGAServiceHelper.py | 57 + admin/Sources/Clients/ogagent/src/OGAgent.manifest | 17 + admin/Sources/Clients/ogagent/src/OGAgent.qrc | 5 + admin/Sources/Clients/ogagent/src/OGAgentUser.py | 358 ++++++ admin/Sources/Clients/ogagent/src/OGAgent_rc.py | 289 +++++ admin/Sources/Clients/ogagent/src/VERSION | 1 + admin/Sources/Clients/ogagent/src/about-dialog.ui | 244 ++++ admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg | 21 + admin/Sources/Clients/ogagent/src/cfg/ogclient.cfg | 11 + .../Sources/Clients/ogagent/src/img/oga-48x48.ico | Bin 0 -> 9662 bytes admin/Sources/Clients/ogagent/src/img/oga-512.png | Bin 0 -> 44217 bytes admin/Sources/Clients/ogagent/src/img/oga.ico | Bin 0 -> 9662 bytes admin/Sources/Clients/ogagent/src/img/oga.png | Bin 0 -> 3906 bytes admin/Sources/Clients/ogagent/src/license.txt | 27 + .../Sources/Clients/ogagent/src/message-dialog.ui | 89 ++ .../Clients/ogagent/src/opengnsys/RESTApi.py | 160 +++ .../Clients/ogagent/src/opengnsys/__init__.py | 57 + .../Sources/Clients/ogagent/src/opengnsys/certs.py | 101 ++ .../Clients/ogagent/src/opengnsys/config.py | 59 + .../Clients/ogagent/src/opengnsys/httpserver.py | 150 +++ admin/Sources/Clients/ogagent/src/opengnsys/ipc.py | 423 +++++++ .../ogagent/src/opengnsys/linux/OGAgentService.py | 147 +++ .../ogagent/src/opengnsys/linux/__init__.py | 32 + .../Clients/ogagent/src/opengnsys/linux/daemon.py | 182 +++ .../Clients/ogagent/src/opengnsys/linux/log.py | 80 ++ .../ogagent/src/opengnsys/linux/operations.py | 286 +++++ .../src/opengnsys/linux/renamer/__init__.py | 61 + .../ogagent/src/opengnsys/linux/renamer/debian.py | 68 + .../src/opengnsys/linux/renamer/opensuse.py | 66 + .../ogagent/src/opengnsys/linux/renamer/redhat.py | 74 ++ .../Clients/ogagent/src/opengnsys/loader.py | 111 ++ admin/Sources/Clients/ogagent/src/opengnsys/log.py | 103 ++ .../ogagent/src/opengnsys/macos/__init__.py | 32 + .../ogagent/src/opengnsys/macos/operations.py | 255 ++++ .../ogagent/src/opengnsys/modules/__init__.py | 0 .../opengnsys/modules/client/OpenGnSys/__init__.py | 63 + .../src/opengnsys/modules/client/__init__.py | 0 .../opengnsys/modules/server/OpenGnSys/__init__.py | 250 ++++ .../src/opengnsys/modules/server/__init__.py | 0 .../Clients/ogagent/src/opengnsys/operations.py | 50 + .../Clients/ogagent/src/opengnsys/scriptThread.py | 51 + .../Clients/ogagent/src/opengnsys/service.py | 249 ++++ .../Sources/Clients/ogagent/src/opengnsys/utils.py | 72 ++ .../src/opengnsys/windows/OGAgentService.py | 124 ++ .../ogagent/src/opengnsys/windows/__init__.py | 39 + .../Clients/ogagent/src/opengnsys/windows/log.py | 77 ++ .../ogagent/src/opengnsys/windows/operations.py | 261 ++++ .../ogagent/src/opengnsys/workers/__init__.py | 2 + .../ogagent/src/opengnsys/workers/client_worker.py | 114 ++ .../ogagent/src/opengnsys/workers/server_worker.py | 186 +++ .../ogagent/src/prototypes/threaded_server.py | 170 +++ admin/Sources/Clients/ogagent/src/setup.py | 136 ++ .../Clients/ogagent/src/test_modules/__init__.py | 0 .../src/test_modules/client/Sample1/__init__.py | 38 + .../ogagent/src/test_modules/client/__init__.py | 0 .../src/test_modules/server/Sample1/__init__.py | 2 + .../src/test_modules/server/Sample1/sample1.py | 40 + .../server/Sample1/sample_pkg/__init__.py | 36 + .../ogagent/src/test_modules/server/__init__.py | 0 .../Clients/ogagent/src/test_rest_server.py | 210 ++++ admin/Sources/Clients/ogagent/src/update.sh | 41 + .../Clients/ogagent/windows/build-windows.sh | 5 + admin/Sources/Clients/ogagent/windows/build.bat | 6 + admin/Sources/Clients/ogagent/windows/ogagent.nsi | 192 +++ .../Clients/ogagent/windows/py2exe-wine-linux.sh | 71 ++ admin/Sources/Includes/Database.cpp | 5 + admin/Sources/Includes/Database.h | 1 + .../Services/ogAdmAgent/sources/ogAdmAgent.h | 2 +- admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg | 1 + .../Services/ogAdmServer/sources/ogAdmServer.cpp | 162 ++- .../Services/ogAdmServer/sources/ogAdmServer.h | 2 +- admin/Sources/Services/ogAdmServerAux | 7 +- admin/Sources/Services/opengnsys.default | 4 +- admin/Sources/Services/opengnsys.init | 8 +- .../asistentes/AsistenteCloneRemotePartition.php | 12 +- .../WebConsole/asistentes/AsistenteDeployImage.php | 11 +- .../asistentes/AsistenteParticionado.php | 10 +- .../WebConsole/asistentes/AsistenteUpdateCache.php | 10 +- .../asistentes/gestores/gestor_Comandos.php | 5 +- .../includes/asistentes/AyudanteFormularios.php | 915 +++++++------- .../asistentes/formCloneRemotePartition.php | 14 +- .../includes/asistentes/formDeployImage.php | 19 +- .../includes/asistentes/formParticionado_gpt.php | 7 +- .../includes/asistentes/formParticionado_msdos.php | 3 +- .../asistentes/includes/capturaacciones.php | 2 +- .../asistentes/includes/formularioacciones.php | 18 +- .../asistentes/includes/opcionesacciones.php | 38 +- .../asistentes/jscripts/EjecutarScripts.js | 2 +- admin/WebConsole/asistentes/jscripts/asistentes.js | 199 ++- admin/WebConsole/asistentes/xajax.server.php | 4 +- admin/WebConsole/barramenu.php | 38 +- admin/WebConsole/clases/AdoPhp.php | 13 +- admin/WebConsole/clases/ArbolVistaXML.php | 2 +- admin/WebConsole/clases/XmlPhp.php | 2 +- admin/WebConsole/comandos/Apagar.php | 6 +- admin/WebConsole/comandos/Arrancar.php | 4 +- admin/WebConsole/comandos/Comando.php | 6 +- admin/WebConsole/comandos/Configurar.php | 37 +- admin/WebConsole/comandos/CrearImagen.php | 58 +- admin/WebConsole/comandos/CrearImagenBasica.php | 28 +- admin/WebConsole/comandos/CrearSoftIncremental.php | 34 +- admin/WebConsole/comandos/EjecutarScripts.php | 21 +- admin/WebConsole/comandos/EliminarImagenCache.php | 68 +- .../comandos/EliminarImagenRepositorio.php | 402 +++--- admin/WebConsole/comandos/EnviarMensaje.php | 97 ++ admin/WebConsole/comandos/IniciarSesion.php | 8 +- admin/WebConsole/comandos/InventarioHardware.php | 6 +- admin/WebConsole/comandos/InventarioSoftware.php | 10 +- admin/WebConsole/comandos/Reiniciar.php | 6 +- admin/WebConsole/comandos/RestaurarImagen.php | 65 +- .../WebConsole/comandos/RestaurarImagenBasica.php | 43 +- .../comandos/RestaurarSoftIncremental.php | 41 +- .../comandos/gestores/gestor_Comandos.php | 120 +- .../comandos/gestores/wakeonlan_repo.php | 85 ++ .../comandos/includes/FiltradoAmbito.php | 126 +- .../comandos/includes/capturaacciones.php | 2 +- .../comandos/includes/formularioacciones.php | 18 +- .../comandos/includes/opcionesacciones.php | 40 +- admin/WebConsole/comandos/jscripts/Configurar.js | 35 +- admin/WebConsole/comandos/jscripts/CrearImagen.js | 6 +- .../comandos/jscripts/EjecutarScripts.js | 6 + .../WebConsole/comandos/jscripts/EnviarMensaje.js | 49 + .../comandos/jscripts/RestaurarImagen.js | 40 +- admin/WebConsole/controlacceso.php | 1 - admin/WebConsole/controlpostacceso.php | 6 +- admin/WebConsole/descargas/README.es.html | 85 ++ admin/WebConsole/descargas/index.php | 68 + admin/WebConsole/estilos.css | 12 +- admin/WebConsole/gestores/gestor_accionmenu.php | 2 +- .../gestores/gestor_administradores_centros.php | 2 +- .../gestores/gestor_administradores_usuarios.php | 2 +- admin/WebConsole/gestores/gestor_aulas.php | 40 +- admin/WebConsole/gestores/gestor_centros.php | 13 +- .../gestores/gestor_componentehardwares.php | 2 +- .../gestores/gestor_componentesoftwares.php | 2 +- admin/WebConsole/gestores/gestor_entidades.php | 10 +- admin/WebConsole/gestores/gestor_entornos.php | 8 +- .../gestores/gestor_gruposordenadores.php | 6 +- admin/WebConsole/gestores/gestor_imagenes.php | 25 +- .../gestores/gestor_inclusionacciones.php | 2 +- admin/WebConsole/gestores/gestor_ordenadores.php | 99 +- .../gestores/gestor_ordenadorestandar.php | 6 +- .../gestores/gestor_perfilcomponente_hard.php | 2 +- .../gestores/gestor_perfilcomponente_soft.php | 2 +- .../WebConsole/gestores/gestor_perfilsoftwares.php | 2 +- .../WebConsole/gestores/gestor_procedimientos.php | 2 +- .../gestores/gestor_procedimientoscomandos.php | 2 +- .../WebConsole/gestores/gestor_programaciones.php | 2 +- admin/WebConsole/gestores/gestor_repositorios.php | 14 +- admin/WebConsole/gestores/gestor_reservas.php | 2 +- admin/WebConsole/gestores/gestor_tareas.php | 2 +- .../WebConsole/gestores/gestor_tareascomandos.php | 2 +- admin/WebConsole/gestores/gestor_tipohardwares.php | 2 +- admin/WebConsole/gestores/gestor_universidades.php | 6 +- admin/WebConsole/gestores/gestor_usuarios.php | 17 +- .../gestores/relaciones/aulas_eliminacion.php | 2 +- .../gestores/relaciones/centros_eliminacion.php | 2 +- .../gestores/relaciones/entidades_eliminacion.php | 2 +- .../relaciones/gruposordenadores_eliminacion.php | 2 +- .../gestores/relaciones/hardwares_eliminacion.php | 2 +- .../gestores/relaciones/imagenes_eliminacion.php | 2 +- .../relaciones/incrementales_eliminacion.php | 2 +- .../gestores/relaciones/menus_eliminacion.php | 2 +- .../relaciones/perfileshard_eliminacion.php | 2 +- .../relaciones/perfilessoft_eliminacion.php | 2 +- .../relaciones/procedimientos_eliminacion.php | 2 +- .../relaciones/repositorios_eliminacion.php | 2 +- .../gestores/relaciones/reservas_eliminacion.php | 2 +- .../gestores/relaciones/softwares_eliminacion.php | 2 +- .../gestores/relaciones/tareas_eliminacion.php | 2 +- .../gestores/relaciones/trabajos_eliminacion.php | 2 +- .../gestores/relaciones/usuarios_eliminacion.php | 2 +- .../idiomas/javascripts/cat/asistentes_cat.js | 10 + .../cat/comandos/comunescomandos_cat.js | 1 + .../javascripts/cat/comandos/configurar_cat.js | 3 +- .../javascripts/cat/comandos/enviarmensaje_cat.js | 9 + .../cat/comandos/restaurarimagen_cat.js | 3 +- .../javascripts/cat/propiedades_aulas_cat.js | 3 +- .../javascripts/cat/propiedades_centros_cat.js | 7 +- .../javascripts/cat/propiedades_entidades_cat.js | 5 +- .../javascripts/cat/propiedades_ordenadores_cat.js | 4 +- .../javascripts/cat/propiedades_usuarios_cat.js | 3 +- .../idiomas/javascripts/eng/asistentes_eng.js | 10 + .../eng/comandos/comunescomandos_eng.js | 1 + .../javascripts/eng/comandos/configurar_eng.js | 3 +- .../javascripts/eng/comandos/enviarmensaje_eng.js | 9 + .../eng/comandos/restaurarimagen_eng.js | 9 +- .../javascripts/eng/propiedades_aulas_eng.js | 3 +- .../javascripts/eng/propiedades_centros_eng.js | 6 +- .../javascripts/eng/propiedades_entidades_eng.js | 5 +- .../javascripts/eng/propiedades_ordenadores_eng.js | 6 +- .../javascripts/eng/propiedades_usuarios_eng.js | 2 + .../idiomas/javascripts/esp/asistentes_esp.js | 10 + .../esp/comandos/comunescomandos_esp.js | 1 + .../javascripts/esp/comandos/configurar_esp.js | 2 + .../javascripts/esp/comandos/enviarmensaje_esp.js | 9 + .../esp/comandos/restaurarimagen_esp.js | 8 +- .../javascripts/esp/propiedades_aulas_esp.js | 3 +- .../javascripts/esp/propiedades_centros_esp.js | 5 +- .../javascripts/esp/propiedades_entidades_esp.js | 5 +- .../javascripts/esp/propiedades_ordenadores_esp.js | 4 +- .../javascripts/esp/propiedades_usuarios_esp.js | 3 +- admin/WebConsole/idiomas/php/cat/acceso_cat.php | 4 +- admin/WebConsole/idiomas/php/cat/acciones_cat.php | 2 +- .../WebConsole/idiomas/php/cat/accionmenu_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/acercade_cat.php | 6 +- .../WebConsole/idiomas/php/cat/actualizar_cat.php | 2 +- .../idiomas/php/cat/administracion_cat.php | 2 +- .../php/cat/administradores_centros_cat.php | 2 +- .../php/cat/administradores_usuarios_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/aulas_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/avisos_cat.php | 5 +- admin/WebConsole/idiomas/php/cat/barramenu_cat.php | 2 +- .../idiomas/php/cat/boot_grub4dos_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/buscar_cat.php | 2 +- .../idiomas/php/cat/clases/Almanaque_cat.php | 28 +- .../idiomas/php/cat/clases/Calendario_cat.php | 2 +- .../idiomas/php/cat/colasacciones_cat.php | 2 +- .../idiomas/php/cat/colasreservas_cat.php | 2 +- .../idiomas/php/cat/comandos/apagar_cat.php | 2 +- .../idiomas/php/cat/comandos/arrancar_cat.php | 2 +- .../idiomas/php/cat/comandos/comando_cat.php | 2 +- .../idiomas/php/cat/comandos/configurar_cat.php | 2 + .../idiomas/php/cat/comandos/conmutar_cat.php | 2 +- .../idiomas/php/cat/comandos/crearimagen_cat.php | 2 +- .../php/cat/comandos/crearimagenbasica_cat.php | 2 +- .../php/cat/comandos/crearperfilsoftware_cat.php | 2 +- .../php/cat/comandos/crearsoftincremental_cat.php | 2 +- .../php/cat/comandos/ejecutarscripts_cat.php | 7 + .../php/cat/comandos/eliminarimagencache_cat.php | 10 +- .../php/cat/comandos/eliminarimagenrepo_cat.php | 5 +- .../idiomas/php/cat/comandos/enviarmensaje_cat.php | 23 + .../cat/comandos/gestor_ejecutarscripts_cat.php | 2 +- .../idiomas/php/cat/comandos/mensajes_cat.php | 1 + .../php/cat/comandos/opcionesacciones_cat.php | 2 +- .../php/cat/comandos/particionaryformatear_cat.php | 2 +- .../idiomas/php/cat/comandos/reiniciar_cat.php | 2 +- .../idiomas/php/cat/comandos/rembooffline_cat.php | 2 +- .../php/cat/comandos/restaurarimagen_cat.php | 2 +- .../php/cat/comandos/restaurarimagenbasica_cat.php | 2 +- .../cat/comandos/restaurarsoftincremental_cat.php | 2 +- .../php/cat/comandos/tomaconfiguracion_cat.php | 2 +- .../idiomas/php/cat/configuraciones_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/conmutar_cat.php | 2 +- .../idiomas/php/cat/consolaremota_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/descargas_cat.php | 13 + admin/WebConsole/idiomas/php/cat/ecoremoto_cat.php | 2 +- .../idiomas/php/cat/ejecutaracciones_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/estados_cat.php | 7 +- .../idiomas/php/cat/gestor_ordenadores_cat.php | 10 + admin/WebConsole/idiomas/php/cat/hardwares_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/iconos_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/imagenes_cat.php | 2 +- .../idiomas/php/cat/imagenincremental_cat.php | 2 +- .../idiomas/php/cat/inclusionacciones_cat.php | 2 +- .../php/cat/incrementalcomponente_soft_cat.php | 2 +- .../idiomas/php/cat/informacion_acciones_cat.php | 2 +- .../idiomas/php/cat/informacion_imagenes_cat.php | 2 +- .../php/cat/informacion_incrementales_cat.php | 2 +- .../idiomas/php/cat/informacion_menus_cat.php | 2 +- .../php/cat/informacion_perfileshard_cat.php | 2 +- .../php/cat/informacion_perfilessoft_cat.php | 2 +- .../php/cat/informacion_procedimientos_cat.php | 2 +- .../idiomas/php/cat/informacion_tareas_cat.php | 2 +- .../WebConsole/idiomas/php/cat/menucliente_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/menus_cat.php | 2 +- .../WebConsole/idiomas/php/cat/msgbrowser_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/nada_cat.php | 2 +- .../idiomas/php/cat/perfilcomponente_hard_cat.php | 2 +- .../idiomas/php/cat/perfilcomponente_soft_cat.php | 2 +- .../idiomas/php/cat/pintaParticiones_cat.php | 11 +- .../idiomas/php/cat/procedimientoscomandos_cat.php | 2 +- .../idiomas/php/cat/programaciones_cat.php | 2 +- .../idiomas/php/cat/programacionesaulas_cat.php | 2 +- .../idiomas/php/cat/programacionesreservas_cat.php | 2 +- .../idiomas/php/cat/propiedades_aulas_cat.php | 16 +- .../idiomas/php/cat/propiedades_centros_cat.php | 6 +- .../cat/propiedades_componentehardwares_cat.php | 2 +- .../cat/propiedades_componentesoftwares_cat.php | 2 +- .../idiomas/php/cat/propiedades_entidades_cat.php | 5 +- .../idiomas/php/cat/propiedades_entornos_cat.php | 2 +- .../idiomas/php/cat/propiedades_grupos_cat.php | 2 +- .../idiomas/php/cat/propiedades_imagenes_cat.php | 9 +- .../idiomas/php/cat/propiedades_menus_cat.php | 1 + .../php/cat/propiedades_ordenadores_cat.php | 26 +- .../php/cat/propiedades_ordenadorestandar_cat.php | 2 +- .../php/cat/propiedades_perfilsoftwares_cat.php | 2 +- .../php/cat/propiedades_procedimientos_cat.php | 2 +- .../php/cat/propiedades_repositorios_cat.php | 13 +- .../idiomas/php/cat/propiedades_reservas_cat.php | 2 +- .../idiomas/php/cat/propiedades_tareas_cat.php | 2 +- .../php/cat/propiedades_tipohardwares_cat.php | 2 +- .../php/cat/propiedades_universidades_cat.php | 2 +- .../idiomas/php/cat/propiedades_usuarios_cat.php | 14 +- admin/WebConsole/idiomas/php/cat/purgar_cat.php | 2 +- .../idiomas/php/cat/repositorios_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/reservas_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/softwares_cat.php | 2 +- admin/WebConsole/idiomas/php/cat/sondeo_cat.php | 2 +- .../idiomas/php/cat/tareascomandos_cat.php | 2 +- .../idiomas/php/cat/tiposhardwares_cat.php | 27 + admin/WebConsole/idiomas/php/eng/acceso_eng.php | 4 +- admin/WebConsole/idiomas/php/eng/acciones_eng.php | 2 +- .../WebConsole/idiomas/php/eng/accionmenu_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/acercade_eng.php | 6 +- .../WebConsole/idiomas/php/eng/actualizar_eng.php | 2 +- .../idiomas/php/eng/administracion_eng.php | 2 +- .../php/eng/administradores_centros_eng.php | 2 +- .../php/eng/administradores_usuarios_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/aulas_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/avisos_eng.php | 9 +- admin/WebConsole/idiomas/php/eng/barramenu_eng.php | 2 +- .../idiomas/php/eng/boot_grub4dos_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/buscar_eng.php | 2 +- .../idiomas/php/eng/clases/Almanaque_eng.php | 28 +- .../idiomas/php/eng/clases/Calendario_eng.php | 2 +- .../idiomas/php/eng/colasacciones_eng.php | 2 +- .../idiomas/php/eng/colasreservas_eng.php | 2 +- .../idiomas/php/eng/comandos/apagar_eng.php | 2 +- .../idiomas/php/eng/comandos/arrancar_eng.php | 2 +- .../idiomas/php/eng/comandos/configurar_eng.php | 2 + .../idiomas/php/eng/comandos/conmutar_eng.php | 2 +- .../idiomas/php/eng/comandos/crearimagen_eng.php | 2 +- .../php/eng/comandos/crearimagenbasica_eng.php | 2 +- .../php/eng/comandos/crearperfilsoftware_eng.php | 2 +- .../php/eng/comandos/crearsoftincremental_eng.php | 2 +- .../php/eng/comandos/ejecutarscripts_eng.php | 9 +- .../php/eng/comandos/eliminarimagencache_eng.php | 12 +- .../php/eng/comandos/eliminarimagenrepo_eng.php | 5 +- .../idiomas/php/eng/comandos/enviarmensaje_eng.php | 24 + .../eng/comandos/gestor_ejecutarscripts_eng.php | 2 +- .../idiomas/php/eng/comandos/mensajes_eng.php | 1 + .../php/eng/comandos/opcionesacciones_eng.php | 2 +- .../php/eng/comandos/particionaryformatear_eng.php | 2 +- .../idiomas/php/eng/comandos/reiniciar_eng.php | 2 +- .../idiomas/php/eng/comandos/rembooffline_eng.php | 2 +- .../php/eng/comandos/restaurarimagen_eng.php | 2 +- .../php/eng/comandos/restaurarimagenbasica_eng.php | 2 +- .../eng/comandos/restaurarsoftincremental_eng.php | 2 +- .../php/eng/comandos/tomaconfiguracion_eng.php | 2 +- .../idiomas/php/eng/configuraciones_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/conmutar_eng.php | 2 +- .../idiomas/php/eng/consolaremota_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/descargas_eng.php | 12 + admin/WebConsole/idiomas/php/eng/ecoremoto_eng.php | 2 +- .../idiomas/php/eng/ejecutaracciones_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/estados_eng.php | 7 +- .../idiomas/php/eng/gestor_ordenadores_eng.php | 10 + admin/WebConsole/idiomas/php/eng/hardwares_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/iconos_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/imagenes_eng.php | 2 +- .../idiomas/php/eng/imagenincremental_eng.php | 2 +- .../idiomas/php/eng/inclusionacciones_eng.php | 2 +- .../php/eng/incrementalcomponente_soft_eng.php | 2 +- .../idiomas/php/eng/informacion_acciones_eng.php | 2 +- .../idiomas/php/eng/informacion_imagenes_eng.php | 2 +- .../php/eng/informacion_incrementales_eng.php | 2 +- .../idiomas/php/eng/informacion_menus_eng.php | 2 +- .../php/eng/informacion_perfileshard_eng.php | 2 +- .../php/eng/informacion_perfilessoft_eng.php | 2 +- .../php/eng/informacion_procedimientos_eng.php | 2 +- .../php/eng/informacion_repositorio_eng.php | 2 +- .../idiomas/php/eng/informacion_tareas_eng.php | 2 +- .../WebConsole/idiomas/php/eng/menucliente_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/menus_eng.php | 2 +- .../WebConsole/idiomas/php/eng/msgbrowser_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/nada_eng.php | 2 +- .../idiomas/php/eng/perfilcomponente_hard_eng.php | 2 +- .../idiomas/php/eng/perfilcomponente_soft_eng.php | 2 +- .../idiomas/php/eng/pintaParticiones_eng.php | 49 +- .../idiomas/php/eng/procedimientoscomandos_eng.php | 2 +- .../idiomas/php/eng/programaciones_eng.php | 2 +- .../idiomas/php/eng/programacionesaulas_eng.php | 2 +- .../idiomas/php/eng/programacionesreservas_eng.php | 2 +- .../idiomas/php/eng/propiedades_aulas_eng.php | 26 +- .../idiomas/php/eng/propiedades_centros_eng.php | 4 +- .../eng/propiedades_componentehardwares_eng.php | 2 +- .../eng/propiedades_componentesoftwares_eng.php | 2 +- .../idiomas/php/eng/propiedades_entidades_eng.php | 3 +- .../idiomas/php/eng/propiedades_entornos_eng.php | 6 +- .../idiomas/php/eng/propiedades_grupos_eng.php | 2 +- .../idiomas/php/eng/propiedades_imagenes_eng.php | 9 +- .../idiomas/php/eng/propiedades_menus_eng.php | 1 + .../php/eng/propiedades_ordenadores_eng.php | 9 +- .../php/eng/propiedades_ordenadorestandar_eng.php | 2 +- .../php/eng/propiedades_perfilsoftwares_eng.php | 2 +- .../php/eng/propiedades_procedimientos_eng.php | 2 +- .../php/eng/propiedades_repositorios_eng.php | 13 +- .../idiomas/php/eng/propiedades_reservas_eng.php | 2 +- .../idiomas/php/eng/propiedades_tareas_eng.php | 2 +- .../php/eng/propiedades_tipohardwares_eng.php | 2 +- .../php/eng/propiedades_universidades_eng.php | 2 +- .../idiomas/php/eng/propiedades_usuarios_eng.php | 10 +- admin/WebConsole/idiomas/php/eng/purgar_eng.php | 2 +- .../idiomas/php/eng/repositorios_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/reservas_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/softwares_eng.php | 2 +- admin/WebConsole/idiomas/php/eng/sondeo_eng.php | 2 +- .../idiomas/php/eng/tareascomandos_eng.php | 2 +- .../idiomas/php/eng/tiposhardwares_eng.php | 5 +- admin/WebConsole/idiomas/php/esp/acceso_esp.php | 4 +- admin/WebConsole/idiomas/php/esp/acciones_esp.php | 2 +- .../WebConsole/idiomas/php/esp/accionmenu_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/acercade_esp.php | 6 +- .../WebConsole/idiomas/php/esp/actualizar_esp.php | 2 +- .../idiomas/php/esp/administracion_esp.php | 2 +- .../php/esp/administradores_centros_esp.php | 2 +- .../php/esp/administradores_usuarios_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/aulas_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/avisos_esp.php | 3 + admin/WebConsole/idiomas/php/esp/barramenu_esp.php | 2 +- .../idiomas/php/esp/boot_grub4dos_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/buscar_esp.php | 2 +- .../idiomas/php/esp/clases/Almanaque_esp.php | 34 +- .../idiomas/php/esp/clases/Calendario_esp.php | 2 +- .../idiomas/php/esp/colasacciones_esp.php | 2 +- .../idiomas/php/esp/colasreservas_esp.php | 2 +- .../idiomas/php/esp/comandos/apagar_esp.php | 2 +- .../idiomas/php/esp/comandos/arrancar_esp.php | 2 +- .../idiomas/php/esp/comandos/comando_esp.php | 2 +- .../idiomas/php/esp/comandos/configurar_esp.php | 2 + .../idiomas/php/esp/comandos/conmutar_esp.php | 2 +- .../idiomas/php/esp/comandos/crearimagen_esp.php | 2 +- .../php/esp/comandos/crearimagenbasica_esp.php | 2 +- .../php/esp/comandos/crearperfilsoftware_esp.php | 2 +- .../php/esp/comandos/crearsoftincremental_esp.php | 2 +- .../php/esp/comandos/ejecutarscripts_esp.php | 7 + .../php/esp/comandos/eliminarimagencache_esp.php | 10 +- .../php/esp/comandos/eliminarimagenrepo_esp.php | 3 +- .../idiomas/php/esp/comandos/enviarmensaje_esp.php | 24 + .../esp/comandos/gestor_ejecutarscripts_esp.php | 2 +- .../idiomas/php/esp/comandos/mensajes_esp.php | 8 +- .../php/esp/comandos/opcionesacciones_esp.php | 2 +- .../php/esp/comandos/particionaryformatear_esp.php | 2 +- .../idiomas/php/esp/comandos/reiniciar_esp.php | 2 +- .../idiomas/php/esp/comandos/rembooffline_esp.php | 2 +- .../php/esp/comandos/restaurarimagen_esp.php | 2 +- .../php/esp/comandos/restaurarimagenbasica_esp.php | 2 +- .../esp/comandos/restaurarsoftincremental_esp.php | 2 +- .../php/esp/comandos/tomaconfiguracion_esp.php | 2 +- .../idiomas/php/esp/configuraciones_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/conmutar_esp.php | 2 +- .../idiomas/php/esp/consolaremota_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/descargas_esp.php | 13 + admin/WebConsole/idiomas/php/esp/ecoremoto_esp.php | 2 +- .../idiomas/php/esp/ejecutaracciones_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/estados_esp.php | 7 +- .../idiomas/php/esp/gestor_ordenadores_esp.php | 10 + admin/WebConsole/idiomas/php/esp/hardwares_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/iconos_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/imagenes_esp.php | 2 +- .../idiomas/php/esp/imagenincremental_esp.php | 2 +- .../idiomas/php/esp/inclusionacciones_esp.php | 2 +- .../php/esp/incrementalcomponente_soft_esp.php | 2 +- .../idiomas/php/esp/informacion_acciones_esp.php | 2 +- .../idiomas/php/esp/informacion_imagenes_esp.php | 2 +- .../php/esp/informacion_incrementales_esp.php | 2 +- .../idiomas/php/esp/informacion_menus_esp.php | 2 +- .../php/esp/informacion_perfileshard_esp.php | 2 +- .../php/esp/informacion_perfilessoft_esp.php | 2 +- .../php/esp/informacion_procedimientos_esp.php | 2 +- .../idiomas/php/esp/informacion_tareas_esp.php | 2 +- .../WebConsole/idiomas/php/esp/menucliente_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/menus_esp.php | 2 +- .../WebConsole/idiomas/php/esp/msgbrowser_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/nada_esp.php | 2 +- .../idiomas/php/esp/perfilcomponente_hard_esp.php | 2 +- .../idiomas/php/esp/perfilcomponente_soft_esp.php | 2 +- .../idiomas/php/esp/pintaParticiones_esp.php | 11 +- .../idiomas/php/esp/procedimientoscomandos_esp.php | 2 +- .../idiomas/php/esp/programaciones_esp.php | 2 +- .../idiomas/php/esp/programacionesaulas_esp.php | 2 +- .../idiomas/php/esp/programacionesreservas_esp.php | 2 +- .../idiomas/php/esp/propiedades_aulas_esp.php | 16 +- .../idiomas/php/esp/propiedades_centros_esp.php | 5 +- .../esp/propiedades_componentehardwares_esp.php | 2 +- .../esp/propiedades_componentesoftwares_esp.php | 2 +- .../idiomas/php/esp/propiedades_entidades_esp.php | 4 +- .../idiomas/php/esp/propiedades_entornos_esp.php | 2 +- .../idiomas/php/esp/propiedades_grupos_esp.php | 2 +- .../idiomas/php/esp/propiedades_imagenes_esp.php | 29 +- .../idiomas/php/esp/propiedades_menus_esp.php | 3 +- .../php/esp/propiedades_ordenadores_esp.php | 8 +- .../php/esp/propiedades_ordenadorestandar_esp.php | 4 +- .../php/esp/propiedades_perfilsoftwares_esp.php | 2 +- .../php/esp/propiedades_procedimientos_esp.php | 2 +- .../php/esp/propiedades_repositorios_esp.php | 13 +- .../idiomas/php/esp/propiedades_reservas_esp.php | 2 +- .../idiomas/php/esp/propiedades_tareas_esp.php | 2 +- .../php/esp/propiedades_tipohardwares_esp.php | 2 +- .../php/esp/propiedades_universidades_esp.php | 2 +- .../idiomas/php/esp/propiedades_usuarios_esp.php | 11 +- admin/WebConsole/idiomas/php/esp/purgar_esp.php | 2 +- .../idiomas/php/esp/repositorios_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/reservas_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/softwares_esp.php | 2 +- admin/WebConsole/idiomas/php/esp/sondeo_esp.php | 2 +- .../idiomas/php/esp/tareascomandos_esp.php | 2 +- .../idiomas/php/esp/tiposhardwares_esp.php | 5 +- admin/WebConsole/images/L_Iconos.php | 36 +- admin/WebConsole/images/M_Iconos.php | 66 +- admin/WebConsole/images/iconos/almacenamiento.png | Bin 0 -> 448 bytes admin/WebConsole/images/iconos/arranque.png | Bin 0 -> 532 bytes admin/WebConsole/images/ordenador_BSY.gif | Bin 811 -> 0 bytes admin/WebConsole/images/ordenador_BSY.png | Bin 0 -> 762 bytes admin/WebConsole/images/ordenador_INI.gif | Bin 1117 -> 0 bytes admin/WebConsole/images/ordenador_INI.png | Bin 0 -> 1065 bytes admin/WebConsole/images/ordenador_LNX.gif | Bin 801 -> 0 bytes admin/WebConsole/images/ordenador_LNX.png | Bin 0 -> 746 bytes admin/WebConsole/images/ordenador_LNXS.png | Bin 0 -> 729 bytes admin/WebConsole/images/ordenador_OFF.gif | Bin 810 -> 0 bytes admin/WebConsole/images/ordenador_OFF.png | Bin 0 -> 778 bytes admin/WebConsole/images/ordenador_OPG.gif | Bin 1060 -> 0 bytes admin/WebConsole/images/ordenador_OPG.png | Bin 0 -> 756 bytes admin/WebConsole/images/ordenador_OSX.png | Bin 0 -> 901 bytes admin/WebConsole/images/ordenador_W2K.gif | Bin 804 -> 0 bytes admin/WebConsole/images/ordenador_W95.gif | Bin 798 -> 0 bytes admin/WebConsole/images/ordenador_W98.gif | Bin 808 -> 0 bytes admin/WebConsole/images/ordenador_WIN.png | Bin 0 -> 747 bytes admin/WebConsole/images/ordenador_WINS.png | Bin 0 -> 733 bytes admin/WebConsole/images/ordenador_WML.gif | Bin 804 -> 0 bytes admin/WebConsole/images/ordenador_WXP.gif | Bin 801 -> 0 bytes admin/WebConsole/images/ver.php | 2 +- .../includes/ConfiguracionesParticiones.php | 161 ++- admin/WebConsole/includes/CreaComando.php | 2 +- admin/WebConsole/includes/CreaTablaParametros.php | 2 +- admin/WebConsole/includes/HTMLCTEMULSELECT.php | 2 +- admin/WebConsole/includes/HTMLMULSELECT.php | 2 +- admin/WebConsole/includes/HTMLSELECT.php | 2 +- admin/WebConsole/includes/InvFecha.php | 6 +- admin/WebConsole/includes/RecopilaIpesMacs.php | 25 +- admin/WebConsole/includes/RedireccionaError.php | 2 +- admin/WebConsole/includes/TomaDato.php | 2 +- admin/WebConsole/includes/TomanDatos.php | 2 +- admin/WebConsole/includes/comunes.php | 20 + admin/WebConsole/includes/cuestionacciones.php | 2 +- admin/WebConsole/includes/cuestionaccionescab.php | 2 +- admin/WebConsole/includes/opciones.php | 2 +- admin/WebConsole/includes/opcionesbotones.php | 4 +- admin/WebConsole/includes/opcionesbotonesop.php | 2 +- admin/WebConsole/includes/opcionesprotocolos.php | 22 +- admin/WebConsole/includes/pintaParticiones.php | 103 +- .../includes/pintaTablaConfiguraciones.php | 13 +- admin/WebConsole/includes/restfunctions.php | 72 ++ admin/WebConsole/includes/tftputils.php | 100 +- admin/WebConsole/index.php | 24 +- admin/WebConsole/jscripts/aula.js | 39 +- admin/WebConsole/jscripts/aulas.js | 5 +- admin/WebConsole/jscripts/comunes.js | 1 + admin/WebConsole/jscripts/propiedades_aulas.js | 1 + admin/WebConsole/jscripts/propiedades_centros.js | 18 +- admin/WebConsole/jscripts/propiedades_entidades.js | 24 +- admin/WebConsole/jscripts/propiedades_imagenes.js | 1 - .../WebConsole/jscripts/propiedades_ordenadores.js | 4 +- admin/WebConsole/jscripts/propiedades_usuarios.js | 10 +- admin/WebConsole/jscripts/validators.js | 3 + admin/WebConsole/menus/examplemenu.html | 79 -- admin/WebConsole/menus/examplemenu.php | 94 ++ admin/WebConsole/menus/menuejemplo.html | 83 -- admin/WebConsole/menus/menuejemplo.php | 97 ++ admin/WebConsole/menus/privatemenu.php | 46 + admin/WebConsole/pagerror.php | 4 +- admin/WebConsole/principal/acciones.php | 10 +- admin/WebConsole/principal/acercade.php | 19 +- admin/WebConsole/principal/actualizar.php | 2 +- admin/WebConsole/principal/administracion.php | 11 +- admin/WebConsole/principal/aula.php | 34 +- admin/WebConsole/principal/aulas.php | 32 +- admin/WebConsole/principal/boot_grub4dos.php | 10 +- admin/WebConsole/principal/boot_grub4dos_crear.php | 126 +- admin/WebConsole/principal/boot_grub4dos_tabla.php | 30 +- admin/WebConsole/principal/boot_pxelinux.php | 217 ---- admin/WebConsole/principal/colasacciones.php | 48 +- admin/WebConsole/principal/colasreservas.php | 10 +- admin/WebConsole/principal/comandos.php | 16 +- admin/WebConsole/principal/configuraciones.php | 78 +- admin/WebConsole/principal/consolaremota.php | 24 +- admin/WebConsole/principal/ecoconsola.php | 2 +- admin/WebConsole/principal/ecoremoto.php | 20 +- admin/WebConsole/principal/hardwares.php | 10 +- admin/WebConsole/principal/imagenes.php | 18 +- admin/WebConsole/principal/menus.php | 10 +- admin/WebConsole/principal/programacionesaulas.php | 10 +- .../principal/programacionesreservas.php | 10 +- admin/WebConsole/principal/purgar.php | 2 +- admin/WebConsole/principal/repositorios.php | 8 +- admin/WebConsole/principal/reservas.php | 10 +- admin/WebConsole/principal/shellconsola.php | 2 +- admin/WebConsole/principal/softwares.php | 10 +- admin/WebConsole/principal/sondeo.php | 32 +- admin/WebConsole/principal/verlog.php | 6 +- admin/WebConsole/principal/verlogseguimiento.php | 6 +- admin/WebConsole/propiedades/propiedades_aulas.php | 254 ++-- .../WebConsole/propiedades/propiedades_centros.php | 60 +- .../propiedades_componentehardwares.php | 26 +- .../propiedades_componentesoftwares.php | 32 +- .../propiedades/propiedades_entidades.php | 57 +- .../propiedades/propiedades_entornos.php | 28 +- .../WebConsole/propiedades/propiedades_grupos.php | 24 +- .../propiedades/propiedades_imagenes.php | 314 +++-- admin/WebConsole/propiedades/propiedades_menus.php | 47 +- .../propiedades/propiedades_ordenadores.php | 100 +- .../propiedades/propiedades_ordenadorestandar.php | 44 +- .../propiedades/propiedades_perfilhardwares.php | 36 +- .../propiedades/propiedades_perfilsoftwares.php | 30 +- .../propiedades/propiedades_procedimientos.php | 26 +- .../propiedades/propiedades_repositorios.php | 191 +-- .../propiedades/propiedades_reservas.php | 62 +- .../WebConsole/propiedades/propiedades_tareas.php | 36 +- .../propiedades/propiedades_tipohardwares.php | 26 +- .../propiedades/propiedades_universidades.php | 24 +- .../propiedades/propiedades_usuarios.php | 126 +- admin/WebConsole/rest/common.php | 292 +++++ admin/WebConsole/rest/index.php | 75 ++ admin/WebConsole/rest/ogagent.php | 272 ++++ admin/WebConsole/rest/opengnsys-api.yml | 1300 ++++++++++++++++++++ admin/WebConsole/rest/remotepc.php | 553 +++++++++ admin/WebConsole/rest/repository.php | 215 ++++ admin/WebConsole/rest/server.php | 1041 ++++++++++++++++ admin/WebConsole/validacion/html/close.php | 2 +- admin/WebConsole/validacion/html/login_prueba.php | 4 +- .../WebConsole/validacion/html/validacion_ldap.php | 2 +- .../validacion/html/validacion_prueba.php | 2 +- .../validacion/html/validacion_template.php | 2 +- admin/WebConsole/varios/acceso_operador.php | 4 +- admin/WebConsole/varios/accesoperadores.php | 4 +- admin/WebConsole/varios/accionmenu.php | 28 +- .../WebConsole/varios/administradores_centros.php | 14 +- .../WebConsole/varios/administradores_usuarios.php | 14 +- admin/WebConsole/varios/calendario_ventana.php | 10 +- .../WebConsole/varios/consulta_programaciones.php | 2 +- admin/WebConsole/varios/desplegablesambitos.php | 2 +- admin/WebConsole/varios/ejecutaracciones.php | 16 +- admin/WebConsole/varios/ejecutaritem.php | 2 +- admin/WebConsole/varios/horareser_ventana.php | 4 +- admin/WebConsole/varios/horario_ventana.php | 4 +- admin/WebConsole/varios/incluiracciones.php | 38 +- admin/WebConsole/varios/inclusionacciones.php | 18 +- admin/WebConsole/varios/incorporaordenadores.php | 76 +- .../varios/incrementalcomponente_soft.php | 22 +- admin/WebConsole/varios/informacion_acciones.php | 2 +- admin/WebConsole/varios/informacion_imagenes.php | 29 +- admin/WebConsole/varios/informacion_menus.php | 20 +- .../varios/informacion_perfileshardware.php | 12 +- .../varios/informacion_perfilessoftware.php | 24 +- .../varios/informacion_procedimientos.php | 12 +- .../WebConsole/varios/informacion_repositorios.php | 8 +- admin/WebConsole/varios/informacion_tareas.php | 6 +- admin/WebConsole/varios/menubrowser.php | 4 +- admin/WebConsole/varios/msgbrowser.php | 4 +- admin/WebConsole/varios/perfilcomponente_hard.php | 35 +- admin/WebConsole/varios/perfilcomponente_soft.php | 31 +- admin/WebConsole/varios/procedimientoscomandos.php | 22 +- admin/WebConsole/varios/programaciones.php | 42 +- admin/WebConsole/varios/tareascomandos.php | 22 +- admin/WebConsole/varios/toma_mes.php | 2 +- admin/slim-2.6.1.zip | Bin 0 -> 58715 bytes admin/swagger-ui-2.2.5.zip | Bin 0 -> 955075 bytes client/README.es.txt | 8 +- client/boot-tools/INSTALL.es.txt | 9 +- client/boot-tools/boottoolsfunctions.lib | 102 +- client/boot-tools/boottoolsgenerator.sh | 21 +- .../includes/etc/apt/sources.list.ubuntu | 6 +- .../includes/etc/initramfs-tools/modules | 15 +- .../etc/initramfs-tools/scripts/VERSION.txt | 1 + .../etc/initramfs-tools/scripts/ogfunctions | 171 ++- .../includes/etc/initramfs-tools/scripts/oginit | 16 +- .../etc/modprobe.d/blacklist-framebuffer.conf | 3 +- .../usr/bin/boot-tools/boottoolsBootGraphics.sh | 5 +- .../usr/bin/boot-tools/boottoolsFsOpengnsys.sh | 19 +- .../usr/bin/boot-tools/boottoolsSoftwareCompile.sh | 34 +- .../usr/bin/boot-tools/boottoolsSoftwareInstall.sh | 53 +- .../usr/bin/boot-tools/listpackages/sw.Xwindow | 7 +- .../usr/bin/boot-tools/listpackages/sw.Zinitrd | 3 - .../usr/bin/boot-tools/listpackages/sw.basic | 6 +- .../usr/bin/boot-tools/listpackages/sw.cloning | 3 - .../usr/bin/boot-tools/listpackages/sw.compile | 7 +- .../usr/bin/boot-tools/listpackages/sw.compresor | 3 +- .../boot-tools/listpackages/sw.filesystem.local | 18 +- .../boot-tools/listpackages/sw.filesystem.remote | 3 +- .../usr/bin/boot-tools/listpackages/sw.networking | 7 +- .../usr/bin/boot-tools/listpackages/sw.testing | 21 +- .../busybox-static_1.17.1-10ubuntu1_i386.deb | Bin 747212 -> 0 bytes .../archivesOG/busybox_1.17.1-10ubuntu1_i386.deb | Bin 290464 -> 0 bytes .../cache/apt/archivesOG/partclone_0.2.38_i386.deb | Bin 6319500 -> 0 bytes .../apt/archivesOG/partclone_0.2.7-1drbl_i386.deb | Bin 5023908 -> 0 bytes .../cache/apt/archivesOG/partclone_0.2.8_i386.deb | Bin 5025002 -> 0 bytes .../includes/var/cache/apt/archivesOG/xvesa.deb | Bin 541364 -> 0 bytes .../includes/var/lib/locales/supported.d/local | 4 +- client/boot-tools/kernelParameterOG.es.txt | 2 +- client/browser/browser.pro | 2 +- client/browser/digitalclock/digitalclock.cpp | 72 ++ client/browser/digitalclock/digitalclock.h | 59 + client/browser/digitalclock/digitalclock.pro | 23 + client/browser/po/ca.po | 110 ++ client/browser/po/en.po | 112 ++ client/browser/src/main.cpp | 20 +- client/browser/src/mainwindow.cpp | 145 ++- client/browser/src/mainwindow.h | 9 +- client/browser/src/src.pro | 4 +- client/engine/Boot.lib | 1162 +++++++++++++++-- client/engine/Cache.lib | 85 +- client/engine/Disk.lib | 379 ++++-- client/engine/File.lib | 33 +- client/engine/FileSystem.lib | 201 ++- client/engine/Image.lib | 348 +++++- client/engine/Inventory.lib | 305 +++-- client/engine/Net.lib | 61 +- client/engine/PostConf.lib | 147 ++- client/engine/PostConfEAC.lib | 93 ++ client/engine/Protocol.lib | 106 +- client/engine/README.es.txt | 8 +- client/engine/Registry.lib | 84 +- client/engine/Rsync.lib | 83 +- client/engine/System.lib | 45 +- client/shared/README.es.txt | 10 +- client/shared/bin/browser | Bin 442268 -> 430012 bytes client/shared/bin/grub-probe1.99 | Bin 358216 -> 0 bytes client/shared/bin/grub-probe1.99_i686 | Bin 0 -> 358216 bytes client/shared/bin/grub-probe1.99_x86_64 | Bin 0 -> 336600 bytes client/shared/bin/poweroffconf | 5 +- client/shared/etc/engine.cfg | 17 +- client/shared/etc/init/default.sh | 13 +- client/shared/etc/lang.ca_ES.conf | 118 +- client/shared/etc/lang.en_GB.conf | 118 +- client/shared/etc/lang.es_ES.conf | 119 +- client/shared/etc/preinit/default.sh | 4 +- client/shared/etc/preinit/fileslinks.sh | 6 +- client/shared/etc/preinit/loadenviron.sh | 6 +- client/shared/etc/preinit/metadevs.sh | 6 +- client/shared/etc/preinit/mountrepo.sh | 5 +- client/shared/etc/preinit/otherservices.sh | 4 +- client/shared/etc/preinit/poweroff.sh | 11 +- .../burg/themes/OpenGnsys/background-original.png | Bin 0 -> 136 bytes .../lib/burg/themes/OpenGnsys/background.png | Bin 0 -> 74953 bytes client/shared/lib/burg/themes/OpenGnsys/extended | 79 ++ .../burg/themes/OpenGnsys/icons/hover_debian.png | Bin 0 -> 3715 bytes .../themes/OpenGnsys/icons/hover_elementary.png | Bin 0 -> 5496 bytes .../burg/themes/OpenGnsys/icons/hover_freebsd.png | Bin 0 -> 4416 bytes .../burg/themes/OpenGnsys/icons/hover_haiku.png | Bin 0 -> 1912 bytes .../burg/themes/OpenGnsys/icons/hover_linux.png | Bin 0 -> 33041 bytes .../themes/OpenGnsys/icons/hover_opengnsys.png | Bin 0 -> 11389 bytes .../burg/themes/OpenGnsys/icons/hover_opensuse.png | Bin 0 -> 4429 bytes .../lib/burg/themes/OpenGnsys/icons/hover_os.png | Bin 0 -> 4586 bytes .../lib/burg/themes/OpenGnsys/icons/hover_osx.png | Bin 0 -> 2457 bytes .../burg/themes/OpenGnsys/icons/hover_recovery.png | Bin 0 -> 4442 bytes .../burg/themes/OpenGnsys/icons/hover_restart.png | Bin 0 -> 5057 bytes .../burg/themes/OpenGnsys/icons/hover_shutdown.png | Bin 0 -> 4539 bytes .../burg/themes/OpenGnsys/icons/hover_ubuntu.png | Bin 0 -> 14374 bytes .../burg/themes/OpenGnsys/icons/hover_windows.png | Bin 0 -> 20160 bytes .../themes/OpenGnsys/icons/hover_windows10.png | Bin 0 -> 5101 bytes .../burg/themes/OpenGnsys/icons/hover_windows7.png | Bin 0 -> 18024 bytes .../themes/OpenGnsys/icons/hover_windows_metro.png | Bin 0 -> 1583 bytes .../shared/lib/burg/themes/OpenGnsys/icons/icons | 21 + .../burg/themes/OpenGnsys/icons/normal_debian.png | Bin 0 -> 3451 bytes .../themes/OpenGnsys/icons/normal_elementary.png | Bin 0 -> 5204 bytes .../burg/themes/OpenGnsys/icons/normal_freebsd.png | Bin 0 -> 4080 bytes .../burg/themes/OpenGnsys/icons/normal_haiku.png | Bin 0 -> 1652 bytes .../burg/themes/OpenGnsys/icons/normal_linux.png | Bin 0 -> 33691 bytes .../themes/OpenGnsys/icons/normal_opengnsys.png | Bin 0 -> 11119 bytes .../themes/OpenGnsys/icons/normal_opensuse.png | Bin 0 -> 4059 bytes .../lib/burg/themes/OpenGnsys/icons/normal_os.png | Bin 0 -> 4242 bytes .../lib/burg/themes/OpenGnsys/icons/normal_osx.png | Bin 0 -> 2066 bytes .../themes/OpenGnsys/icons/normal_recovery.png | Bin 0 -> 4081 bytes .../burg/themes/OpenGnsys/icons/normal_restart.png | Bin 0 -> 4718 bytes .../themes/OpenGnsys/icons/normal_shutdown.png | Bin 0 -> 4182 bytes .../burg/themes/OpenGnsys/icons/normal_ubuntu.png | Bin 0 -> 14036 bytes .../burg/themes/OpenGnsys/icons/normal_windows.png | Bin 0 -> 20637 bytes .../themes/OpenGnsys/icons/normal_windows10.png | Bin 0 -> 4791 bytes .../themes/OpenGnsys/icons/normal_windows7.png | Bin 0 -> 17786 bytes .../OpenGnsys/icons/normal_windows_metro.png | Bin 0 -> 1280 bytes .../burg/themes/OpenGnsys/images/000-70opaque.png | Bin 0 -> 109 bytes .../lib/burg/themes/OpenGnsys/images/button-bg.png | Bin 0 -> 146 bytes .../themes/OpenGnsys/images/button-hover-bg.png | Bin 0 -> 146 bytes .../themes/OpenGnsys/images/button-hover-l.png | Bin 0 -> 525 bytes .../themes/OpenGnsys/images/button-hover-r.png | Bin 0 -> 671 bytes .../lib/burg/themes/OpenGnsys/images/button-l.png | Bin 0 -> 725 bytes .../lib/burg/themes/OpenGnsys/images/button-r.png | Bin 0 -> 562 bytes .../themes/OpenGnsys/images/button-tools-hover.png | Bin 0 -> 1550 bytes .../burg/themes/OpenGnsys/images/button-tools.png | Bin 0 -> 1398 bytes .../burg/themes/OpenGnsys/images/container-b.png | Bin 0 -> 153 bytes .../burg/themes/OpenGnsys/images/container-bg.png | Bin 0 -> 146 bytes .../burg/themes/OpenGnsys/images/container-bl.png | Bin 0 -> 154 bytes .../burg/themes/OpenGnsys/images/container-br.png | Bin 0 -> 154 bytes .../burg/themes/OpenGnsys/images/container-l.png | Bin 0 -> 155 bytes .../burg/themes/OpenGnsys/images/container-r.png | Bin 0 -> 148 bytes .../burg/themes/OpenGnsys/images/container-t.png | Bin 0 -> 159 bytes .../themes/OpenGnsys/images/container-title-bg.png | Bin 0 -> 144 bytes .../themes/OpenGnsys/images/container-title-l.png | Bin 0 -> 139 bytes .../themes/OpenGnsys/images/container-title-r.png | Bin 0 -> 139 bytes .../themes/OpenGnsys/images/container-title-t.png | Bin 0 -> 151 bytes .../themes/OpenGnsys/images/container-title-tl.png | Bin 0 -> 181 bytes .../themes/OpenGnsys/images/container-title-tr.png | Bin 0 -> 188 bytes .../burg/themes/OpenGnsys/images/container-tl.png | Bin 0 -> 154 bytes .../burg/themes/OpenGnsys/images/container-tr.png | Bin 0 -> 154 bytes .../lib/burg/themes/OpenGnsys/images/dialog-b.png | Bin 0 -> 135 bytes .../lib/burg/themes/OpenGnsys/images/dialog-bg.png | Bin 0 -> 144 bytes .../lib/burg/themes/OpenGnsys/images/dialog-bl.png | Bin 0 -> 177 bytes .../lib/burg/themes/OpenGnsys/images/dialog-bl.xcf | Bin 0 -> 889 bytes .../lib/burg/themes/OpenGnsys/images/dialog-br.png | Bin 0 -> 168 bytes .../lib/burg/themes/OpenGnsys/images/dialog-lr.png | Bin 0 -> 131 bytes .../burg/themes/OpenGnsys/images/dialog-spacer.png | Bin 0 -> 140 bytes .../lib/burg/themes/OpenGnsys/images/dialog-t.png | Bin 0 -> 135 bytes .../lib/burg/themes/OpenGnsys/images/dialog-tl.png | Bin 0 -> 181 bytes .../lib/burg/themes/OpenGnsys/images/dialog-tr.png | Bin 0 -> 188 bytes .../themes/OpenGnsys/images/progressbar-bg-b.png | Bin 0 -> 156 bytes .../themes/OpenGnsys/images/progressbar-bg-bl.png | Bin 0 -> 169 bytes .../themes/OpenGnsys/images/progressbar-bg-br.png | Bin 0 -> 215 bytes .../themes/OpenGnsys/images/progressbar-bg-l.png | Bin 0 -> 346 bytes .../themes/OpenGnsys/images/progressbar-bg-r.png | Bin 0 -> 165 bytes .../themes/OpenGnsys/images/progressbar-bg-t.png | Bin 0 -> 155 bytes .../themes/OpenGnsys/images/progressbar-bg-tl.png | Bin 0 -> 183 bytes .../themes/OpenGnsys/images/progressbar-bg-tr.png | Bin 0 -> 186 bytes .../themes/OpenGnsys/images/progressbar-bg.png | Bin 0 -> 152 bytes .../burg/themes/OpenGnsys/images/text-line-l.png | Bin 0 -> 254 bytes .../burg/themes/OpenGnsys/images/text-line-r.png | Bin 0 -> 260 bytes .../lib/burg/themes/OpenGnsys/images/tick.png | Bin 0 -> 253 bytes .../lib/burg/themes/OpenGnsys/images/txt-about.png | Bin 0 -> 905 bytes .../lib/burg/themes/OpenGnsys/images/txt-help.png | Bin 0 -> 423 bytes .../burg/themes/OpenGnsys/images/txt-select.png | Bin 0 -> 4367 bytes .../lib/burg/themes/OpenGnsys/images/txt-tools.png | Bin 0 -> 474 bytes .../themes/OpenGnsys/images/ubuntu-glow-96.png | Bin 0 -> 9155 bytes client/shared/lib/burg/themes/OpenGnsys/menus | 188 +++ client/shared/lib/burg/themes/OpenGnsys/style | 158 +++ client/shared/lib/burg/themes/OpenGnsys/theme | 231 ++++ client/shared/lib/engine/tests/Modify/Cache.shtest | 8 +- .../shared/lib/engine/tests/NoModify/Lock1.shtest | 10 +- client/shared/lib/engine/tests/crearTestLock2 | 4 +- client/shared/lib/httpd/httpd-log.sh | 5 +- client/shared/lib/httpd/httpd-runengine.sh | 1 + client/shared/lib/locale/ca/LC_MESSAGES/browser.mo | Bin 0 -> 899 bytes client/shared/lib/locale/en/LC_MESSAGES/browser.mo | Bin 0 -> 2134 bytes client/shared/lib/os-probes/10zvol-test | 14 + client/shared/lib/os-probes/50mounted-tests | 99 ++ client/shared/lib/os-probes/init/10filesystems | 39 + client/shared/lib/os-probes/mounted/05efi | 71 ++ client/shared/lib/os-probes/mounted/10freedos | 23 + client/shared/lib/os-probes/mounted/10qnx | 21 + client/shared/lib/os-probes/mounted/20macosx | 30 + client/shared/lib/os-probes/mounted/20microsoft | 140 +++ client/shared/lib/os-probes/mounted/30utility | 33 + client/shared/lib/os-probes/mounted/40lsb | 48 + client/shared/lib/os-probes/mounted/70hurd | 16 + client/shared/lib/os-probes/mounted/80minix | 28 + client/shared/lib/os-probes/mounted/83haiku | 35 + client/shared/lib/os-probes/mounted/90linux-distro | 138 +++ client/shared/lib/os-probes/mounted/90solaris | 19 + client/shared/lib/os-probes/mounted/efi/10elilo | 24 + .../shared/lib/os-probes/mounted/efi/20microsoft | 28 + client/shared/lib/pictures/oglogo.png | Bin 0 -> 736 bytes client/shared/scripts/ImagenesSincronizadas.lib | 2 +- client/shared/scripts/README.es.txt | 19 +- client/shared/scripts/bootOs | 48 +- client/shared/scripts/bootOsCustom.template | 83 ++ client/shared/scripts/configureOs | 36 +- client/shared/scripts/createBaseImage | 10 +- client/shared/scripts/createDiffImage | 10 +- client/shared/scripts/createImage | 54 +- client/shared/scripts/deployImage | 38 +- client/shared/scripts/formatFs | 2 +- client/shared/scripts/grubSyntax | 83 +- client/shared/scripts/initCache | 77 +- client/shared/scripts/launchOgagentInstaller | 147 +++ client/shared/scripts/listHardwareInfo | 4 +- client/shared/scripts/listSoftwareInfo | 11 +- client/shared/scripts/menuBrowser | 3 +- client/shared/scripts/poweroff | 18 +- client/shared/scripts/reboot | 19 +- client/shared/scripts/restoreBaseImage | 2 +- client/shared/scripts/restoreDiffImage | 2 +- client/shared/scripts/restoreImage | 45 +- client/shared/scripts/restoreImageCustom.template | 13 +- client/shared/scripts/setBootMode | 32 +- client/shared/scripts/updateBootCache | 47 +- client/shared/scripts/updateCache | 72 +- doc/CHANGELOG.es.txt | 116 +- doc/INSTALL.en.txt | 28 +- doc/INSTALL.es.txt | 37 +- doc/README.en.txt | 29 +- doc/README.es.txt | 19 +- doc/VERSION.txt | 2 +- doc/filetree.en.txt | 15 +- doc/filetree.es.txt | 14 +- doc/userManual/Tema0-Laboratorio_virtual.pdf | Bin 0 -> 3544233 bytes doc/userManual/Tema1-Introduccion.pdf | Bin 312799 -> 1073113 bytes doc/userManual/Tema2-Instalacion.pdf | Bin 167663 -> 845442 bytes .../Tema3.1-Administracion_componentes.pdf | Bin 691692 -> 1020845 bytes .../Tema3.2-Administracion_consola_web.pdf | Bin 617183 -> 1289992 bytes .../Tema3.3-Administracion_unidad_organizativa.pdf | Bin 1475303 -> 2607159 bytes doc/userManual/Tema4-Ambito_aplicacion.pdf | Bin 568451 -> 2394682 bytes doc/userManual/Tema5-Particionado_discos.pdf | Bin 644412 -> 1455816 bytes doc/userManual/Tema6.1-Creacion_imagenes.pdf | Bin 652924 -> 1939762 bytes .../Tema6.2-Restauracion_y_despliegue_imagenes.pdf | Bin 2055792 -> 2487581 bytes doc/userManual/Tema6.3-Eliminacion_imagenes.pdf | Bin 190772 -> 1017185 bytes doc/userManual/Tema7-Acciones_y_menus_usuario.pdf | Bin 1079262 -> 1666428 bytes installer/INSTALL.en.txt | 12 +- installer/INSTALL.es.txt | 14 +- installer/README.es.txt | 11 +- installer/ogGenerateDoc.sh | 6 +- installer/ogagent-devel-installer.sh | 113 ++ installer/ogagentpkgs-1.1.0.tar.gz | Bin 0 -> 17012444 bytes installer/opengnsys_export.sh | 114 ++ installer/opengnsys_import.sh | 331 +++++ installer/opengnsys_installer.sh | 402 +++--- installer/opengnsys_makecompress.sh | 4 +- installer/opengnsys_uninstall.sh | 34 +- installer/opengnsys_update.sh | 485 +++++--- installer/vagrant/README.es.txt | 75 ++ installer/vagrant/Vagrantfile-1.0.6b-vbox | 152 +++ installer/vagrant/Vagrantfile-boottools-vbox | 55 + installer/vagrant/Vagrantfile-browser-vbox | 69 ++ installer/vagrant/Vagrantfile-devel-vbox | 185 +++ installer/vagrant/Vagrantfile-ogagent-vbox | 72 ++ installer/vagrant/Vagrantfile-trunk-vbox | 164 +++ repoman/README.es.txt | 4 +- repoman/bin/checkrepo | 230 ++++ repoman/bin/createfileimage | 65 + repoman/bin/deleteimage | 19 +- repoman/bin/deletepreimage | 66 +- repoman/bin/mountimage | 71 ++ repoman/bin/opengnsys.cron | 4 +- repoman/bin/partclone2sync | 178 +++ repoman/bin/reduceimage | 58 + repoman/bin/torrent-creator | 4 +- repoman/bin/unmountimage | 52 + server/README.es.txt | 5 +- server/bin/checkperms | 27 +- server/bin/comparedhcpopengnsys | 2 +- server/bin/comparemac | 2 +- server/bin/createfileimage | 61 - server/bin/installmodule | 97 ++ server/bin/installoglive | 95 +- server/bin/listclientlive | 50 + server/bin/listclientmode | 2 +- server/bin/mountimage | 66 - server/bin/ogagentqueue.cron | 100 ++ server/bin/oglivecli | 482 ++++++++ server/bin/partclone2sync | 174 --- server/bin/reduceimage | 54 - server/bin/registeredsoftware | 23 +- server/bin/setclientlive | 73 ++ server/bin/setclientmode | 101 +- server/bin/setserveraddr | 4 +- server/bin/setsmbpass | 126 +- server/bin/unmountimage | 47 - server/etc/apache-prev2.4.conf.tmpl | 18 +- server/etc/apache.conf.tmpl | 18 +- server/etc/dhcpd.conf.tmpl | 11 + server/etc/smb-og.conf.tmpl | 8 +- server/lib/security-config | 86 ++ server/tftpboot/NetbootPXE.es.txt | 10 +- server/tftpboot/menu.lst/templates/00unknown | 1 - server/tftpboot/menu.lst/templates/01 | 1 - server/tftpboot/menu.lst/templates/11 | 1 - server/tftpboot/menu.lst/templates/12 | 1 - server/tftpboot/menu.lst/templates/19pxeADMIN | 17 +- server/tftpboot/menu.lst/templates/pxe | 29 +- 1008 files changed, 26454 insertions(+), 8384 deletions(-) create mode 100644 admin/Database/ogAdmBD-1.0.6b-1.1.0.sql delete mode 100644 admin/Database/ogAdmBD-1.0.6b-postinst.sql create mode 100644 admin/Database/ogAdmBD-1.1.0-postinst.sql create mode 100644 admin/Database/ogAdmBD-1.1.0pre-1.1.0.sql create mode 100644 admin/Sources/Clients/README.es.txt delete mode 100644 admin/Sources/Clients/ogAdmLnxClient/Makefile delete mode 100644 admin/Sources/Clients/ogAdmLnxClient/ogAdmLnxClient.cfg delete mode 100644 admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.c delete mode 100644 admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.h delete mode 100644 admin/Sources/Clients/ogAdmWinClient/Readme delete mode 100644 admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.cpp delete mode 100644 admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.h delete mode 100644 admin/Sources/Clients/ogAdmWinClient/sources/servicio.c delete mode 100644 admin/Sources/Clients/ogAdmWinClient/sources/servicio.h create mode 100644 admin/Sources/Clients/ogagent/INSTALL.es.txt create mode 100644 admin/Sources/Clients/ogagent/linux/Makefile create mode 100755 admin/Sources/Clients/ogagent/linux/build-packages.sh create mode 100644 admin/Sources/Clients/ogagent/linux/debian/changelog create mode 100644 admin/Sources/Clients/ogagent/linux/debian/compat create mode 100644 admin/Sources/Clients/ogagent/linux/debian/control create mode 100644 admin/Sources/Clients/ogagent/linux/debian/copyright create mode 100644 admin/Sources/Clients/ogagent/linux/debian/docs create mode 100644 admin/Sources/Clients/ogagent/linux/debian/ogagent.init create mode 100644 admin/Sources/Clients/ogagent/linux/debian/ogagent.links create mode 100644 admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst create mode 100644 admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst.debhelper create mode 100644 admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm create mode 100644 admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm.debhelper create mode 100644 admin/Sources/Clients/ogagent/linux/debian/ogagent.substvars create mode 100755 admin/Sources/Clients/ogagent/linux/debian/rules create mode 100644 admin/Sources/Clients/ogagent/linux/debian/source/format create mode 100644 admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop create mode 100644 admin/Sources/Clients/ogagent/linux/ogagent-template.spec create mode 100644 admin/Sources/Clients/ogagent/linux/policy/org.openuds.pkexec.UDSActorConfig.policy create mode 100644 admin/Sources/Clients/ogagent/linux/readme.txt create mode 100644 admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool create mode 100644 admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup create mode 100644 admin/Sources/Clients/ogagent/linux/scripts/ogagent create mode 100755 admin/Sources/Clients/ogagent/macos/build-pkg.sh create mode 100644 admin/Sources/Clients/ogagent/macos/scripts/es.opengnsys.ogagent.plist create mode 100755 admin/Sources/Clients/ogagent/macos/scripts/ogagent create mode 100755 admin/Sources/Clients/ogagent/macos/scripts/postinstall create mode 100644 admin/Sources/Clients/ogagent/requires.txt create mode 100644 admin/Sources/Clients/ogagent/src/OGAServiceHelper.py create mode 100644 admin/Sources/Clients/ogagent/src/OGAgent.manifest create mode 100644 admin/Sources/Clients/ogagent/src/OGAgent.qrc create mode 100644 admin/Sources/Clients/ogagent/src/OGAgentUser.py create mode 100644 admin/Sources/Clients/ogagent/src/OGAgent_rc.py create mode 100644 admin/Sources/Clients/ogagent/src/VERSION create mode 100644 admin/Sources/Clients/ogagent/src/about-dialog.ui create mode 100644 admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg create mode 100644 admin/Sources/Clients/ogagent/src/cfg/ogclient.cfg create mode 100644 admin/Sources/Clients/ogagent/src/img/oga-48x48.ico create mode 100644 admin/Sources/Clients/ogagent/src/img/oga-512.png create mode 100644 admin/Sources/Clients/ogagent/src/img/oga.ico create mode 100644 admin/Sources/Clients/ogagent/src/img/oga.png create mode 100644 admin/Sources/Clients/ogagent/src/license.txt create mode 100644 admin/Sources/Clients/ogagent/src/message-dialog.ui create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/certs.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/config.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/httpserver.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/ipc.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/OGAgentService.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/daemon.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/log.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/debian.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/opensuse.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/redhat.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/loader.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/log.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/macos/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/macos/operations.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/modules/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/modules/client/OpenGnSys/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/modules/client/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/modules/server/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/operations.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/scriptThread.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/service.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/utils.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/windows/OGAgentService.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/windows/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/windows/log.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/windows/operations.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/workers/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/workers/client_worker.py create mode 100644 admin/Sources/Clients/ogagent/src/opengnsys/workers/server_worker.py create mode 100644 admin/Sources/Clients/ogagent/src/prototypes/threaded_server.py create mode 100644 admin/Sources/Clients/ogagent/src/setup.py create mode 100644 admin/Sources/Clients/ogagent/src/test_modules/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/test_modules/client/Sample1/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/test_modules/client/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample1.py create mode 100644 admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample_pkg/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/test_modules/server/__init__.py create mode 100644 admin/Sources/Clients/ogagent/src/test_rest_server.py create mode 100755 admin/Sources/Clients/ogagent/src/update.sh create mode 100755 admin/Sources/Clients/ogagent/windows/build-windows.sh create mode 100644 admin/Sources/Clients/ogagent/windows/build.bat create mode 100644 admin/Sources/Clients/ogagent/windows/ogagent.nsi create mode 100755 admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh create mode 100644 admin/WebConsole/comandos/EnviarMensaje.php create mode 100644 admin/WebConsole/comandos/gestores/wakeonlan_repo.php create mode 100644 admin/WebConsole/comandos/jscripts/EnviarMensaje.js create mode 100644 admin/WebConsole/descargas/README.es.html create mode 100644 admin/WebConsole/descargas/index.php create mode 100644 admin/WebConsole/idiomas/javascripts/cat/asistentes_cat.js create mode 100644 admin/WebConsole/idiomas/javascripts/cat/comandos/enviarmensaje_cat.js create mode 100644 admin/WebConsole/idiomas/javascripts/eng/asistentes_eng.js create mode 100644 admin/WebConsole/idiomas/javascripts/eng/comandos/enviarmensaje_eng.js create mode 100644 admin/WebConsole/idiomas/javascripts/esp/asistentes_esp.js create mode 100644 admin/WebConsole/idiomas/javascripts/esp/comandos/enviarmensaje_esp.js create mode 100644 admin/WebConsole/idiomas/php/cat/comandos/enviarmensaje_cat.php create mode 100644 admin/WebConsole/idiomas/php/cat/descargas_cat.php create mode 100644 admin/WebConsole/idiomas/php/cat/gestor_ordenadores_cat.php create mode 100644 admin/WebConsole/idiomas/php/cat/tiposhardwares_cat.php create mode 100644 admin/WebConsole/idiomas/php/eng/comandos/enviarmensaje_eng.php create mode 100644 admin/WebConsole/idiomas/php/eng/descargas_eng.php create mode 100644 admin/WebConsole/idiomas/php/eng/gestor_ordenadores_eng.php create mode 100644 admin/WebConsole/idiomas/php/esp/comandos/enviarmensaje_esp.php create mode 100644 admin/WebConsole/idiomas/php/esp/descargas_esp.php create mode 100644 admin/WebConsole/idiomas/php/esp/gestor_ordenadores_esp.php create mode 100644 admin/WebConsole/images/iconos/almacenamiento.png create mode 100644 admin/WebConsole/images/iconos/arranque.png delete mode 100644 admin/WebConsole/images/ordenador_BSY.gif create mode 100644 admin/WebConsole/images/ordenador_BSY.png delete mode 100644 admin/WebConsole/images/ordenador_INI.gif create mode 100644 admin/WebConsole/images/ordenador_INI.png delete mode 100644 admin/WebConsole/images/ordenador_LNX.gif create mode 100644 admin/WebConsole/images/ordenador_LNX.png create mode 100644 admin/WebConsole/images/ordenador_LNXS.png delete mode 100644 admin/WebConsole/images/ordenador_OFF.gif create mode 100644 admin/WebConsole/images/ordenador_OFF.png delete mode 100644 admin/WebConsole/images/ordenador_OPG.gif create mode 100644 admin/WebConsole/images/ordenador_OPG.png create mode 100644 admin/WebConsole/images/ordenador_OSX.png delete mode 100644 admin/WebConsole/images/ordenador_W2K.gif delete mode 100644 admin/WebConsole/images/ordenador_W95.gif delete mode 100644 admin/WebConsole/images/ordenador_W98.gif create mode 100644 admin/WebConsole/images/ordenador_WIN.png create mode 100644 admin/WebConsole/images/ordenador_WINS.png delete mode 100644 admin/WebConsole/images/ordenador_WML.gif delete mode 100644 admin/WebConsole/images/ordenador_WXP.gif create mode 100644 admin/WebConsole/includes/restfunctions.php delete mode 100644 admin/WebConsole/menus/examplemenu.html create mode 100644 admin/WebConsole/menus/examplemenu.php delete mode 100644 admin/WebConsole/menus/menuejemplo.html create mode 100644 admin/WebConsole/menus/menuejemplo.php create mode 100644 admin/WebConsole/menus/privatemenu.php delete mode 100644 admin/WebConsole/principal/boot_pxelinux.php create mode 100644 admin/WebConsole/rest/common.php create mode 100644 admin/WebConsole/rest/index.php create mode 100644 admin/WebConsole/rest/ogagent.php create mode 100644 admin/WebConsole/rest/opengnsys-api.yml create mode 100644 admin/WebConsole/rest/remotepc.php create mode 100644 admin/WebConsole/rest/repository.php create mode 100644 admin/WebConsole/rest/server.php create mode 100644 admin/slim-2.6.1.zip create mode 100644 admin/swagger-ui-2.2.5.zip create mode 100644 client/boot-tools/includes/etc/initramfs-tools/scripts/VERSION.txt delete mode 100644 client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Zinitrd delete mode 100644 client/boot-tools/includes/var/cache/apt/archivesOG/busybox-static_1.17.1-10ubuntu1_i386.deb delete mode 100644 client/boot-tools/includes/var/cache/apt/archivesOG/busybox_1.17.1-10ubuntu1_i386.deb delete mode 100644 client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.38_i386.deb delete mode 100755 client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.7-1drbl_i386.deb delete mode 100755 client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.8_i386.deb delete mode 100644 client/boot-tools/includes/var/cache/apt/archivesOG/xvesa.deb create mode 100644 client/browser/digitalclock/digitalclock.cpp create mode 100644 client/browser/digitalclock/digitalclock.h create mode 100644 client/browser/digitalclock/digitalclock.pro create mode 100644 client/browser/po/ca.po create mode 100644 client/browser/po/en.po delete mode 100755 client/shared/bin/grub-probe1.99 create mode 100755 client/shared/bin/grub-probe1.99_i686 create mode 100755 client/shared/bin/grub-probe1.99_x86_64 create mode 100644 client/shared/lib/burg/themes/OpenGnsys/background-original.png create mode 100755 client/shared/lib/burg/themes/OpenGnsys/background.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/extended create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_debian.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_elementary.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_freebsd.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_haiku.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_linux.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_opengnsys.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_opensuse.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_os.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_osx.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_recovery.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_restart.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_shutdown.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_ubuntu.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows10.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows7.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows_metro.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/icons create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_debian.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_elementary.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_freebsd.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_haiku.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_linux.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_opengnsys.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_opensuse.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_os.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_osx.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_recovery.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_restart.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_shutdown.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_ubuntu.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows10.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows7.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows_metro.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/000-70opaque.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-bg.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-hover-bg.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-hover-l.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-hover-r.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-l.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-r.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-tools-hover.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/button-tools.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-b.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-bg.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-bl.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-br.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-l.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-r.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-t.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-title-bg.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-title-l.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-title-r.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-title-t.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-title-tl.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-title-tr.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-tl.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/container-tr.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-b.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-bg.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.xcf create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-br.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-lr.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-spacer.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-t.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-tl.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/dialog-tr.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-b.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-bl.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-br.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-l.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-r.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-t.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tl.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tr.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/text-line-l.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/text-line-r.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/tick.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/txt-about.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/txt-help.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/txt-select.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/txt-tools.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/images/ubuntu-glow-96.png create mode 100644 client/shared/lib/burg/themes/OpenGnsys/menus create mode 100644 client/shared/lib/burg/themes/OpenGnsys/style create mode 100644 client/shared/lib/burg/themes/OpenGnsys/theme create mode 100644 client/shared/lib/locale/ca/LC_MESSAGES/browser.mo create mode 100644 client/shared/lib/locale/en/LC_MESSAGES/browser.mo create mode 100755 client/shared/lib/os-probes/10zvol-test create mode 100755 client/shared/lib/os-probes/50mounted-tests create mode 100755 client/shared/lib/os-probes/init/10filesystems create mode 100755 client/shared/lib/os-probes/mounted/05efi create mode 100755 client/shared/lib/os-probes/mounted/10freedos create mode 100755 client/shared/lib/os-probes/mounted/10qnx create mode 100755 client/shared/lib/os-probes/mounted/20macosx create mode 100755 client/shared/lib/os-probes/mounted/20microsoft create mode 100755 client/shared/lib/os-probes/mounted/30utility create mode 100755 client/shared/lib/os-probes/mounted/40lsb create mode 100755 client/shared/lib/os-probes/mounted/70hurd create mode 100755 client/shared/lib/os-probes/mounted/80minix create mode 100755 client/shared/lib/os-probes/mounted/83haiku create mode 100755 client/shared/lib/os-probes/mounted/90linux-distro create mode 100755 client/shared/lib/os-probes/mounted/90solaris create mode 100755 client/shared/lib/os-probes/mounted/efi/10elilo create mode 100755 client/shared/lib/os-probes/mounted/efi/20microsoft create mode 100644 client/shared/lib/pictures/oglogo.png create mode 100755 client/shared/scripts/bootOsCustom.template create mode 100755 client/shared/scripts/launchOgagentInstaller create mode 100644 doc/userManual/Tema0-Laboratorio_virtual.pdf create mode 100755 installer/ogagent-devel-installer.sh create mode 100644 installer/ogagentpkgs-1.1.0.tar.gz create mode 100755 installer/opengnsys_export.sh create mode 100755 installer/opengnsys_import.sh create mode 100644 installer/vagrant/README.es.txt create mode 100644 installer/vagrant/Vagrantfile-1.0.6b-vbox create mode 100644 installer/vagrant/Vagrantfile-boottools-vbox create mode 100644 installer/vagrant/Vagrantfile-browser-vbox create mode 100644 installer/vagrant/Vagrantfile-devel-vbox create mode 100644 installer/vagrant/Vagrantfile-ogagent-vbox create mode 100644 installer/vagrant/Vagrantfile-trunk-vbox create mode 100755 repoman/bin/checkrepo create mode 100755 repoman/bin/createfileimage create mode 100755 repoman/bin/mountimage create mode 100755 repoman/bin/partclone2sync create mode 100755 repoman/bin/reduceimage create mode 100755 repoman/bin/unmountimage delete mode 100755 server/bin/createfileimage create mode 100755 server/bin/installmodule mode change 100755 => 120000 server/bin/installoglive create mode 100755 server/bin/listclientlive delete mode 100755 server/bin/mountimage create mode 100755 server/bin/ogagentqueue.cron create mode 100755 server/bin/oglivecli delete mode 100755 server/bin/partclone2sync delete mode 100755 server/bin/reduceimage create mode 100755 server/bin/setclientlive delete mode 100755 server/bin/unmountimage create mode 100755 server/lib/security-config diff --git a/admin/Database/ogAdmBD-1.0.6a-1.0.6b.sql b/admin/Database/ogAdmBD-1.0.6a-1.0.6b.sql index f5fa8b19..c772ee3e 100644 --- a/admin/Database/ogAdmBD-1.0.6a-1.0.6b.sql +++ b/admin/Database/ogAdmBD-1.0.6a-1.0.6b.sql @@ -1,12 +1,12 @@ +### Fichero de actualización de la base de datos. # OpenGnSys 1.0.6, 1.0.6a - 1.0.6b #use ogAdmBD -ALTER TABLE ordenadores - ADD INDEX idaulaip (idaula ASC, ip ASC); - -# Añadir nuevos sistemas de ficheros (ticket #758) INSERT INTO sistemasficheros (idsistemafichero, nemonico, descripcion) VALUES (19, 'LINUX-SWAP', 'LINUX-SWAP') ON DUPLICATE KEY UPDATE idsistemafichero=VALUES(idsistemafichero), nemonico=VALUES(nemonico), descripcion=VALUES(descripcion); +ALTER TABLE ordenadores + ADD INDEX idaulaip (idaula ASC, ip ASC); + diff --git a/admin/Database/ogAdmBD-1.0.6b-1.1.0.sql b/admin/Database/ogAdmBD-1.0.6b-1.1.0.sql new file mode 100644 index 00000000..6b7ad95e --- /dev/null +++ b/admin/Database/ogAdmBD-1.0.6b-1.1.0.sql @@ -0,0 +1,161 @@ +### Fichero de actualización de la base de datos. +# OpenGnSys 1.0.6b - OpenGnsys 1.1.0 +#use ogAdmBD + +### NOTA: la configuración de MySQL solo puede modificarla el usuario "root". +# Soportar cláusuloas GROUP BY especiales para configuración de equipos. +#SET GLOBAL sql_mode = TRIM(BOTH ',' FROM REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', '')); +# Activar calendario de eventos de MySQL. +#SET GLOBAL event_scheduler = ON; + +# Nuevos tipos de particiones y de sistemas de ficheros (ticket #758). +INSERT INTO tipospar (codpar, tipopar, clonable) VALUES + (CONV('A9',16,10), 'NETBSD', 1), + (CONV('2700',16,10), 'WIN-RECOV', 1), + (CONV('8302',16,10), 'LINUX', 1), + (CONV('A504',16,10), 'FREEBSD', 1), + (CONV('A901',16,10), 'NETBSD-SWAP', 0), + (CONV('A902',16,10), 'NETBSD', 1), + (CONV('A903',16,10), 'NETBSD', 1), + (CONV('A904',16,10), 'NETBSD', 1), + (CONV('A905',16,10), 'NETBSD', 1), + (CONV('A906',16,10), 'NETBSD-RAID', 1), + (CONV('AF02',16,10), 'HFS-RAID', 1), + (CONV('FB00',16,10), 'VMFS', 1), + (CONV('FB01',16,10), 'VMFS-RESERV', 1), + (CONV('FB02',16,10), 'VMFS-KRN', 1), + (CONV('10000',16,10), 'LVM-LV', 1), + (CONV('10010',16,10), 'ZFS-VOL', 1) + ON DUPLICATE KEY UPDATE + codpar=VALUES(codpar), tipopar=VALUES(tipopar), clonable=VALUES(clonable); +INSERT INTO sistemasficheros (idsistemafichero, nemonico, descripcion) VALUES + (20, 'F2FS', 'F2FS'), + (21, 'NILFS2', 'NILFS2') + ON DUPLICATE KEY UPDATE + idsistemafichero=VALUES(idsistemafichero), nemonico=VALUES(nemonico), descripcion=VALUES(descripcion); + +# Eliminar campos sin uso (ticket #730). +# Añadir campos para aulas: servidor NTP e inclusión en proyecto Remote PC (tickets #725 y #708). +ALTER TABLE aulas + DROP cuadro_x, + DROP cuadro_y, + ADD ntp VARCHAR(30) AFTER proxy, + ADD inremotepc TINYINT DEFAULT 0; +# Añadir campos para nº de revisión de imágenes y su inclusión en proyecto Remote PC (tickets #737 y #708). +ALTER TABLE imagenes + ADD revision SMALLINT UNSIGNED NOT NULL DEFAULT 0 AFTER nombreca, + ADD inremotepc TINYINT DEFAULT 0; + +# Adaptar campo para codificar claves de usuarios (ticket #778), +# eliminar campo sin uso (ticket #730), +# añadir clave de acceso a la API REST (tickets #708). +ALTER TABLE usuarios + MODIFY pasguor VARCHAR(56) NOT NULL DEFAULT '', + ADD apikey VARCHAR(32) NOT NULL DEFAULT ''; +# Preparar generación de clave de acceso a la API REST para el usuario principal (ticket #708). +UPDATE usuarios + SET apikey = 'APIKEY' + WHERE idusuario = 1 AND apikey = ''; +# Codificar claves de usuarios (ticket #) +INSERT INTO usuarios (idusuario, pasguor) + SELECT idusuario, pasguor FROM usuarios + ON DUPLICATE KEY UPDATE + idusuario=VALUES(idusuario), pasguor=SHA2(VALUES(pasguor),224); + +# Añadir nº de revisión de imagen restaurada (ticket #737), +# añadir porcentaje de uso de sistema de ficheros (ticket #711), +# evitar errores "TEXT NOT NULL" y "NO_ZERO_DATE" (ticket #730). +ALTER TABLE ordenadores_particiones + MODIFY cache TEXT, + ADD revision SMALLINT UNSIGNED NOT NULL DEFAULT 0 AFTER idimagen, + ADD uso TINYINT NOT NULL DEFAULT 0; +ALTER TABLE acciones + MODIFY restrambito TEXT, + MODIFY fechahorareg DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00', + MODIFY fechahorafin DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00'; +ALTER TABLE parametros + MODIFY descripcion TEXT; +ALTER TABLE tareas + MODIFY restrambito TEXT; + +# Actualizar componentes hardware y añadir nº de serie, clave de acceso a API REST de OGAgent y directorio de ogLive(tickets #713, #718 y #768) +ALTER TABLE tipohardwares + DROP pci; +INSERT INTO tipohardwares (idtipohardware, descripcion, urlimg, nemonico) VALUES + (17, 'Chasis del Sistema', '', 'cha'), + (18, 'Controladores de almacenamiento', '../images/iconos/almacenamiento.png', 'sto'), + (19, 'Tipo de proceso de arranque', '../images/iconos/arranque.png', 'boo'); +ALTER TABLE ordenadores + ADD numserie VARCHAR(25) DEFAULT NULL AFTER nombreordenador, + ADD agentkey VARCHAR(32) DEFAULT NULL, + ADD oglivedir VARCHAR(50) NOT NULL DEFAULT 'ogLive'; + +# Directorios en repo para distintas UO (ticket #678). +ALTER TABLE entidades + ADD ogunit TINYINT(1) NOT NULL DEFAULT 0; +ALTER TABLE centros + ADD directorio VARCHAR(50) DEFAULT ''; + +# Incluir campo ID sistema operativo en el perfil de software (tickets #738 #713) +ALTER TABLE perfilessoft + ADD idnombreso SMALLINT UNSIGNED AFTER idperfilsoft; + +# Añadir campo y generar clave de acceso a la API REST del repositorio (ticket #743). +ALTER TABLE repositorios + ADD apikey VARCHAR(32) NOT NULL DEFAULT ''; +UPDATE repositorios + SET apikey = 'REPOKEY' + WHERE idrepositorio = 1 AND apikey = ''; + +# Número de puestos del aula permite valores hasta 32768 (ticket #747) +ALTER TABLE aulas + MODIFY puestos smallint DEFAULT NULL; + +# Nuevas tablas para datos del proyecto Remote PC y operaciones de OGAgent (ticket #708). +CREATE TABLE IF NOT EXISTS remotepc ( + id INT(11) NOT NULL, + reserved DATETIME DEFAULT NULL, + urllogin VARCHAR(100), + urllogout VARCHAR(100), + PRIMARY KEY (id) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8; +CREATE TABLE IF NOT EXISTS ogagent_queue ( + id INT(11) NOT NULL AUTO_INCREMENT, + clientid INT(11) NOT NULL, + exectime DATETIME DEFAULT NULL, + operation VARCHAR(25), + PRIMARY KEY (id) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8; + + +# Nuevo comando "Enviar mensaje" (ticket #779) +INSERT INTO comandos (idcomando, descripcion, pagina, gestor, funcion, urlimg, + aplicambito, visuparametros, parametros, comentarios, activo, submenu) VALUES + (16, 'Enviar mensaje', '../comandos/EnviarMensaje.php', '../comandos/gestores/gestor_Comandos.php', 'EnviarMensaje', '', + 31, 'tit;msj', 'nfn;iph;tit;msj', '', 1, '' ); +INSERT INTO parametros (idparametro, nemonico, descripcion, nomidentificador, nomtabla, nomliteral, tipopa, visual) VALUES + (39, 'tit', 'Título', '', '', '', 0, 1), + (40, 'msj', 'Contenido', '', '', '', 0, 1); + +# Crear tabla de log para la cola de acciones (ticket #782) +CREATE TABLE IF NOT EXISTS acciones_log LIKE acciones; +ALTER TABLE acciones_log ADD fecha_borrado DATETIME; +DELIMITER // +CREATE TRIGGER registrar_acciones BEFORE DELETE ON acciones FOR EACH ROW BEGIN + INSERT INTO acciones_log VALUES + (OLD.idaccion, OLD.tipoaccion, OLD.idtipoaccion, OLD.descriaccion, + OLD.idordenador, OLD.ip, OLD.sesion, OLD.idcomando, OLD.parametros, + OLD.fechahorareg, OLD.fechahorafin, OLD.estado, OLD.resultado, + OLD.descrinotificacion, OLD.ambito, OLD.idambito, OLD.restrambito, + OLD.idprocedimiento, OLD.idtarea, OLD.idcentro, OLD.idprogramacion, NOW()); +END// +DELIMITER ; + +# Ampliar programación de tareas hasta 2025 (ticket #732). +ALTER TABLE programaciones + MODIFY annos SMALLINT DEFAULT NULL, + MODIFY meses SMALLINT DEFAULT NULL; + +# Eliminar tabla sin uso (ticket #730). +DROP TABLE IF EXISTS campus; + diff --git a/admin/Database/ogAdmBD-1.0.6b-postinst.sql b/admin/Database/ogAdmBD-1.0.6b-postinst.sql deleted file mode 100644 index 81cb77ab..00000000 --- a/admin/Database/ogAdmBD-1.0.6b-postinst.sql +++ /dev/null @@ -1,41 +0,0 @@ -### Procedimiento para actualización de la base de datos. -# Postinstalación de OpenGnSys 1.0.5+ -#use ogAdmBD - -# Nota: retocar el fichero para sustituir KERNELVERSION por la versión del -# Kernel del cliente ogLive con el formato V.RR (V=versión, RR=revisión). - -# Cambiar parámetro de resolución de pantalla para Kernel anteriores a 3.7. -UPDATE menus - SET resolucion = CASE resolucion - WHEN 'uvesafb:1152x864-16' THEN '355' - WHEN 'uvesafb:800x600-16' THEN '788' - WHEN 'uvesafb:800x600-24' THEN '789' - WHEN 'uvesafb:1024x768-16' THEN '791' - WHEN 'uvesafb:1024x768-24' THEN '792' - WHEN 'uvesafb:1280x1024-16' THEN '794' - WHEN 'uvesafb:1280x1024-24' THEN '795' - WHEN 'uvesafb:1600x1200-16' THEN '798' - WHEN 'uvesafb:1600x1200-24' THEN '799' - WHEN NULL or '0' THEN '788' - ELSE resolucion - END - WHERE KERNELVERSION < 3.07; - -# Cambiar parámetro de resolución de pantalla para Kernel 3.7 o superior. -UPDATE menus - SET resolucion = CASE resolucion - WHEN '355' THEN 'uvesafb:1152x864-16' - WHEN '788' THEN 'uvesafb:800x600-16' - WHEN '789' THEN 'uvesafb:800x600-24' - WHEN '791' THEN 'uvesafb:1024x768-16' - WHEN '792' THEN 'uvesafb:1024x768-24' - WHEN '794' THEN 'uvesafb:1280x1024-16' - WHEN '795' THEN 'uvesafb:1280x1024-24' - WHEN '798' THEN 'uvesafb:1600x1200-16' - WHEN '799' THEN 'uvesafb:1600x1200-24' - WHEN NULL or '0' THEN 'uvesafb:800x600-16' - ELSE resolucion - END - WHERE KERNELVERSION >= 3.07; - diff --git a/admin/Database/ogAdmBD-1.1.0-postinst.sql b/admin/Database/ogAdmBD-1.1.0-postinst.sql new file mode 100644 index 00000000..7ebbfd14 --- /dev/null +++ b/admin/Database/ogAdmBD-1.1.0-postinst.sql @@ -0,0 +1,49 @@ +### Procedimiento para actualización de la base de datos. +# Postinstalación de OpenGnsys 1.1.0 +#use ogAdmBD + +# Nota: retocar el fichero para sustituir KERNELVERSION por la versión del +# Kernel del cliente ogLive con el formato V.RR (V=versión, RR=revisión). + +# Cambiar parámetro de resolución de pantalla para Kernel anteriores a 3.7. +UPDATE menus + SET resolucion = CASE resolucion + WHEN 'uvesafb:1152x864-16' THEN '355' + WHEN 'uvesafb:800x600-16' THEN '788' + WHEN 'uvesafb:800x600-24' THEN '789' + WHEN 'uvesafb:800x600-32' THEN '814' + WHEN 'uvesafb:1024x768-16' THEN '791' + WHEN 'uvesafb:1024x768-24' THEN '792' + WHEN 'uvesafb:1024x768-32' THEN '824' + WHEN 'uvesafb:1280x1024-16' THEN '794' + WHEN 'uvesafb:1280x1024-24' THEN '795' + WHEN 'uvesafb:1280x1024-32' THEN '829' + WHEN 'uvesafb:1600x1200-16' THEN '798' + WHEN 'uvesafb:1600x1200-24' THEN '799' + WHEN 'uvesafb:1600x1200-32' THEN '834' + WHEN NULL or '0' THEN '788' + ELSE resolucion + END + WHERE KERNELVERSION < 3.07; + +# Cambiar parámetro de resolución de pantalla para Kernel 3.7 o superior. +UPDATE menus + SET resolucion = CASE resolucion + WHEN '355' THEN 'uvesafb:1152x864-16' + WHEN '788' THEN 'uvesafb:800x600-16' + WHEN '789' THEN 'uvesafb:800x600-24' + WHEN '791' THEN 'uvesafb:1024x768-16' + WHEN '792' THEN 'uvesafb:1024x768-24' + WHEN '794' THEN 'uvesafb:1280x1024-16' + WHEN '795' THEN 'uvesafb:1280x1024-24' + WHEN '798' THEN 'uvesafb:1600x1200-16' + WHEN '799' THEN 'uvesafb:1600x1200-24' + WHEN '814' THEN 'uvesafb:800x600-32' + WHEN '824' THEN 'uvesafb:1024x768-32' + WHEN '829' THEN 'uvesafb:1280x1024-32' + WHEN '834' THEN 'uvesafb:1600x1200-32' + WHEN NULL or '0' THEN 'uvesafb:800x600-16' + ELSE resolucion + END + WHERE KERNELVERSION >= 3.07; + diff --git a/admin/Database/ogAdmBD-1.1.0pre-1.1.0.sql b/admin/Database/ogAdmBD-1.1.0pre-1.1.0.sql new file mode 100644 index 00000000..ed296e44 --- /dev/null +++ b/admin/Database/ogAdmBD-1.1.0pre-1.1.0.sql @@ -0,0 +1,270 @@ +### Fichero de actualización de la base de datos. +# OpenGnsys 1.1.0pre - 1.1.0 +#use ogAdmBD + +### NOTA: la configuración de MySQL solo puede modificarla el usuario "root". +# Soportar cláusuloas GROUP BY especiales para configuración de equipos. +#SET GLOBAL sql_mode = TRIM(BOTH ',' FROM REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', '')); +# Activar calendario de eventos de MySQL. +#SET GLOBAL event_scheduler = ON; + +# Eliminar procedimiento y disparador para evitar errores de ejecución. +DROP PROCEDURE IF EXISTS addcols; +DROP TRIGGER IF EXISTS registrar_acciones; +# Procedimiento para actualización condicional de tablas. +DELIMITER '//' +CREATE PROCEDURE addcols() BEGIN + # Añadir campo para incluir aulas en proyecto Remote PC (ticket #708). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='inremotepc' AND TABLE_NAME='aulas' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE aulas + ADD inremotepc TINYINT DEFAULT 0; + END IF; + # Añadir campo para incluir imágenes en proyecto Remote PC (ticket #708). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='inremotepc' AND TABLE_NAME='imagenes' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE imagenes + ADD inremotepc TINYINT DEFAULT 0; + END IF; + # Añadir campo para clave de acceso a la API REST (ticket #708). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='apikey' AND TABLE_NAME='usuarios' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE usuarios + ADD apikey VARCHAR(32) NOT NULL DEFAULT ''; + END IF; + # Añadir porcentaje de uso de sistema de ficheros (ticket #711) + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='uso' AND TABLE_NAME='ordenadores_particiones' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE ordenadores_particiones + ADD uso TINYINT NOT NULL DEFAULT 0; + END IF; + # Añadir nº de serie (ticket #713) + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='numserie' AND TABLE_NAME='ordenadores' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE ordenadores + ADD numserie varchar(25) DEFAULT NULL AFTER nombreordenador; + END IF; + # Añadir campo para clave de acceso a la API REST de OGAgent (ticket #718). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='agentkey' AND TABLE_NAME='ordenadores' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE ordenadores + ADD agentkey VARCHAR(32) DEFAULT NULL; + END IF; + # Añadir índice para mostrar correctamente el formulario de estado. + IF NOT EXISTS (SELECT * FROM information_schema.STATISTICS + WHERE INDEX_NAME='idaulaip' AND TABLE_NAME='ordenadores' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE ordenadores + ADD KEY idaulaip (idaula ASC, ip ASC); + END IF; + # Añadir campo para directorio de ogLive asociado al cliente (ticket #768). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='oglivedir' AND TABLE_NAME='ordenadores' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE ordenadores + ADD oglivedir VARCHAR(50) NOT NULL DEFAULT 'ogLive'; + END IF; + # Añadir campo para directorio de ogLive asociado al cliente (ticket #768). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='oglivedir' AND TABLE_NAME='aulas' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE aulas + ADD oglivedir VARCHAR(50) NOT NULL DEFAULT 'ogLive'; + END IF; + # Eliminar campos sin uso en aulas (ticket #730). + IF EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='cuadro_x' AND TABLE_NAME='aulas' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE aulas + DROP cuadro_x, + DROP cuadro_y; + END IF; + # Eliminar campos no usado en inventario de hardware (ticket #713). + IF EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='pci' AND TABLE_NAME='tipohardwares' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE tipohardwares + DROP pci; + END IF; + # Añadir servidor de sincronización horaria NTP (ticket #725). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='ntp' AND TABLE_NAME='aulas' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE aulas + ADD ntp VARCHAR(30) AFTER proxy; + END IF; + # Directorios en repo para distintas UO (ticket #678). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='ogunit' AND TABLE_NAME='entidades' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE entidades + ADD ogunit TINYINT(1) NOT NULL DEFAULT 0; + END IF; + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='directorio' AND TABLE_NAME='centros' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE centros + ADD directorio VARCHAR(50) DEFAULT ''; + END IF; + # Nº de revisión de imagen (ticket #737). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='revision' AND TABLE_NAME='imagenes' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE imagenes + ADD revision SMALLINT UNSIGNED NOT NULL DEFAULT 0 AFTER nombreca; + END IF; + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='revision' AND TABLE_NAME='ordenadores_particiones' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE ordenadores_particiones + ADD revision SMALLINT UNSIGNED NOT NULL DEFAULT 0 AFTER idimagen; + END IF; + # Incluir campo sistema operativo en el perfil de software (tickets #738 #713) + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='idnombreso' AND TABLE_NAME='perfilessoft' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE perfilessoft + ADD idnombreso SMALLINT UNSIGNED AFTER idperfilsoft; + END IF; + # Añadir campo para clave de acceso a la API REST del repositorio (ticket #743). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='apikey' AND TABLE_NAME='repositorios' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE repositorios + ADD apikey VARCHAR(32) NOT NULL DEFAULT ''; + END IF; + # Codificar claves de los usuarios, si fuese necesario (ticket #778) + IF ((SELECT CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS + WHERE COLUMN_NAME='pasguor' AND TABLE_NAME='usuarios' AND TABLE_SCHEMA=DATABASE()) != 56) + THEN + ALTER TABLE usuarios + MODIFY pasguor VARCHAR(56) NOT NULL DEFAULT ''; + INSERT INTO usuarios (idusuario, pasguor) + SELECT idusuario, pasguor FROM usuarios + ON DUPLICATE KEY UPDATE + pasguor=SHA2(VALUES(pasguor),224); + END IF; + # Crear tabla de log para la cola de acciones (ticket #782) + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE TABLE_NAME='acciones_log' AND TABLE_SCHEMA=DATABASE()) + THEN + CREATE TABLE acciones_log LIKE acciones; + ALTER TABLE acciones_log ADD fecha_borrado DATETIME; + END IF; +END// +# Disparador para mover acciones borradas a la tabla de registro de acciones. +CREATE TRIGGER registrar_acciones BEFORE DELETE ON acciones FOR EACH ROW +BEGIN + INSERT INTO acciones_log VALUES + (OLD.idaccion, OLD.tipoaccion, OLD.idtipoaccion, OLD.descriaccion, + OLD.idordenador, OLD.ip, OLD.sesion, OLD.idcomando, OLD.parametros, + OLD.fechahorareg, OLD.fechahorafin, OLD.estado, OLD.resultado, + OLD.descrinotificacion, OLD.ambito, OLD.idambito, OLD.restrambito, + OLD.idprocedimiento, OLD.idtarea, OLD.idcentro, OLD.idprogramacion, + NOW()); +END// +# Ejecutar actualización condicional. +DELIMITER ';' +CALL addcols(); +DROP PROCEDURE addcols; + +# Nuevos tipos de particiones y de sistemas de ficheros. +INSERT INTO tipospar (codpar, tipopar, clonable) VALUES + (CONV('A9',16,10), 'NETBSD', 1), + (CONV('2700',16,10), 'WIN-RECOV', 1), + (CONV('8302',16,10), 'LINUX', 1), + (CONV('A504',16,10), 'FREEBSD', 1), + (CONV('A901',16,10), 'NETBSD-SWAP', 0), + (CONV('A902',16,10), 'NETBSD', 1), + (CONV('A903',16,10), 'NETBSD', 1), + (CONV('A904',16,10), 'NETBSD', 1), + (CONV('A905',16,10), 'NETBSD', 1), + (CONV('A906',16,10), 'NETBSD-RAID', 1), + (CONV('AF02',16,10), 'HFS-RAID', 1), + (CONV('FB00',16,10), 'VMFS', 1), + (CONV('FB01',16,10), 'VMFS-RESERV', 1), + (CONV('FB02',16,10), 'VMFS-KRN', 1), + (CONV('10000',16,10), 'LVM-LV', 1), + (CONV('10010',16,10), 'ZFS-VOL', 1) + ON DUPLICATE KEY UPDATE + codpar=VALUES(codpar), tipopar=VALUES(tipopar), clonable=VALUES(clonable); +INSERT INTO sistemasficheros (idsistemafichero, nemonico, descripcion) VALUES + (19, 'LINUX-SWAP', 'LINUX-SWAP'), + (20, 'F2FS', 'F2FS'), + (21, 'NILFS2', 'NILFS2') + ON DUPLICATE KEY UPDATE + idsistemafichero=VALUES(idsistemafichero), nemonico=VALUES(nemonico), descripcion=VALUES(descripcion); + + +# Preparar generación de claves de acceso a la API REST para el usuario principal y a la del repositorio principal (tickets #708 y #743). +UPDATE usuarios + SET apikey = 'APIKEY' + WHERE idusuario = 1 AND apikey = ''; +UPDATE repositorios + SET apikey = 'REPOKEY' + WHERE idrepositorio = 1 AND apikey = ''; + +# Nuevos componentes hardware (ticket #713) +INSERT INTO tipohardwares (idtipohardware, descripcion, urlimg, nemonico) VALUES + (17, 'Chasis del Sistema', '', 'cha'), + (18, 'Controladores de almacenamiento', '../images/iconos/almacenamiento.png', 'sto'), + (19, 'Tipo de proceso de arranque', '../images/iconos/arranque.png', 'boo') + ON DUPLICATE KEY UPDATE + descripcion=VALUES(descripcion), urlimg=VALUES(urlimg), nemonico=VALUES(nemonico); + +# Número de puestos del aula permite valores hasta 32768 (ticket #747) +ALTER TABLE aulas + MODIFY puestos SMALLINT DEFAULT NULL; + +# Nuevas tablas para datos del proyecto Remote PC y operaciones de OGAgent (ticket #708). +DROP TABLE IF EXISTS remotepc; +CREATE TABLE remotepc ( + id INT(11) NOT NULL, + reserved DATETIME DEFAULT NULL, + urllogin VARCHAR(100), + urllogout VARCHAR(100), + language VARCHAR(5), + PRIMARY KEY (id) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8; +DROP TABLE IF EXISTS ogagent_queue; +CREATE TABLE ogagent_queue ( + id INT(11) NOT NULL AUTO_INCREMENT, + clientid INT(11) NOT NULL, + exectime DATETIME DEFAULT NULL, + operation VARCHAR(25), + PRIMARY KEY (id) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +# Nuevo comando "Enviar mensaje" (ticket #779) +INSERT INTO comandos (idcomando, descripcion, pagina, gestor, funcion, urlimg, + aplicambito, visuparametros, parametros, comentarios, activo, submenu) VALUES + (16, 'Enviar mensaje', '../comandos/EnviarMensaje.php', '../comandos/gestores/gestor_Comandos.php', 'EnviarMensaje', '', 31, '', '', '', 1, '' ) + ON DUPLICATE KEY UPDATE + descripcion=VALUES(descripcion), pagina=VALUES(pagina), + gestor=VALUES(gestor), funcion=VALUES(funcion), + aplicambito=VALUES(aplicambito), activo=VALUES(activo); +INSERT INTO parametros (idparametro, nemonico, descripcion, nomidentificador, nomtabla, nomliteral, tipopa, visual) VALUES + (39, 'tit', 'Título', '', '', '', 0, 1), + (40, 'msj', 'Contenido', '', '', '', 0, 1) + ON DUPLICATE KEY UPDATE + nemonico=VALUES(nemonico), descripcion=VALUES(descripcion), + tipopa=VALUES(tipopa), visual=VALUES(visual); + +# Evitar error de MySQL con modo NO_ZERO_DATE (ticket #730). +ALTER TABLE acciones + MODIFY fechahorareg DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00', + MODIFY fechahorafin DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00'; + +# Ampliar programación de tareas hasta 2025 (ticket #732). +ALTER TABLE programaciones + MODIFY annos SMALLINT DEFAULT NULL; + +# Eliminar tabla sin uso (ticket #730). +DROP TABLE IF EXISTS campus; + diff --git a/admin/Database/ogAdmBD.sql b/admin/Database/ogAdmBD.sql index 06ca3e08..c126f63c 100644 --- a/admin/Database/ogAdmBD.sql +++ b/admin/Database/ogAdmBD.sql @@ -1,6 +1,8 @@ -- Fichero de instalación de la base de datos. -SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; +SET sql_mode = "NO_AUTO_VALUE_ON_ZERO"; +SET GLOBAL sql_mode = TRIM(BOTH ',' FROM REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', '')); +SET GLOBAL event_scheduler = ON; -- -- Base de datos: `ogAdmBD` @@ -12,24 +14,25 @@ SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; -- Estructura de tabla para la tabla `acciones` -- -CREATE TABLE IF NOT EXISTS `acciones` ( +DROP TABLE IF EXISTS `acciones`; +CREATE TABLE `acciones` ( `idaccion` int(11) NOT NULL AUTO_INCREMENT, - `tipoaccion` smallint(6) NOT NULL, - `idtipoaccion` int(11) NOT NULL, - `descriaccion` varchar(250) NOT NULL, - `idordenador` int(11) NOT NULL, - `ip` varchar(50) NOT NULL, - `sesion` int(11) NOT NULL, - `idcomando` int(11) NOT NULL, + `tipoaccion` smallint(6) NOT NULL DEFAULT '0', + `idtipoaccion` int(11) NOT NULL DEFAULT '0', + `descriaccion` varchar(250) NOT NULL DEFAULT '', + `idordenador` int(11) NOT NULL DEFAULT '0', + `ip` varchar(50) NOT NULL DEFAULT '', + `sesion` int(11) NOT NULL DEFAULT '0', + `idcomando` int(11) NOT NULL DEFAULT '0', `parametros` text, - `fechahorareg` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `fechahorafin` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `fechahorareg` datetime NOT NULL DEFAULT '1970-01-01 00:00:00', + `fechahorafin` datetime NOT NULL DEFAULT '1970-01-01 00:00:00', `estado` tinyint(1) NOT NULL DEFAULT '0', `resultado` tinyint(1) NOT NULL DEFAULT '0', `descrinotificacion` varchar(256) DEFAULT NULL, `ambito` smallint(6) NOT NULL DEFAULT '0', `idambito` int(11) NOT NULL DEFAULT '0', - `restrambito` text NOT NULL, + `restrambito` text, `idprocedimiento` int(11) NOT NULL DEFAULT '0', `idtarea` int(11) NOT NULL DEFAULT '0', `idcentro` int(11) NOT NULL DEFAULT '0', @@ -43,11 +46,33 @@ CREATE TABLE IF NOT EXISTS `acciones` ( -- -------------------------------------------------------- +-- +-- Estructura de tabla para la tabla `acciones_log` +-- + +DROP TABLE IF EXISTS `acciones_log`; +CREATE TABLE acciones_log LIKE acciones; +ALTER TABLE acciones_log ADD fecha_borrado DATETIME; +DELIMITER // +-- Trigger para guardar acciones antes de ser borradas. +CREATE TRIGGER registrar_acciones BEFORE DELETE ON acciones FOR EACH ROW BEGIN + INSERT INTO acciones_log VALUES + (OLD.idaccion, OLD.tipoaccion, OLD.idtipoaccion, OLD.descriaccion, + OLD.idordenador, OLD.ip, OLD.sesion, OLD.idcomando, OLD.parametros, + OLD.fechahorareg, OLD.fechahorafin, OLD.estado, OLD.resultado, + OLD.descrinotificacion, OLD.ambito, OLD.idambito, OLD.restrambito, + OLD.idprocedimiento, OLD.idtarea, OLD.idcentro, OLD.idprogramacion, NOW()); +END// +DELIMITER ; + +-- -------------------------------------------------------- + -- -- Estructura de tabla para la tabla `acciones_menus` -- -CREATE TABLE IF NOT EXISTS `acciones_menus` ( +DROP TABLE IF EXISTS `acciones_menus`; +CREATE TABLE `acciones_menus` ( `idaccionmenu` int(11) NOT NULL AUTO_INCREMENT, `tipoaccion` tinyint(4) NOT NULL DEFAULT '0', `idtipoaccion` int(11) NOT NULL DEFAULT '0', @@ -65,7 +90,8 @@ CREATE TABLE IF NOT EXISTS `acciones_menus` ( -- Estructura de tabla para la tabla `administradores_centros` -- -CREATE TABLE IF NOT EXISTS `administradores_centros` ( +DROP TABLE IF EXISTS `administradores_centros`; +CREATE TABLE `administradores_centros` ( `idadministradorcentro` int(11) NOT NULL AUTO_INCREMENT, `idusuario` int(11) NOT NULL DEFAULT '0', `idcentro` int(11) NOT NULL DEFAULT '0', @@ -81,34 +107,36 @@ INSERT INTO `administradores_centros` (`idadministradorcentro`, `idusuario`, `id -- Estructura de tabla para la tabla `aulas` -- -CREATE TABLE IF NOT EXISTS `aulas` ( +DROP TABLE IF EXISTS `aulas`; +CREATE TABLE `aulas` ( `idaula` int(11) NOT NULL AUTO_INCREMENT, `nombreaula` varchar(100) NOT NULL DEFAULT '', `idcentro` int(11) NOT NULL DEFAULT '0', `urlfoto` varchar(250) DEFAULT NULL, - `cuadro_y` char(3) DEFAULT NULL, - `cuadro_x` char(3) DEFAULT NULL, `cagnon` tinyint(1) DEFAULT NULL, `pizarra` tinyint(1) DEFAULT NULL, `grupoid` int(11) DEFAULT NULL, `ubicacion` varchar(255) DEFAULT NULL, `comentarios` text, - `puestos` tinyint(4) DEFAULT NULL, + `puestos` smallint DEFAULT NULL, `horaresevini` tinyint(4) DEFAULT NULL, `horaresevfin` tinyint(4) DEFAULT NULL, - `modomul` tinyint(4) NOT NULL, - `ipmul` varchar(16) NOT NULL, - `pormul` int(11) NOT NULL, + `modomul` tinyint(4) NOT NULL DEFAULT '0', + `ipmul` varchar(16) NOT NULL DEFAULT '', + `pormul` int(11) NOT NULL DEFAULT '0', `velmul` smallint(6) NOT NULL DEFAULT '70', `router` varchar( 30 ), `netmask` varchar( 30 ), `dns` varchar (30), `proxy` varchar (30), + `ntp` varchar (30), `modp2p` enum('seeder','peer','leecher') DEFAULT 'peer', `timep2p` int(11) NOT NULL DEFAULT '60', `validacion` tinyint(1) DEFAULT '0', `paginalogin` varchar(100), `paginavalidacion` varchar(100), + `inremotepc` tinyint DEFAULT '0', + `oglivedir` varchar(50) NOT NULL DEFAULT 'ogLive', PRIMARY KEY (`idaula`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -117,18 +145,19 @@ CREATE TABLE IF NOT EXISTS `aulas` ( -- Estructura de tabla para la tabla `asistentes` -- -CREATE TABLE IF NOT EXISTS `asistentes` ( +DROP TABLE IF EXISTS `asistentes`; +CREATE TABLE `asistentes` ( `idcomando` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', - `pagina` varchar(256) NOT NULL, - `gestor` varchar(256) NOT NULL, - `funcion` varchar(64) NOT NULL, + `pagina` varchar(256) NOT NULL DEFAULT '', + `gestor` varchar(256) NOT NULL DEFAULT '', + `funcion` varchar(64) NOT NULL DEFAULT '', `urlimg` varchar(250) DEFAULT NULL, `aplicambito` tinyint(4) DEFAULT NULL, `visuparametros` varchar(250) DEFAULT NULL, `parametros` varchar(250) DEFAULT NULL, `comentarios` text, - `activo` tinyint(1) NOT NULL, + `activo` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY ( `idcomando` , `descripcion` ) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ; @@ -141,39 +170,19 @@ INSERT INTO `asistentes` (`idcomando`, `descripcion`, `pagina`, `gestor`, `funci ('8', 'Asistente Particionado', '../asistentes/AsistenteParticionado.php', '../asistentes/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '1'); - --- -------------------------------------------------------- - --- --- Estructura de tabla para la tabla `campus` --- - -CREATE TABLE IF NOT EXISTS `campus` ( - `idcampus` int(11) NOT NULL AUTO_INCREMENT, - `nombrecampus` varchar(100) NOT NULL DEFAULT '', - `iduniversidad` int(11) DEFAULT NULL, - `urlmapa` varchar(255) DEFAULT NULL, - `cuadro_y` tinyint(3) DEFAULT NULL, - `cuadro_x` tinyint(3) DEFAULT NULL, - PRIMARY KEY (`idcampus`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; - --- --- Volcar la base de datos para la tabla `campus` --- - - -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `centros` -- -CREATE TABLE IF NOT EXISTS `centros` ( +DROP TABLE IF EXISTS `centros`; +CREATE TABLE `centros` ( `idcentro` int(11) NOT NULL AUTO_INCREMENT, `nombrecentro` varchar(100) NOT NULL DEFAULT '', `identidad` int(11) DEFAULT NULL, `comentarios` text, + `directorio` varchar(50) DEFAULT '', PRIMARY KEY (`idcentro`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -182,7 +191,7 @@ CREATE TABLE IF NOT EXISTS `centros` ( -- Volcar la base de datos para la tabla `centros` -- INSERT INTO `centros` (`idcentro`,`nombrecentro`,`identidad`,`comentarios`) VALUES - (1,'Unidad Organizativa (Default)',1,'Esta Unidad Organizativa se crea automáticamente en el proceso de instalación de OpenGnSys'); + (1,'Unidad Organizativa (Default)',1,'Esta Unidad Organizativa se crea automáticamente en el proceso de instalación de OpenGnsys'); -- -------------------------------------------------------- @@ -191,18 +200,19 @@ INSERT INTO `centros` (`idcentro`,`nombrecentro`,`identidad`,`comentarios`) VALU -- Estructura de tabla para la tabla `comandos` -- -CREATE TABLE IF NOT EXISTS `comandos` ( +DROP TABLE IF EXISTS `comandos`; +CREATE TABLE `comandos` ( `idcomando` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', - `pagina` varchar(256) NOT NULL, - `gestor` varchar(256) NOT NULL, - `funcion` varchar(64) NOT NULL, + `pagina` varchar(256) NOT NULL DEFAULT '', + `gestor` varchar(256) NOT NULL DEFAULT '', + `funcion` varchar(64) NOT NULL DEFAULT '', `urlimg` varchar(250) DEFAULT NULL, `aplicambito` tinyint(4) DEFAULT NULL, `visuparametros` varchar(250) DEFAULT NULL, `parametros` varchar(250) DEFAULT NULL, `comentarios` text, - `activo` tinyint(1) NOT NULL, + `activo` tinyint(1) NOT NULL DEFAULT '0', `submenu` varchar(50) NOT NULL DEFAULT '', PRIMARY KEY (`idcomando`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=13 ; @@ -226,7 +236,8 @@ INSERT INTO `comandos` (`idcomando`, `descripcion`, `pagina`, `gestor`, `funcion (12, 'Crear Imagen Basica', '../comandos/CrearImagenBasica.php', '../comandos/gestores/gestor_Comandos.php', 'CrearImagenBasica', '', 16, 'dsk;par;cpt;idi;nci;ipr;iph;bpi;cpc;bpc;rti;nba', 'nfn;dsk;par;cpt;idi;nci;ipr;iph;bpi;cpc;bpc;rti;nba', '', 1, 'Sincronizacion'), (13, 'Restaurar Imagen Basica', '../comandos/RestaurarImagenBasica.php', '../comandos/gestores/gestor_Comandos.php', 'RestaurarImagenBasica', '', 28, 'dsk;par;idi;nci;ipr;iph;bpi;cpc;bpc;rti;nba;met', 'nfn;dsk;par;idi;nci;ipr;iph;bpi;cpc;bpc;rti;nba;met', '', 1, 'Sincronizacion'), (14, 'Crear Software Incremental', '../comandos/CrearSoftIncremental.php', '../comandos/gestores/gestor_Comandos.php', 'CrearSoftIncremental', '', 16, 'dsk;par;idi;nci;ipr;idf;ncf;bpi;cpc;bpc;iph;rti;nba', 'nfn;dsk;par;idi;nci;ipr;idf;ncf;bpi;cpc;bpc;iph;rti;nba', '', 1, 'Sincronizacion'), -(15, 'Restaurar Software Incremental', '../comandos/RestaurarSoftIncremental.php', '../comandos/gestores/gestor_Comandos.php', 'RestaurarSoftIncremental', '', 28, 'dsk;par;idi;nci;ipr;idf;ncf;bpi;cpc;bpc;iph;rti;met;nba', 'nfn;dsk;par;idi;nci;ipr;idf;ncf;bpi;cpc;bpc;iph;rti;met;nba', '', 1, 'Sincronizacion'); +(15, 'Restaurar Software Incremental', '../comandos/RestaurarSoftIncremental.php', '../comandos/gestores/gestor_Comandos.php', 'RestaurarSoftIncremental', '', 28, 'dsk;par;idi;nci;ipr;idf;ncf;bpi;cpc;bpc;iph;rti;met;nba', 'nfn;dsk;par;idi;nci;ipr;idf;ncf;bpi;cpc;bpc;iph;rti;met;nba', '', 1, 'Sincronizacion'), +(16, 'Enviar mensaje', '../comandos/EnviarMensaje.php', '../comandos/gestores/gestor_Comandos.php', 'EnviarMensaje', '', 31, 'tit;msj', 'nfn;iph;tit;msj', '', 1, ''); @@ -236,12 +247,14 @@ INSERT INTO `comandos` (`idcomando`, `descripcion`, `pagina`, `gestor`, `funcion -- Estructura de tabla para la tabla `entidades` -- -CREATE TABLE IF NOT EXISTS `entidades` ( +DROP TABLE IF EXISTS `entidades`; +CREATE TABLE `entidades` ( `identidad` int(11) NOT NULL AUTO_INCREMENT, `nombreentidad` varchar(200) NOT NULL DEFAULT '', `comentarios` text, `iduniversidad` int(11) DEFAULT NULL, `grupoid` int(11) DEFAULT NULL, + `ogunit` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`identidad`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; @@ -250,7 +263,7 @@ CREATE TABLE IF NOT EXISTS `entidades` ( -- INSERT INTO `entidades` (`identidad`, `nombreentidad`, `comentarios`, `iduniversidad`, `grupoid`) VALUES -(1, 'Entidad (Default)', 'Esta Entidad se crea automáticamente en el proceso de instalación de OpenGnSys', 1, 0); +(1, 'Entidad (Default)', 'Esta Entidad se crea automáticamente en el proceso de instalación de OpenGnsys', 1, 0); -- -------------------------------------------------------- @@ -258,11 +271,12 @@ INSERT INTO `entidades` (`identidad`, `nombreentidad`, `comentarios`, `idunivers -- Estructura de tabla para la tabla `entornos` -- -CREATE TABLE IF NOT EXISTS `entornos` ( +DROP TABLE IF EXISTS `entornos`; +CREATE TABLE `entornos` ( `identorno` int(11) NOT NULL AUTO_INCREMENT, - `ipserveradm` varchar(50) NOT NULL, - `portserveradm` int(20) NOT NULL, - `protoclonacion` varchar(50) NOT NULL, + `ipserveradm` varchar(50) NOT NULL DEFAULT '', + `portserveradm` int(20) NOT NULL DEFAULT 2008, + `protoclonacion` varchar(50) NOT NULL DEFAULT '', PRIMARY KEY (`identorno`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; @@ -279,7 +293,8 @@ INSERT INTO `entornos` (`identorno`, `ipserveradm`, `portserveradm`, `protoclona -- Estructura de tabla para la tabla `estatus` -- -CREATE TABLE IF NOT EXISTS `estatus` ( +DROP TABLE IF EXISTS `estatus`; +CREATE TABLE `estatus` ( `idestatus` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', PRIMARY KEY (`idestatus`) @@ -302,7 +317,8 @@ INSERT INTO `estatus` (`idestatus`, `descripcion`) VALUES -- Estructura de tabla para la tabla `grupos` -- -CREATE TABLE IF NOT EXISTS `grupos` ( +DROP TABLE IF EXISTS `grupos`; +CREATE TABLE `grupos` ( `idgrupo` int(11) NOT NULL AUTO_INCREMENT, `nombregrupo` varchar(250) NOT NULL DEFAULT '', `grupoid` int(11) NOT NULL DEFAULT '0', @@ -319,7 +335,8 @@ CREATE TABLE IF NOT EXISTS `grupos` ( -- Estructura de tabla para la tabla `gruposordenadores` -- -CREATE TABLE IF NOT EXISTS `gruposordenadores` ( +DROP TABLE IF EXISTS `gruposordenadores`; +CREATE TABLE `gruposordenadores` ( `idgrupo` int(11) NOT NULL AUTO_INCREMENT, `nombregrupoordenador` varchar(250) NOT NULL DEFAULT '', `idaula` int(11) NOT NULL DEFAULT '0', @@ -334,7 +351,8 @@ CREATE TABLE IF NOT EXISTS `gruposordenadores` ( -- Estructura de tabla para la tabla `hardwares` -- -CREATE TABLE IF NOT EXISTS `hardwares` ( +DROP TABLE IF EXISTS `hardwares`; +CREATE TABLE `hardwares` ( `idhardware` int(11) NOT NULL AUTO_INCREMENT, `idtipohardware` int(11) NOT NULL DEFAULT '0', `descripcion` varchar(250) NOT NULL DEFAULT '', @@ -350,7 +368,8 @@ CREATE TABLE IF NOT EXISTS `hardwares` ( -- Estructura de tabla para la tabla `iconos` -- -CREATE TABLE IF NOT EXISTS `iconos` ( +DROP TABLE IF EXISTS `iconos`; +CREATE TABLE `iconos` ( `idicono` int(11) NOT NULL AUTO_INCREMENT, `urlicono` varchar(200) DEFAULT NULL, `idtipoicono` int(11) DEFAULT NULL, @@ -384,7 +403,8 @@ INSERT INTO `iconos` (`idicono`, `urlicono`, `idtipoicono`, `descripcion`) VALUE -- Estructura de tabla para la tabla `idiomas` -- -CREATE TABLE IF NOT EXISTS `idiomas` ( +DROP TABLE IF EXISTS `idiomas`; +CREATE TABLE `idiomas` ( `ididioma` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(100) DEFAULT NULL, `nemonico` char(3) DEFAULT NULL, @@ -406,23 +426,26 @@ INSERT INTO `idiomas` (`ididioma`, `descripcion`, `nemonico`) VALUES -- Estructura de tabla para la tabla `imagenes` -- -CREATE TABLE IF NOT EXISTS `imagenes` ( +DROP TABLE IF EXISTS `imagenes`; +CREATE TABLE `imagenes` ( `idimagen` int(11) NOT NULL AUTO_INCREMENT, - `nombreca` varchar(50) NOT NULL, + `nombreca` varchar(50) NOT NULL DEFAULT '', + `revision` smallint UNSIGNED NOT NULL DEFAULT '0', `descripcion` varchar(250) NOT NULL DEFAULT '', `idperfilsoft` int(11) DEFAULT NULL, `idcentro` int(11) DEFAULT NULL, `comentarios` text, `grupoid` int(11) DEFAULT NULL, - `idrepositorio` int(11) NOT NULL DEFAULT 0, - `idordenador` int(11) NOT NULL DEFAULT 0, - `numdisk` smallint NOT NULL DEFAULT 0, - `numpar` smallint NOT NULL DEFAULT 0, - `codpar` int(8) NOT NULL DEFAULT 0, + `idrepositorio` int(11) NOT NULL DEFAULT '0', + `idordenador` int(11) NOT NULL DEFAULT '0', + `numdisk` smallint NOT NULL DEFAULT '0', + `numpar` smallint NOT NULL DEFAULT '0', + `codpar` int(8) NOT NULL DEFAULT '0', `tipo` tinyint NULL, - `imagenid` int NOT NULL DEFAULT 0, + `imagenid` int NOT NULL DEFAULT '0', `ruta` varchar(250) NULL, `fechacreacion` datetime DEFAULT NULL, + `inremotepc` tinyint DEFAULT '0', PRIMARY KEY (`idimagen`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -432,7 +455,8 @@ CREATE TABLE IF NOT EXISTS `imagenes` ( -- Estructura de tabla para la tabla `menus` -- -CREATE TABLE IF NOT EXISTS `menus` ( +DROP TABLE IF EXISTS `menus`; +CREATE TABLE `menus` ( `idmenu` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', `idcentro` int(11) NOT NULL DEFAULT '0', @@ -454,23 +478,42 @@ CREATE TABLE IF NOT EXISTS `menus` ( -- Estructura de tabla para la tabla `nombresos` -- -CREATE TABLE IF NOT EXISTS `nombresos` ( +DROP TABLE IF EXISTS `nombresos`; +CREATE TABLE `nombresos` ( `idnombreso` smallint(11) NOT NULL AUTO_INCREMENT, - `nombreso` varchar(250) NOT NULL, + `nombreso` varchar(250) NOT NULL DEFAULT '', `idtiposo` int(11) DEFAULT '0', PRIMARY KEY (`idnombreso`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- +-- +-- Estructura de tabla para la tabla `ogagent_queue` +-- + +DROP TABLE IF EXISTS `ogagent_queue`; +CREATE TABLE `ogagent_queue` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientid` int(11) NOT NULL, + `exectime` datetime DEFAULT NULL, + `operation` varchar(25), +-- `parameters` varchar(100), + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +-- -------------------------------------------------------- + -- -- Estructura de tabla para la tabla `ordenadores` -- -CREATE TABLE IF NOT EXISTS `ordenadores` ( +DROP TABLE IF EXISTS `ordenadores`; +CREATE TABLE `ordenadores` ( `idordenador` int(11) NOT NULL AUTO_INCREMENT, `nombreordenador` varchar(100) DEFAULT NULL, - `ip` varchar(16) NOT NULL, + `numserie` varchar(25) DEFAULT NULL, + `ip` varchar(16) NOT NULL DEFAULT '', `mac` varchar(12) DEFAULT NULL, `idaula` int(11) DEFAULT NULL, `idperfilhard` int(11) DEFAULT NULL, @@ -478,16 +521,18 @@ CREATE TABLE IF NOT EXISTS `ordenadores` ( `grupoid` int(11) DEFAULT NULL, `idmenu` int(11) DEFAULT NULL, `cache` int(11) DEFAULT NULL, - `router` varchar(16) NOT NULL, - `mascara` varchar(16) NOT NULL, - `idproautoexec` int(11) NOT NULL DEFAULT 0, - `arranque` VARCHAR( 30 ) NOT NULL DEFAULT '00unknown', + `router` varchar(16) NOT NULL DEFAULT '', + `mascara` varchar(16) NOT NULL DEFAULT '', + `idproautoexec` int(11) NOT NULL DEFAULT '0', + `arranque` varchar(30) NOT NULL DEFAULT '00unknown', `netiface` enum('eth0','eth1','eth2') DEFAULT 'eth0', - `netdriver` varchar( 30 ) NOT NULL DEFAULT 'generic', - `fotoord` varchar( 250 ) NOT NULL DEFAULT 'fotoordenador.gif', + `netdriver` varchar(30) NOT NULL DEFAULT 'generic', + `fotoord` varchar(250) NOT NULL DEFAULT 'fotoordenador.gif', `validacion` tinyint(1) DEFAULT '0', `paginalogin` varchar(100), `paginavalidacion` varchar(100), + `agentkey` varchar(32), + `oglivedir` varchar(50) NOT NULL DEFAULT 'ogLive', PRIMARY KEY (`idordenador`), KEY `idaulaip` (`idaula` ASC, `ip` ASC) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -500,18 +545,21 @@ CREATE TABLE IF NOT EXISTS `ordenadores` ( -- Estructura de tabla para la tabla `ordenadores_particiones` -- -CREATE TABLE IF NOT EXISTS `ordenadores_particiones` ( - `idordenador` int(11) NOT NULL, - `numdisk` smallint NOT NULL, - `numpar` smallint NOT NULL, - `codpar` int(8) NOT NULL, - `tamano` int(11) NOT NULL, - `idsistemafichero` smallint(11) NOT NULL, - `idnombreso` smallint(11) NOT NULL, - `idimagen` int(11) NOT NULL, - `idperfilsoft` int(11) NOT NULL, +DROP TABLE IF EXISTS `ordenadores_particiones`; +CREATE TABLE `ordenadores_particiones` ( + `idordenador` int(11) NOT NULL DEFAULT '0', + `numdisk` smallint NOT NULL DEFAULT '0', + `numpar` smallint NOT NULL DEFAULT '0', + `codpar` int(8) NOT NULL DEFAULT '0', + `tamano` int(11) NOT NULL DEFAULT '0', + `uso` tinyint NOT NULL DEFAULT '0', + `idsistemafichero` smallint(11) NOT NULL DEFAULT '0', + `idnombreso` smallint(11) NOT NULL DEFAULT '0', + `idimagen` int(11) NOT NULL DEFAULT '0', + `revision` smallint UNSIGNED NOT NULL DEFAULT '0', + `idperfilsoft` int(11) NOT NULL DEFAULT '0', `fechadespliegue` datetime NULL, - `cache` text NOT NULL, + `cache` text, UNIQUE KEY `idordenadornumdisknumpar` (`idordenador`,`numdisk`,`numpar`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; @@ -521,13 +569,14 @@ CREATE TABLE IF NOT EXISTS `ordenadores_particiones` ( -- Estructura de tabla para la tabla `parametros` -- -CREATE TABLE IF NOT EXISTS `parametros` ( +DROP TABLE IF EXISTS `parametros`; +CREATE TABLE `parametros` ( `idparametro` int(11) NOT NULL AUTO_INCREMENT, - `nemonico` char(3) NOT NULL, - `descripcion` text NOT NULL, - `nomidentificador` varchar(64) NOT NULL, - `nomtabla` varchar(64) NOT NULL, - `nomliteral` varchar(64) NOT NULL, + `nemonico` char(3) NOT NULL DEFAULT '', + `descripcion` text, + `nomidentificador` varchar(64) NOT NULL DEFAULT '', + `nomtabla` varchar(64) NOT NULL DEFAULT '', + `nomliteral` varchar(64) NOT NULL DEFAULT '', `tipopa` tinyint(1) DEFAULT '0', `visual` tinyint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`idparametro`), @@ -575,7 +624,9 @@ INSERT INTO `parametros` (`idparametro`, `nemonico`, `descripcion`, `nomidentifi (35, 'bpc', 'Borrado previo de la imagen en cache', '', '', '', 5, 1), (36, 'rti', 'Ruta de origen', '', '', '', 0, 1), (37, 'met', 'Método clonación', ';', '', 'Desde caché; Desde repositorio', 3, 1), -(38, 'nba', 'No borrar archivos en destino', '', '', '', 0, 1); +(38, 'nba', 'No borrar archivos en destino', '', '', '', 0, 1), +(39, 'tit', 'Título', '', '', '', 0, 1), +(40, 'msj', 'Contenido', '', '', '', 0, 1); -- -------------------------------------------------------- @@ -584,12 +635,13 @@ INSERT INTO `parametros` (`idparametro`, `nemonico`, `descripcion`, `nomidentifi -- -CREATE TABLE IF NOT EXISTS `perfileshard` ( +DROP TABLE IF EXISTS `perfileshard`; +CREATE TABLE `perfileshard` ( `idperfilhard` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', `comentarios` text, `grupoid` int(11) DEFAULT NULL, - `idcentro` int(11) NOT NULL, + `idcentro` int(11) NOT NULL DEFAULT '0', `winboot` enum( 'reboot', 'kexec' ) NOT NULL DEFAULT 'reboot', PRIMARY KEY (`idperfilhard`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -601,7 +653,8 @@ CREATE TABLE IF NOT EXISTS `perfileshard` ( -- Estructura de tabla para la tabla `perfileshard_hardwares` -- -CREATE TABLE IF NOT EXISTS `perfileshard_hardwares` ( +DROP TABLE IF EXISTS `perfileshard_hardwares`; +CREATE TABLE `perfileshard_hardwares` ( `idperfilhard` int(11) NOT NULL DEFAULT '0', `idhardware` int(11) NOT NULL DEFAULT '0', KEY `idperfilhard` (`idperfilhard`) @@ -613,12 +666,14 @@ CREATE TABLE IF NOT EXISTS `perfileshard_hardwares` ( -- Estructura de tabla para la tabla `perfilessoft` -- -CREATE TABLE IF NOT EXISTS `perfilessoft` ( +DROP TABLE IF EXISTS `perfilessoft`; +CREATE TABLE `perfilessoft` ( `idperfilsoft` int(11) NOT NULL AUTO_INCREMENT, + `idnombreso` smallint(5) unsigned DEFAULT NULL, `descripcion` varchar(250) NOT NULL DEFAULT '', `comentarios` text, `grupoid` int(11) DEFAULT NULL, - `idcentro` int(11) NOT NULL, + `idcentro` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`idperfilsoft`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -628,7 +683,8 @@ CREATE TABLE IF NOT EXISTS `perfilessoft` ( -- Estructura de tabla para la tabla `perfilessoft_softwares` -- -CREATE TABLE IF NOT EXISTS `perfilessoft_softwares` ( +DROP TABLE IF EXISTS `perfilessoft_softwares`; +CREATE TABLE `perfilessoft_softwares` ( `idperfilsoft` int(11) NOT NULL DEFAULT '0', `idsoftware` int(11) NOT NULL DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; @@ -639,9 +695,10 @@ CREATE TABLE IF NOT EXISTS `perfilessoft_softwares` ( -- Estructura de tabla para la tabla `plataformas` -- -CREATE TABLE IF NOT EXISTS `plataformas` ( +DROP TABLE IF EXISTS `plataformas`; +CREATE TABLE `plataformas` ( `idplataforma` int(11) NOT NULL AUTO_INCREMENT, - `plataforma` varchar(250) NOT NULL, + `plataforma` varchar(250) NOT NULL DEFAULT '', PRIMARY KEY (`idplataforma`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=18 ; @@ -662,7 +719,8 @@ INSERT INTO `plataformas` (`idplataforma`, `plataforma`) VALUES -- Estructura de tabla para la tabla `procedimientos` -- -CREATE TABLE IF NOT EXISTS `procedimientos` ( +DROP TABLE IF EXISTS `procedimientos`; +CREATE TABLE `procedimientos` ( `idprocedimiento` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', `urlimg` varchar(250) DEFAULT NULL, @@ -678,13 +736,14 @@ CREATE TABLE IF NOT EXISTS `procedimientos` ( -- Estructura de tabla para la tabla `procedimientos_acciones` -- -CREATE TABLE IF NOT EXISTS `procedimientos_acciones` ( +DROP TABLE IF EXISTS `procedimientos_acciones`; +CREATE TABLE `procedimientos_acciones` ( `idprocedimientoaccion` int(11) NOT NULL AUTO_INCREMENT, `idprocedimiento` int(11) NOT NULL DEFAULT '0', `orden` smallint(4) DEFAULT NULL, `idcomando` int(11) NOT NULL DEFAULT '0', `parametros` text, - `procedimientoid` int(11) NOT NULL, + `procedimientoid` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`idprocedimientoaccion`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -694,13 +753,14 @@ CREATE TABLE IF NOT EXISTS `procedimientos_acciones` ( -- Estructura de tabla para la tabla `programaciones` -- -CREATE TABLE IF NOT EXISTS `programaciones` ( +DROP TABLE IF EXISTS `programaciones`; +CREATE TABLE `programaciones` ( `idprogramacion` int(11) NOT NULL AUTO_INCREMENT, `tipoaccion` int(11) DEFAULT NULL, `identificador` int(11) DEFAULT NULL, `nombrebloque` varchar(255) DEFAULT NULL, - `annos` tinyint(4) DEFAULT NULL, - `meses` smallint(4) DEFAULT NULL, + `annos` smallint DEFAULT NULL, + `meses` smallint DEFAULT NULL, `diario` int(11) DEFAULT NULL, `dias` tinyint(4) DEFAULT NULL, `semanas` tinyint(4) DEFAULT NULL, @@ -715,30 +775,48 @@ CREATE TABLE IF NOT EXISTS `programaciones` ( `ampmfin` tinyint(1) DEFAULT NULL, `minutosfin` tinyint(4) DEFAULT NULL, `suspendida` tinyint(1) DEFAULT NULL, - `sesion` int(11) NOT NULL, + `sesion` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`idprogramacion`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- +-- +-- Estructura de tabla para la tabla `remotepc` +-- + +DROP TABLE IF EXISTS `remotepc`; +CREATE TABLE `remotepc` ( + `id` int(11) NOT NULL, + `reserved` datetime DEFAULT NULL, + `urllogin` varchar(100), + `urllogout` varchar(100), + `language` varchar(5), + PRIMARY KEY (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8; + +-- -------------------------------------------------------- + -- -- Estructura de tabla para la tabla `repositorios` -- -CREATE TABLE IF NOT EXISTS `repositorios` ( +DROP TABLE IF EXISTS `repositorios`; +CREATE TABLE `repositorios` ( `idrepositorio` int(11) NOT NULL AUTO_INCREMENT, - `nombrerepositorio` varchar(250) NOT NULL, + `nombrerepositorio` varchar(250) NOT NULL DEFAULT '', `ip` varchar(15) NOT NULL DEFAULT '', `passguor` varchar(50) NOT NULL DEFAULT '', `idcentro` int(11) DEFAULT NULL, `grupoid` int(11) DEFAULT NULL, `comentarios` text, - `puertorepo` int(11) NOT NULL, + `puertorepo` int(11) NOT NULL DEFAULT '0', + `apikey` varchar(32) NOT NULL DEFAULT '', PRIMARY KEY (`idrepositorio`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; -INSERT INTO `repositorios` (`idrepositorio`,`nombrerepositorio`,`ip`,`passguor`,`idcentro`,`grupoid`,`comentarios`,`puertorepo`) VALUES - (1,'Repositorio (Default)','SERVERIP','',1,0,'',2002); +INSERT INTO `repositorios` (`idrepositorio`,`nombrerepositorio`,`ip`,`passguor`,`idcentro`,`grupoid`,`comentarios`,`puertorepo`,`apikey`) VALUES + (1,'Repositorio (Default)','SERVERIP','',1,0,'',2002,'REPOKEY'); -- -------------------------------------------------------- @@ -747,11 +825,12 @@ INSERT INTO `repositorios` (`idrepositorio`,`nombrerepositorio`,`ip`,`passguor`, -- Estructura de tabla para la tabla `sistemasficheros` -- -CREATE TABLE IF NOT EXISTS `sistemasficheros` ( +DROP TABLE IF EXISTS `sistemasficheros`; +CREATE TABLE `sistemasficheros` ( `idsistemafichero` smallint(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(50) NOT NULL DEFAULT '', `nemonico` varchar(16) DEFAULT NULL, - `codpar` int(8) NOT NULL, + `codpar` int(8) NOT NULL DEFAULT '0', PRIMARY KEY (`idsistemafichero`), UNIQUE KEY (`descripcion`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; @@ -774,7 +853,9 @@ INSERT INTO `sistemasficheros` (`idsistemafichero`, `descripcion`, `nemonico`, ` (16, 'UFS', 'UFS', 0), (17, 'XFS', 'XFS', 0), (18, 'EXFAT', 'EXFAT', 0), - (19, 'LINUX-SWAP', 'LINUX-SWAP', 0); + (19, 'LINUX-SWAP', 'LINUX-SWAP', 0), + (20, 'F2FS', 'F2FS', 0), + (21, 'NILFS2', 'NILFS2', 0); -- -------------------------------------------------------- @@ -783,7 +864,8 @@ INSERT INTO `sistemasficheros` (`idsistemafichero`, `descripcion`, `nemonico`, ` -- Estructura de tabla para la tabla `softwares` -- -CREATE TABLE IF NOT EXISTS `softwares` ( +DROP TABLE IF EXISTS `softwares`; +CREATE TABLE `softwares` ( `idsoftware` int(11) NOT NULL AUTO_INCREMENT, `idtiposoftware` int(11) NOT NULL DEFAULT '0', `descripcion` varchar(250) NOT NULL DEFAULT '', @@ -800,14 +882,15 @@ CREATE TABLE IF NOT EXISTS `softwares` ( -- Estructura de tabla para la tabla `tareas` -- -CREATE TABLE IF NOT EXISTS `tareas` ( +DROP TABLE IF EXISTS `tareas`; +CREATE TABLE `tareas` ( `idtarea` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', `urlimg` varchar(250) DEFAULT NULL, `idcentro` int(11) NOT NULL DEFAULT '0', `ambito` smallint(6) NOT NULL DEFAULT '0', `idambito` int(11) NOT NULL DEFAULT '0', - `restrambito` text NOT NULL, + `restrambito` text, `comentarios` text, `grupoid` int(11) DEFAULT '0', PRIMARY KEY (`idtarea`) @@ -819,7 +902,8 @@ CREATE TABLE IF NOT EXISTS `tareas` ( -- Estructura de tabla para la tabla `tareas_acciones` -- -CREATE TABLE IF NOT EXISTS `tareas_acciones` ( +DROP TABLE IF EXISTS `tareas_acciones`; +CREATE TABLE `tareas_acciones` ( `idtareaaccion` int(11) NOT NULL AUTO_INCREMENT, `idtarea` int(11) NOT NULL DEFAULT '0', `orden` smallint(6) NOT NULL DEFAULT '0', @@ -834,12 +918,12 @@ CREATE TABLE IF NOT EXISTS `tareas_acciones` ( -- Estructura de tabla para la tabla `tipohardwares` -- -CREATE TABLE IF NOT EXISTS `tipohardwares` ( +DROP TABLE IF EXISTS `tipohardwares`; +CREATE TABLE `tipohardwares` ( `idtipohardware` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', `urlimg` varchar(250) NOT NULL DEFAULT '', - `nemonico` char(3) NOT NULL, - `pci` tinyint(1) NOT NULL, + `nemonico` char(3) NOT NULL DEFAULT '', PRIMARY KEY (`idtipohardware`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=17 ; @@ -847,22 +931,25 @@ CREATE TABLE IF NOT EXISTS `tipohardwares` ( -- Volcar la base de datos para la tabla `tipohardwares` -- -INSERT INTO `tipohardwares` (`idtipohardware`, `descripcion`, `urlimg`, `nemonico`, `pci`) VALUES -(1, 'Placas', '../images/iconos/placabase.gif', 'boa', 0), -(2, 'Dispositivos Multimedia', '../images/iconos/tsonido.gif', 'mul', 0), -(3, 'Tarjetas de Red', '../images/iconos/nic.gif', 'net', 0), -(4, 'Microprocesadores', '../images/iconos/micro.gif', 'cpu', 0), -(5, 'Memorias', '../images/iconos/confihard.gif', 'mem', 0), -(7, 'Tarjetas gráficas', '../images/iconos/vga.gif', 'vga', 0), -(8, 'Discos', '../images/iconos/discoduro.gif', 'dis', 0), -(9, 'Dispositivos de sonido', '../images/iconos/audio.gif', 'aud', 0), -(10, 'Marca y modelo del equipo', '../images/iconos/confihard.gif', 'mod', 0), -(11, 'Modelo y version de la bios', '../images/iconos/confihard.gif', 'bio', 0), -(12, 'Modelo de grabadora o grabadora de CD/DVD', '../images/iconos/dvdcd.gif', 'cdr', 0), -(13, 'Controladores IDE', '../images/iconos/ide.gif', 'ide', 0), -(14, 'Controladores FireWire', '../images/iconos/confihard.gif', 'fir', 0), -(15, 'Controladores USB', '../images/iconos/usb.gif', 'usb', 0), -(16, 'Bus del Sistema', '../images/iconos/confihard.gif', 'bus', 0); +INSERT INTO `tipohardwares` (`idtipohardware`, `descripcion`, `urlimg`, `nemonico`) VALUES +(1, 'Placas', '../images/iconos/placabase.gif', 'boa'), +(2, 'Dispositivos Multimedia', '../images/iconos/tsonido.gif', 'mul'), +(3, 'Tarjetas de Red', '../images/iconos/nic.gif', 'net'), +(4, 'Microprocesadores', '../images/iconos/micro.gif', 'cpu'), +(5, 'Memorias', '../images/iconos/confihard.gif', 'mem'), +(7, 'Tarjetas gráficas', '../images/iconos/vga.gif', 'vga'), +(8, 'Discos', '../images/iconos/discoduro.gif', 'dis'), +(9, 'Dispositivos de sonido', '../images/iconos/audio.gif', 'aud'), +(10, 'Marca y modelo del equipo', '../images/iconos/confihard.gif', 'mod'), +(11, 'Modelo y version de la bios', '../images/iconos/confihard.gif', 'bio'), +(12, 'Modelo de grabadora o grabadora de CD/DVD', '../images/iconos/dvdcd.gif', 'cdr'), +(13, 'Controladores IDE', '../images/iconos/ide.gif', 'ide'), +(14, 'Controladores FireWire', '../images/iconos/confihard.gif', 'fir'), +(15, 'Controladores USB', '../images/iconos/usb.gif', 'usb'), +(16, 'Bus del Sistema', '../images/iconos/confihard.gif', 'bus'), +(17, 'Chasis del Sistema', '', 'cha'), +(18, 'Controladores de almacenamiento', '../images/iconos/almacenamiento.png', 'sto'), +(19, 'Tipo de proceso de arranque', '../images/iconos/arranque.png', 'boo'); -- -------------------------------------------------------- @@ -870,7 +957,8 @@ INSERT INTO `tipohardwares` (`idtipohardware`, `descripcion`, `urlimg`, `nemonic -- Estructura de tabla para la tabla `tiposoftwares` -- -CREATE TABLE IF NOT EXISTS `tiposoftwares` ( +DROP TABLE IF EXISTS `tiposoftwares`; +CREATE TABLE `tiposoftwares` ( `idtiposoftware` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', `urlimg` varchar(250) NOT NULL DEFAULT '', @@ -892,10 +980,11 @@ INSERT INTO `tiposoftwares` (`idtiposoftware`, `descripcion`, `urlimg`) VALUES -- Estructura de tabla para la tabla `tiposos` -- -CREATE TABLE IF NOT EXISTS `tiposos` ( +DROP TABLE IF EXISTS `tiposos`; +CREATE TABLE `tiposos` ( `idtiposo` int(11) NOT NULL AUTO_INCREMENT, - `tiposo` varchar(250) NOT NULL, - `idplataforma` int(11) NOT NULL, + `tiposo` varchar(250) NOT NULL DEFAULT '', + `idplataforma` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`idtiposo`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ; @@ -920,10 +1009,11 @@ INSERT INTO `tiposos` (`idtiposo`, `tiposo`, `idplataforma`) VALUES -- Estructura de tabla para la tabla `tipospar` -- -CREATE TABLE IF NOT EXISTS `tipospar` ( +DROP TABLE IF EXISTS `tipospar`; +CREATE TABLE `tipospar` ( `codpar` int(8) NOT NULL, - `tipopar` varchar(250) NOT NULL, - `clonable` tinyint(4) NOT NULL, + `tipopar` varchar(250) NOT NULL DEFAULT '', + `clonable` tinyint(4) NOT NULL DEFAULT '0', UNIQUE KEY `codpar` (`codpar`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; @@ -947,6 +1037,7 @@ INSERT INTO `tipospar` (`codpar`, `tipopar`, `clonable`) VALUES (CONV('8E',16,10), 'LINUX-LVM', 1), (CONV('A5',16,10), 'FREEBSD', 1), (CONV('A6',16,10), 'OPENBSD', 1), +(CONV('A9',16,10), 'NETBSD', 1), (CONV('AF',16,10), 'HFS', 1), (CONV('BE',16,10), 'SOLARIS-BOOT', 1), (CONV('BF',16,10), 'SOLARIS', 1), @@ -958,20 +1049,30 @@ INSERT INTO `tipospar` (`codpar`, `tipopar`, `clonable`) VALUES (CONV('FD',16,10), 'LINUX-RAID', 1), (CONV('0700',16,10), 'WINDOWS', 1), (CONV('0C01',16,10), 'WIN-RESERV', 1), +(CONV('2700',16,10), 'WIN-RECOV', 1), (CONV('7F00',16,10), 'CHROMEOS-KRN', 1), (CONV('7F01',16,10), 'CHROMEOS', 1), (CONV('7F02',16,10), 'CHROMEOS-RESERV', 1), (CONV('8200',16,10), 'LINUX-SWAP', 0), (CONV('8300',16,10), 'LINUX', 1), (CONV('8301',16,10), 'LINUX-RESERV', 1), +(CONV('8302',16,10), 'LINUX', 1), (CONV('8E00',16,10), 'LINUX-LVM', 1), (CONV('A500',16,10), 'FREEBSD-DISK', 0), (CONV('A501',16,10), 'FREEBSD-BOOT', 1), (CONV('A502',16,10), 'FREEBSD-SWAP', 0), (CONV('A503',16,10), 'FREEBSD', 1), +(CONV('A504',16,10), 'FREEBSD', 1), +(CONV('A901',16,10), 'NETBSD-SWAP', 0), +(CONV('A902',16,10), 'NETBSD', 1), +(CONV('A903',16,10), 'NETBSD', 1), +(CONV('A904',16,10), 'NETBSD', 1), +(CONV('A905',16,10), 'NETBSD', 1), +(CONV('A906',16,10), 'NETBSD-RAID', 1), (CONV('AB00',16,10), 'HFS-BOOT', 1), (CONV('AF00',16,10), 'HFS', 1), (CONV('AF01',16,10), 'HFS-RAID', 1), +(CONV('AF02',16,10), 'HFS-RAID', 1), (CONV('BE00',16,10), 'SOLARIS-BOOT', 1), (CONV('BF00',16,10), 'SOLARIS', 1), (CONV('BF01',16,10), 'SOLARIS', 1), @@ -983,8 +1084,14 @@ INSERT INTO `tipospar` (`codpar`, `tipopar`, `clonable`) VALUES (CONV('EF00',16,10), 'EFI', 1), (CONV('EF01',16,10), 'MBR', 0), (CONV('EF02',16,10), 'BIOS-BOOT', 0), +(CONV('FB00',16,10), 'VMFS', 1), +(CONV('FB01',16,10), 'VMFS-RESERV', 1), +(CONV('FB02',16,10), 'VMFS-KRN', 1), (CONV('FD00',16,10), 'LINUX-RAID', 1), -(CONV('FFFF',16,10), 'UNKNOWN', 1); +(CONV('FFFF',16,10), 'UNKNOWN', 1), +(CONV('10000',16,10), 'LVM-LV', 1), +(CONV('10010',16,10), 'ZFS-VOL', 1); + -- -------------------------------------------------------- @@ -992,7 +1099,8 @@ INSERT INTO `tipospar` (`codpar`, `tipopar`, `clonable`) VALUES -- Estructura de tabla para la tabla `universidades` -- -CREATE TABLE IF NOT EXISTS `universidades` ( +DROP TABLE IF EXISTS `universidades`; +CREATE TABLE `universidades` ( `iduniversidad` int(11) NOT NULL AUTO_INCREMENT, `nombreuniversidad` varchar(200) NOT NULL DEFAULT '', `comentarios` text, @@ -1004,7 +1112,7 @@ CREATE TABLE IF NOT EXISTS `universidades` ( -- INSERT INTO `universidades` (`iduniversidad`, `nombreuniversidad`, `comentarios`) VALUES -(1, 'Universidad (Default)', 'Esta Universidad se crea automáticamentese en el proceso de instalación de OpenGnSys'); +(1, 'Universidad (Default)', 'Esta Universidad se crea automáticamentese en el proceso de instalación de OpenGnsys'); -- -------------------------------------------------------- @@ -1012,7 +1120,8 @@ INSERT INTO `universidades` (`iduniversidad`, `nombreuniversidad`, `comentarios` -- Estructura de tabla para la tabla `urlimagesitems` -- -CREATE TABLE IF NOT EXISTS `urlimagesitems` ( +DROP TABLE IF EXISTS `urlimagesitems`; +CREATE TABLE `urlimagesitems` ( `idurlimagesitems` int(11) NOT NULL AUTO_INCREMENT, `descripcion` varchar(250) NOT NULL DEFAULT '', PRIMARY KEY (`idurlimagesitems`) @@ -1029,14 +1138,16 @@ CREATE TABLE IF NOT EXISTS `urlimagesitems` ( -- Estructura de tabla para la tabla `usuarios` -- -CREATE TABLE IF NOT EXISTS `usuarios` ( +DROP TABLE IF EXISTS `usuarios`; +CREATE TABLE `usuarios` ( `idusuario` int(11) NOT NULL AUTO_INCREMENT, `usuario` varchar(50) NOT NULL DEFAULT '', - `pasguor` varchar(50) NOT NULL DEFAULT '', + `pasguor` varchar(56) NOT NULL DEFAULT '', `nombre` varchar(200) DEFAULT NULL, `email` varchar(200) DEFAULT NULL, `ididioma` int(11) DEFAULT NULL, `idtipousuario` tinyint(4) DEFAULT NULL, + `apikey` varchar(32) NOT NULL DEFAULT '', PRIMARY KEY (`idusuario`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; @@ -1044,7 +1155,7 @@ CREATE TABLE IF NOT EXISTS `usuarios` ( -- Volcar la base de datos para la tabla `usuarios` -- -INSERT INTO `usuarios` (`idusuario`, `usuario`, `pasguor`, `nombre`, `email`, `ididioma`, `idtipousuario`) VALUES -(1, 'DBUSER', 'DBPASSWORD', 'Usuario de la base de datos MySql', '', 1, 1); +INSERT INTO `usuarios` (`idusuario`, `usuario`, `pasguor`, `nombre`, `email`, `ididioma`, `idtipousuario`, `apikey`) VALUES +(1, 'DBUSER', SHA2('DBPASSWORD', 224), 'Usuario de la base de datos MySql', '', 1, 1, 'APIKEY'); diff --git a/admin/Interface/CambiarAcceso b/admin/Interface/CambiarAcceso index 50df9b49..b57cfcd2 100755 --- a/admin/Interface/CambiarAcceso +++ b/admin/Interface/CambiarAcceso @@ -6,7 +6,7 @@ # $1 modo (admin, user) #______________________________________ -# Error si llamada no se realliza desde OpenGnSys Client. +# Error si llamada no se realliza desde OpenGnsys Client. PROG=$(basename $0) CALLER=$(ogGetCaller) if ! $(ogCheckStringInGroup "$CALLER" "CrearImagen ConsolaRemota CrearImagenBasica CrearSoftIncremental"); then @@ -41,12 +41,14 @@ esac # Desmontar repositorio y volver a montarlo con el modo adecuado. umount $OGIMG +# Unidad organizativa +[ "$ogunit" != "" ] && OGUNIT="/$ogunit" ogEcho info "$PROG: Montar repositorio $REPO por $PROTO en modo $1" case "$PROTO" in - nfs) mount -t nfs $REPOIP:$OGIMG $OGIMG -o $MODE ;; + nfs) mount -t nfs $REPOIP:$OGIMG$OGUNIT $OGIMG -o $MODE ;; smb) PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \ sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') PASS=${PASS:-"og"} - mount.cifs //$REPOIP/ogimages $OGIMG -o $MODE,serverino,acl,username=opengnsys,password=$PASS + mount.cifs //$REPOIP/ogimages$OGUNIT $OGIMG -o $MODE,serverino,acl,username=opengnsys,password=$PASS esac diff --git a/admin/Interface/Configurar b/admin/Interface/Configurar index fcf77b95..554e52c9 100755 --- a/admin/Interface/Configurar +++ b/admin/Interface/Configurar @@ -12,7 +12,7 @@ echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.t # Registro de inicio de ejecución ogEcho log session "$MSG_INTERFACE_START $0 $*" -# Solo ejecutable por OpenGnSys Client. +# Solo ejecutable por OpenGnsys Client. PATH=$PATH:$(dirname $0) PROG=$(basename $0) @@ -78,7 +78,7 @@ for ((i=0; i<${#TBPRM[@]}; i++)); do # Si se activa operación de formatear, componer datos de formateo. if [ "$ope" == 1 ]; then # Comprobamos que la particion y el s.f sean validos. - ogCheckStringInGroup $cpt "EMPTY EXTENDED LINUX-LVM" + ogCheckStringInGroup $cpt "EMPTY EXTENDED LINUX-LVM LVM ZPOOL" [ $? -ne 0 ] && TBF[par]="$sfi" fi # Obtener la partición mayor. diff --git a/admin/Interface/CrearImagen b/admin/Interface/CrearImagen index c3fa9b45..e3b21c7a 100755 --- a/admin/Interface/CrearImagen +++ b/admin/Interface/CrearImagen @@ -42,7 +42,7 @@ echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.t # Registro de inicio de ejecución ogEcho log session "$MSG_INTERFACE_START $0 $*" -# Solo ejecutable por OpenGnSys Client. +# Solo ejecutable por OpenGnsys Client. PATH=$PATH:$(dirname $0) PROG=$(basename $0) CALLER=$(ogGetCaller) @@ -53,9 +53,16 @@ fi # Valor por defecto para el repositorio. REPO=${4:-"REPO"} -[ "$REPO" == "$(ogGetRepoIp)" ] && REPO="REPO" [ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE" -[ "$REPO" == "CACHE" ] && REPO="CACHE" +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPO +if [ $? == 0 -o $REPO == "REPO" ] ; then + # Unidad organizativa + [ "$ogunit" != "" ] && OGUNIT="$ogunit" + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?) + REPO="REPO" +fi # Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura, if [ "$REPO" == "REPO" -a "$boot" != "admin" ] @@ -65,11 +72,12 @@ then [ $RETVAL -gt 0 ] && exit $RETVAL fi +ogEcho createImage "$1" "$2" "$4" /"$3" # Si existe, ejecuta script personalizado "createImageCustom"; si no, llama al genérico "createImage". if which createImageCustom &>/dev/null; then - createImageCustom "$1" "$2" "$REPO" /"$3" &>> $OGLOGCOMMAND + createImageCustom "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND else - createImage "$1" "$2" "$REPO" /"$3" &>> $OGLOGCOMMAND + createImage "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND fi RETVAL=$? diff --git a/admin/Interface/getConfiguration b/admin/Interface/getConfiguration index 0979986d..ddfc3821 100755 --- a/admin/Interface/getConfiguration +++ b/admin/Interface/getConfiguration @@ -7,6 +7,10 @@ #_______________________________________________________________________________________________________________________________ +# No registrar los errores. +export DEBUG="no" + +ser=$(ogGetSerialNumber) cfg="" disks=$(ogDiskToDev | wc -w) for ((dsk=1; dsk<=$disks; dsk++)); do @@ -18,10 +22,11 @@ for ((dsk=1; dsk<=$disks; dsk++)); do MSDOS) ptt=1 ;; GPT) ptt=2 ;; LVM) ptt=3 ;; + ZPOOL) ptt=4 ;; *) ptt=0 ;; esac # Información de disco (partición 0) - cfg="$cfg$dsk:0:$ptt:::$(ogGetDiskSize $dsk);" + cfg="$cfg$dsk:0:$ptt:::$(ogGetDiskSize $dsk):0;" for ((par=1;par<=$particiones;par++)); do # Código del identificador de tipo de partición cod=$(ogGetPartitionId $dsk $par 2>/dev/null) @@ -33,14 +38,23 @@ for ((dsk=1; dsk<=$disks; dsk++)); do tam=${tam:-"0"} # Sistema operativo instalado case "$fsi" in - ""|EMPTY|CACHE|LINUX-SWAP|LINUX-LVM) - soi="" ;; - *) soi=$(getOsVersion $dsk $par 2>/dev/null | cut -f2 -d:) - # Sistema de archivos para datos (sistema operativo "DATA") - [ -z "$soi" -a "$fsi" != "EMPTY" -a "$fsi" != "CACHE" ] && soi="DATA" + ""|EMPTY|LINUX-SWAP|LINUX-LVM|ZVOL) + soi=""; uso=0 ;; + *) if [ -n "$(ogMount $dsk $par 2>/dev/null)" ]; then + soi=$(getOsVersion $dsk $par 2>/dev/null | cut -f2 -d:) + # Hacer un 2º intento para algunos casos especiales. + [ -z "$soi" ] && soi=$(getOsVersion $dsk $par 2>/dev/null | cut -f2 -d:) + # Sistema de archivos para datos (sistema operativo "DATA") + [ -z "$soi" -a "$fsi" != "EMPTY" -a "$fsi" != "CACHE" ] && soi="DATA" + # Obtener porcentaje de uso. + uso=$(df $(ogGetMountPoint $dsk $par) | awk '{getline; printf "%d",$5}') + uso=${uso:0} + else + soi=""; uso=0 + fi ;; esac - cfg="$cfg$dsk:$par:$cod:$fsi:$soi:$tam;" + cfg="$cfg$dsk:$par:$cod:$fsi:$soi:$tam:$uso;" done done @@ -49,7 +63,7 @@ done # Guardar salida en fichero temporal. cfgfile=/tmp/getconfig -echo $cfg > $cfgfile +echo "${ser:+$ser;}$cfg" > $cfgfile # Crear el menú por defecto a partir del fichero generado (no dar ninguna salida). generateMenuDefault &>/dev/null @@ -57,9 +71,18 @@ generateMenuDefault &>/dev/null # Componer salida formateada. awk '{ n=split($0,sep,";"); for (i=1; i=DEBUG_MAXIMO) { @@ -1483,6 +1484,11 @@ BOOLEAN RestaurarImagen(TRAMA* ptrTrama) else muestraMensaje(11,NULL); + /* Obtener nueva configuracin */ + cfg=LeeConfiguracion(); + if(!cfg){ // No se puede recuperar la configuracin del cliente + errorLog(modulo,36,FALSE); + } /* Envia respuesta de ejecucin de la funcin de interface */ initParametros(ptrTrama,0); @@ -1491,6 +1497,7 @@ BOOLEAN RestaurarImagen(TRAMA* ptrTrama) lon+=sprintf(ptrTrama->parametros+lon,"dsk=%s\r",dsk); // Nmero de disco lon+=sprintf(ptrTrama->parametros+lon,"par=%s\r",par); // Nmero de particin lon+=sprintf(ptrTrama->parametros+lon,"ifs=%s\r",ifs); // Identificador del perfil software + lon+=sprintf(ptrTrama->parametros+lon,"cfg=%s\r",cfg); // Configuracin de discos respuestaEjecucionComando(ptrTrama,herror,ids); liberaMemoria(nfn); @@ -1500,6 +1507,7 @@ BOOLEAN RestaurarImagen(TRAMA* ptrTrama) liberaMemoria(nci); liberaMemoria(ipr); liberaMemoria(ifs); + liberaMemoria(cfg); liberaMemoria(ptc); liberaMemoria(ids); @@ -1521,7 +1529,7 @@ BOOLEAN RestaurarImagen(TRAMA* ptrTrama) BOOLEAN RestaurarImagenBasica(TRAMA* ptrTrama) { int lon; - char *nfn,*dsk,*par,*idi,*ipr,*met,*nci,*rti,*ifs,*msy,*whl,*eli,*cmp,*tpt,*bpi,*cpc,*bpc,*nba,*ids,msglog[LONSTD]; + char *nfn,*dsk,*par,*idi,*ipr,*met,*nci,*rti,*ifs,*cfg,*msy,*whl,*eli,*cmp,*tpt,*bpi,*cpc,*bpc,*nba,*ids,msglog[LONSTD]; char modulo[] = "RestaurarImagenBasica()"; if (ndebug>=DEBUG_MAXIMO) { @@ -1544,8 +1552,6 @@ BOOLEAN RestaurarImagenBasica(TRAMA* ptrTrama) eli=copiaParametro("eli",ptrTrama); // Elimiar archivos en destino que no estn en origen cmp=copiaParametro("cmp",ptrTrama); // Comprimir antes de enviar - - bpi=copiaParametro("bpi",ptrTrama); // Borrar la imagen antes de crearla cpc=copiaParametro("cpc",ptrTrama); // Copiar tambin imagen a la cache bpc=copiaParametro("bpc",ptrTrama); // Borrarla de la cache antes de copiarla en ella @@ -1565,6 +1571,12 @@ BOOLEAN RestaurarImagenBasica(TRAMA* ptrTrama) else muestraMensaje(32,NULL); + /* Obtener nueva configuracin */ + cfg=LeeConfiguracion(); + if(!cfg){ // No se puede recuperar la configuracin del cliente + errorLog(modulo,36,FALSE); + } + /* Envia respuesta de ejecucin de la funcin de interface */ initParametros(ptrTrama,0); lon=sprintf(ptrTrama->parametros,"nfn=%s\r","RESPUESTA_RestaurarImagenBasica"); @@ -1572,33 +1584,35 @@ BOOLEAN RestaurarImagenBasica(TRAMA* ptrTrama) lon+=sprintf(ptrTrama->parametros+lon,"dsk=%s\r",dsk); // Nmero de disco lon+=sprintf(ptrTrama->parametros+lon,"par=%s\r",par); // Nmero de particin lon+=sprintf(ptrTrama->parametros+lon,"ifs=%s\r",ifs); // Identificador del perfil software + lon+=sprintf(ptrTrama->parametros+lon,"cfg=%s\r",cfg); // Configuracin de discos respuestaEjecucionComando(ptrTrama,herror,ids); - - liberaMemoria(nfn); - liberaMemoria(dsk); - liberaMemoria(par); - liberaMemoria(idi); - liberaMemoria(nci); - liberaMemoria(rti); - liberaMemoria(ifs); - liberaMemoria(ipr); + + liberaMemoria(nfn); + liberaMemoria(dsk); + liberaMemoria(par); + liberaMemoria(idi); + liberaMemoria(nci); + liberaMemoria(rti); + liberaMemoria(ifs); + liberaMemoria(cfg); + liberaMemoria(ipr); liberaMemoria(met); - liberaMemoria(tpt); - liberaMemoria(msy); + liberaMemoria(tpt); + liberaMemoria(msy); - liberaMemoria(whl); - liberaMemoria(eli); - liberaMemoria(cmp); + liberaMemoria(whl); + liberaMemoria(eli); + liberaMemoria(cmp); - liberaMemoria(bpi); - liberaMemoria(cpc); - liberaMemoria(bpc); + liberaMemoria(bpi); + liberaMemoria(cpc); + liberaMemoria(bpc); liberaMemoria(nba); - liberaMemoria(ids); + liberaMemoria(ids); muestraMenu(); - + return(TRUE); } //______________________________________________________________________________________________________ diff --git a/admin/Sources/Clients/ogAdmLnxClient/Makefile b/admin/Sources/Clients/ogAdmLnxClient/Makefile deleted file mode 100644 index bc2fe3a9..00000000 --- a/admin/Sources/Clients/ogAdmLnxClient/Makefile +++ /dev/null @@ -1,34 +0,0 @@ -# makefile - -# Nombre del proyecto -PROYECTO := ogAdmLnxClient - -# Directorios y librerias -DIRS := -LIBS := -static - -# Opciones de compilacion -#OPCS := -m32 -O0 -g -Wall # Depuracion -OPCS := -m32 -O3 -Wall # Optimizacion - -# Ficheros objetos -OBJS := sources/ogAdmLnxClient.o - -all: $(PROYECTO) - -$(PROYECTO): $(OBJS) - g++ $(OPCS) $(DIRS) $(LIBS) $(OBJS) -o $(PROYECTO) - strip $(PROYECTO) # Optimizacion - -clean: - rm $(PROYECTO) $(OBJS) - -sources/%.o: sources/%.cpp - g++ $(OPCS) -c -o"$@" "$<" - -sources/%.o: sources/%.c - gcc $(OPCS) -I ../../Includes -c -o"$@" "$<" - - - - diff --git a/admin/Sources/Clients/ogAdmLnxClient/ogAdmLnxClient.cfg b/admin/Sources/Clients/ogAdmLnxClient/ogAdmLnxClient.cfg deleted file mode 100644 index 80d69686..00000000 --- a/admin/Sources/Clients/ogAdmLnxClient/ogAdmLnxClient.cfg +++ /dev/null @@ -1,4 +0,0 @@ -ServidorAdm=Direccin IP del servidor de administracin -PUERTO=Puerto del servidor de administracin -IPLOCAL=Direccin IP local - diff --git a/admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.c b/admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.c deleted file mode 100644 index 0c4c431e..00000000 --- a/admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.c +++ /dev/null @@ -1,499 +0,0 @@ -// ******************************************************************************************************** -// Cliernte: ogAdmLnxClient -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Febrero-2012 -// Fecha Última modificación: Febrero-2012 -// Nombre del fichero: ogAdmLnxClient.c -// Descripción :Este fichero implementa el cliente windows del sistema -// ******************************************************************************************************** -#include "ogAdmLnxClient.h" -#include "ogAdmLib.c" - -// ________________________________________________________________________________________________________ -// Función: EjecutarScript -// -// Descripción: -// Ejecuta código de script -// Parámetros: -// ptrTrama: contenido del mensaje -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -//______________________________________________________________________________________________________ -BOOLEAN EjecutarScript(TRAMA* ptrTrama) -{ - int lon,resul,res; - char *nfn,*ids,*cod,*scp,msglog[LONSTD]; - char modulo[] = "EjecutarScript()"; - - - if (ndebug>=DEBUG_MAXIMO) { - sprintf(msglog, "%s:%s",tbMensajes[21],modulo); - infoDebug(msglog); - } - - nfn=copiaParametro("nfn",ptrTrama); - ids=copiaParametro("ids",ptrTrama); - - scp=copiaParametro("scp",ptrTrama); - cod=URLDecode(scp); - - res=0; - /* Nombre del archivo de script */ - char filescript[LONPRM]; - sprintf(filescript,"/tmp/_script_%s",IPlocal); - if(!escribeArchivo(filescript,cod)){ - errorLog(modulo, 52, FALSE); - res=52; // Error al crear fichero de comandos - } - - if(res==0){ - sprintf(filescript,"chmod 0777 /tmp/_script_%s",IPlocal); - - resul=system(filescript); - if (resul==0) { - sprintf(filescript,"/tmp/_script_%s",IPlocal); - resul=system(filescript); - if (resul>0) { - errorLog(modulo, 86, FALSE); - } - } - } - - initParametros(ptrTrama,0); - lon=sprintf(ptrTrama->parametros,"nfn=%s\r","RESPUESTA_EjecutarScript"); - respuestaEjecucionComando(ptrTrama,resul,ids); - return(TRUE); -} -//________________________________________________________________________________________________________ -// Función: tomaConfiguracion -// -// Descripción: -// Lee el fichero de configuración del servicio -// Parámetros: -// filecfg : Ruta completa al fichero de configuración -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -//________________________________________________________________________________________________________ -BOOLEAN tomaConfiguracion(char* filecfg) -{ - char modulo[] = "tomaConfiguracion()"; - - if (filecfg == NULL || strlen(filecfg) == 0) { - errorLog(modulo, 1, FALSE); // Fichero de configuración del cliente vacío - return (FALSE); - } - FILE *fcfg; - int lSize; - char * buffer, *lineas[MAXPRM], *dualparametro[2]; - int i, numlin, resul; - - fcfg = fopen(filecfg, "rt"); - if (fcfg == NULL) { - errorLog(modulo, 2, FALSE); // No existe fichero de configuración del cliente - return (FALSE); - } - - fseek(fcfg, 0, SEEK_END); - lSize = ftell(fcfg); // Obtiene tamaño del fichero. - rewind(fcfg); - buffer = (char*) reservaMemoria(lSize+1); // Toma memoria para el buffer de lectura. - if (buffer == NULL) { // No hay memoria suficiente para el buffer - errorLog(modulo, 3, FALSE); - return (FALSE); - } - lSize=fread(buffer, 1, lSize, fcfg); // Lee contenido del fichero - buffer[lSize]=CHARNULL; - fclose(fcfg); - - /* Inicializar variables globales */ - servidoradm[0]=CHARNULL; - puerto[0] = CHARNULL; - IPlocal[0]=CHARNULL; - - numlin = splitCadena(lineas, buffer, '\n'); - for (i = 0; i < numlin; i++){ - splitCadena(dualparametro, lineas[i], '='); - - resul = strcmp(StrToUpper(dualparametro[0]), "SERVIDORADM"); - if (resul == 0) - strcpy(servidoradm, dualparametro[1]); - - resul = strcmp(StrToUpper(dualparametro[0]), "PUERTO"); - if (resul == 0) - strcpy(puerto, dualparametro[1]); - - resul = strcmp(StrToUpper(dualparametro[0]), "IPLOCAL"); - if (resul == 0) - strcpy(IPlocal, dualparametro[1]); - } - - if (servidoradm[0] == CHARNULL) { - errorLog(modulo,4, FALSE); // Falta parámetro SERVIDORADM - return (FALSE); - } - - if (puerto[0] == CHARNULL) { - errorLog(modulo,5, FALSE); // Falta parámetro PUERTO - return (FALSE); - } - if (IPlocal[0] == CHARNULL) { - errorLog(modulo, 92, FALSE); // Falta parámetro IPLOCAL - return (FALSE); - } - return (TRUE); -} -//______________________________________________________________________________________________________ -// Función: InclusionClienteWinLnx -// Descripción: -// Abre una sesión en el servidor de administración y registra al cliente en el sistema -// Parámetros: -// Ninguno -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -//______________________________________________________________________________________________________ -BOOLEAN InclusionClienteWinLnx(TRAMA* ptrTrama) -{ - int lon; - SOCKET socket_c; - char modulo[] = "InclusionClienteWinLnx()"; - - initParametros(ptrTrama,0); - lon=sprintf(ptrTrama->parametros,"nfn=InclusionClienteWinLnx\r"); // Nombre de la función a ejecutar en el servidor - - if(!enviaMensajeServidor(&socket_c,ptrTrama,MSG_PETICION)){ - errorLog(modulo,37,FALSE); - return(FALSE); - } - ptrTrama=recibeMensaje(&socket_c); - if(!ptrTrama){ - errorLog(modulo,22,FALSE); - return(FALSE); - } - close(socket_c); - - if(!gestionaTrama(ptrTrama)){ // Análisis de la trama - errorLog(modulo,39,FALSE); - return(FALSE); - } - - return(TRUE); -} -//______________________________________________________________________________________________________ -// Función: RESPUESTA_InclusionClienteWinLnx -// -// Descripción: -// Respuesta del servidor de administración a la petición de inicio -// enviando los datos identificativos del cliente -// Parámetros: -// - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -//______________________________________________________________________________________________________ -BOOLEAN RESPUESTA_InclusionClienteWinLnx(TRAMA* ptrTrama) -{ - char* res; - char modulo[] = "RESPUESTA_InclusionClienteWinLnx()"; - int err; - - res=copiaParametro("res",ptrTrama); // Resultado del proceso de inclusión - err=(int)atoi(res); // Código de error devuelto por el servidor - if(err>0){ // Error en el proceso de inclusión - errorLog(modulo,41,FALSE); - errorLog(modulo,err,FALSE); - return (FALSE); - } - strcpy(idordenador,copiaParametro("ido",ptrTrama)); // Identificador del ordenador - strcpy(nombreordenador,copiaParametro("npc",ptrTrama)); // Nombre del ordenador - - if(idordenador==NULL || nombreordenador==NULL){ - errorLog(modulo,40,FALSE); - return (FALSE); - } - return(TRUE); -} -//______________________________________________________________________________________________________ -// Función: ProcesaComandos -// -// Descripción: -// Espera comando desde el Servidor de Administración para ejecutarlos -// Parámetros: -// Ninguno -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -void procesaComandos(TRAMA* ptrTrama) -{ - int lon; - SOCKET socket_c; - char modulo[] = "procesaComandos()"; - - initParametros(ptrTrama,0); - while(TRUE){ - lon=sprintf(ptrTrama->parametros,"nfn=DisponibilidadComandos\r"); - lon+=sprintf(ptrTrama->parametros+lon,"tpc=%s\r",CLIENTE_LNX); // Activar disponibilidad - if(!enviaMensajeServidor(&socket_c,ptrTrama,MSG_INFORMACION)){ - errorLog(modulo,43,FALSE); - return; - } - infoLog(19); // Disponibilidad de cliente activada - ptrTrama=recibeMensaje(&socket_c); - if(!ptrTrama){ - errorLog(modulo,46,FALSE); - return; - } - - close(socket_c); - - if(!gestionaTrama(ptrTrama)){ // Análisis de la trama - errorLog(modulo,39,FALSE); - return; - } - } -} -//_____________________________________________________________________________________________________ -// Función: Apagar -// -// Descripción: -// Apaga el cliente -// Parámetros: -// ptrTrama: contenido del mensaje -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -//_____________________________________________________________________________________________________ -BOOLEAN Apagar(TRAMA* ptrTrama) -{ - int lon; - char *ids,msglog[LONSTD]; - char modulo[] = "Apagar()"; - - if (ndebug>=DEBUG_MAXIMO) { - sprintf(msglog, "%s:%s",tbMensajes[21],modulo); - infoDebug(msglog); - } - ids=copiaParametro("ids",ptrTrama); - - initParametros(ptrTrama,0); - lon=sprintf(ptrTrama->parametros,"nfn=%s\r","RESPUESTA_Apagar"); - respuestaEjecucionComando(ptrTrama,0,ids); - - system("shutdown -h now"); - return(TRUE); -} -//_____________________________________________________________________________________________________ -// Función: Reiniciar -// -// Descripción: -// Apaga el cliente -// Parámetros: -// ptrTrama: contenido del mensaje -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún errorservidoradm -//_____________________________________________________________________________________________________ -BOOLEAN Reiniciar(TRAMA* ptrTrama) -{ - int lon; - char *ids,msglog[LONSTD]; - char modulo[] = "Reiniciar()"; - - if (ndebug>=DEBUG_MAXIMO) { - sprintf(msglog, "%s:%s",tbMensajes[21],modulo); - infoDebug(msglog); - } - ids=copiaParametro("ids",ptrTrama); - - initParametros(ptrTrama,0); - lon=sprintf(ptrTrama->parametros,"nfn=%s\r","RESPUESTA_Reiniciar"); - respuestaEjecucionComando(ptrTrama,0,ids); - - system("shutdown -r now"); - - return(TRUE); -} -//______________________________________________________________________________________________________ -// Función: Sondeo -// -// Descripción: -// Envía al servidor una confirmación de que está dentro del sistema -// Parámetros: -// ptrTrama: contenido del mensajede -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -//______________________________________________________________________________________________________ -BOOLEAN Sondeo(TRAMA* ptrTrama) -{ - return(TRUE); -} -//______________________________________________________________________________________________________ -// Función: respuestaEjecucionComando -// -// Descripción: -// Envia una respuesta a una ejecucion de comando al servidor de Administración -// Parámetros: -// - ptrTrama: contenido del mensaje -// - res: Resultado de la ejecución (Código de error devuelto por el script ejecutado) -// - ids: Identificador de la sesion (En caso de no haber seguimiento es NULO) -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -BOOLEAN respuestaEjecucionComando(TRAMA* ptrTrama,int res,char *ids) -{ - int lon; - SOCKET socket_c; - char modulo[] = "respuestaEjecucionComando()"; - - lon=strlen(ptrTrama->parametros); - if(ids){ // Existe seguimiento - lon+=sprintf(ptrTrama->parametros+lon,"ids=%s\r",ids); // Añade identificador de la sesión - } - if (res==0){ // Resultado satisfactorio - lon+=sprintf(ptrTrama->parametros+lon,"res=%s\r","1"); - lon+=sprintf(ptrTrama->parametros+lon,"der=%s\r",""); - } - else{ // Algún error - lon+=sprintf(ptrTrama->parametros+lon,"res=%s\r","2"); - lon+=sprintf(ptrTrama->parametros+lon,"der=(Errno:%d)-%s\r",res,tbErrores[res]);// Descripción del error - } - if(!(enviaMensajeServidor(&socket_c,ptrTrama,MSG_NOTIFICACION))){ - errorLog(modulo,44,FALSE); - return(FALSE); - } - close(socket_c); - return(TRUE); -} -// ________________________________________________________________________________________________________ -// Función: gestionaTrama -// -// Descripción: -// Procesa las tramas recibidas.servidoradm -// Parametros: -// ptrTrama: contenido del mensaje -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -BOOLEAN gestionaTrama(TRAMA *ptrTrama) -{ - int i, res; - char *nfn; - char modulo[] = "gestionaTrama()"; - - INTROaFINCAD(ptrTrama); - nfn = copiaParametro("nfn", ptrTrama); // Toma nombre de función - - for (i = 0; i < MAXIMAS_FUNCIONES; i++) { // Recorre funciones que procesan las tramas - res = strcmp(tbfuncionesClient[i].nf, nfn); - if (res == 0) { // Encontrada la función que procesa el mensaje - return(tbfuncionesClient[i].fptr(ptrTrama)); // Invoca la función - } - } - errorLog(modulo, 18, FALSE); - return (FALSE); -} -//______________________________________________________________________________________________________ -// Función: enviaMensajeServidor -// -// Descripción: -// Envia un mensaje al servidor de Administración -// Parámetros: -// - socket_c: (Salida) Socket utilizado para el envío -// - ptrTrama: contenido del mensaje -// - tipo: Tipo de mensaje -// C=Comando, N=Respuesta a un comando, P=Peticion,R=Respuesta a una petición, I=Informacion -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -BOOLEAN enviaMensajeServidor(SOCKET *socket_c,TRAMA *ptrTrama,char tipo) -{ - int lon; - char modulo[] = "enviaMensajeServidor()"; - - *socket_c=abreConexion(); - if(*socket_c==INVALID_SOCKET){ - errorLog(modulo,38,FALSE); // Error de conexión con el servidor - return(FALSE); - } - ptrTrama->arroba='@'; // Cabecera de la trama - strncpy(ptrTrama->identificador,"JMMLCAMDJ_MCDJ",14); // identificador de la trama - ptrTrama->tipo=tipo; // Tipo de mensaje - lon=strlen(ptrTrama->parametros); // Compone la trama - lon+=sprintf(ptrTrama->parametros+lon,"iph=%s\r",IPlocal); // Ip del ordenador - lon+=sprintf(ptrTrama->parametros+lon,"ido=%s\r",idordenador); // Identificador del ordenador - lon+=sprintf(ptrTrama->parametros+lon,"npc=%s\r",nombreordenador); // Nombre del ordenador - - if (!mandaTrama(socket_c,ptrTrama)) { - errorLog(modulo,26,FALSE); - return (FALSE); - } - return(TRUE); -} -// ******************************************************************************************************** -// PROGRAMA PRINCIPAL (CLIENTE) -// ******************************************************************************************************** -int main(int argc, char *argv[]) -{ - TRAMA *ptrTrama; - char modulo[] = "main()"; - - ptrTrama=(TRAMA *)reservaMemoria(sizeof(TRAMA)); - if (ptrTrama == NULL) { // No hay memoria suficiente para el bufer de las tramas - errorLog(modulo, 3, FALSE); - exit(EXIT_FAILURE); - } - /*-------------------------------------------------------------------------------------------------------- - Validación de parámetros de ejecución y fichero de configuración - ---------------------------------------------------------------------------------------------------------*/ - /*-------------------------------------------------------------------------------------------------------- - Validación de parámetros de ejecución y fichero de configuración - ---------------------------------------------------------------------------------------------------------*/ - if (!validacionParametros(argc, argv,7)) // Valida parámetros de ejecución - exit(EXIT_FAILURE); - - if (!tomaConfiguracion(szPathFileCfg)) // Toma parametros de configuración - exit(EXIT_FAILURE); - - /*-------------------------------------------------------------------------------------------------------- - Carga catálogo de funciones que procesan las tramas - ---------------------------------------------------------------------------------------------------------*/ - int cf = 0; - - strcpy(tbfuncionesClient[cf].nf, "RESPUESTA_InclusionClienteWinLnx"); - tbfuncionesClient[cf++].fptr = &RESPUESTA_InclusionClienteWinLnx; - - strcpy(tbfuncionesClient[cf].nf, "Apagar"); - tbfuncionesClient[cf++].fptr = &Apagar; - - strcpy(tbfuncionesClient[cf].nf, "Reiniciar"); - tbfuncionesClient[cf++].fptr = &Reiniciar; - - strcpy(tbfuncionesClient[cf].nf, "Sondeo"); - tbfuncionesClient[cf++].fptr = &Sondeo; - - strcpy(tbfuncionesClient[cf].nf, "EjecutarScript"); - tbfuncionesClient[cf++].fptr = &EjecutarScript; - - /*-------------------------------------------------------------------------------------------------------- - Inicio de sesión - ---------------------------------------------------------------------------------------------------------*/ - infoLog(1); // Inicio de sesión - infoLog(3); // Abriendo sesión en el servidor de Administración; - /*-------------------------------------------------------------------------------------------------------- - Inclusión del cliente en el sistema - ---------------------------------------------------------------------------------------------------------*/ - if(!InclusionClienteWinLnx(ptrTrama)){ // Ha habido algún problema al abrir sesión - errorLog(modulo,0,FALSE); - exit(EXIT_FAILURE); - } - infoLog(4); // Cliente iniciado - procesaComandos(ptrTrama); // Bucle para procesar comandos interactivos - exit(EXIT_SUCCESS); -} diff --git a/admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.h b/admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.h deleted file mode 100644 index 8371d2e4..00000000 --- a/admin/Sources/Clients/ogAdmLnxClient/sources/ogAdmLnxClient.h +++ /dev/null @@ -1,54 +0,0 @@ -// ******************************************************************************************************** -// Cliernte: ogAdmLnxClient -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Marzo-2010 -// Fecha Última modificación: Marzo-2010 -// Nombre del fichero: ogAdmLnxClient.h -// Descripción :Este fichero implementa el cliente general del sistema -// ******************************************************************************************************** -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ogAdmLib.h" -// ________________________________________________________________________________________________________ -// Variables globales -// ________________________________________________________________________________________________________ -char idordenador[LONPRM]; // Identificador del ordenador -char nombreordenador[LONPRM]; // Nombre del ordenador - -char servidoradm[LONPRM]; // Dirección IP del servidor de administración -char puerto[LONPRM]; // Puerto de comunicación -char IPlocal[LONPRM]; // Path donde está la interface entre la administración y el módulo de clonación - - -typedef struct{ // Estructura usada para referenciar las funciones que procesan las tramas - char nf[LONFUN]; // Nombre de la función - BOOLEAN (*fptr)(TRAMA*); // Puntero a la función que procesa la trama -}MSGFUN; -MSGFUN tbfuncionesClient[MAXIMAS_FUNCIONES]; -// ________________________________________________________________________________________________________ -// Prototipo de funciones -// ________________________________________________________________________________________________________ - -void procesaComandos(TRAMA*); -BOOLEAN gestionaTrama(TRAMA *); -BOOLEAN InclusionClienteWinLnx(); -BOOLEAN RESPUESTA_InclusionClienteWinLnx(TRAMA *); -BOOLEAN respuestaEjecucionComando(TRAMA *,int,char*); - -BOOLEAN Apagar(TRAMA *); -BOOLEAN Reiniciar(TRAMA *); -BOOLEAN Sondeo(TRAMA *); - -BOOLEAN enviaMensajeServidor(SOCKET *,TRAMA *,char); - diff --git a/admin/Sources/Clients/ogAdmWinClient/Readme b/admin/Sources/Clients/ogAdmWinClient/Readme deleted file mode 100644 index 6585e818..00000000 --- a/admin/Sources/Clients/ogAdmWinClient/Readme +++ /dev/null @@ -1,25 +0,0 @@ - El cliente opengnsys para Windows es una aplicacin que se instala como un servicio, de esta manera, no es necesario - abrir sesin en este sistema operativo para que la mquina cliente se comunique con el administrador de opengnsys. - Actualmente slo responde a los comandos "Apagar" y "Reiniciar". - - -Para INSTALAR esta aplicacin como un servicio windows hay que seguir los siguentes pasos: - -1) Copiar el ejecutable ogAdmWinClient.exe en una carpeta cualquiera --se aconseja la carpeta c:\Windows\system32\opengnsys, crendola previamente--. -2) Abrir una consola y posicionarse en la carpeta seleccionada -3) Teclear: - c>ogAdmClient t -install -s [IP servidor Opengnsys] -p [puerto] -i [IP local usada para comunicaciones con el servidor] - -Este servicio se da de alta en la base de datos de servicios de Windows con estado "detenido" y "manual" por lo que es necesario abrir la consola -del administrador de servicios de Windows para iniciarlos y modificar las propiedades para que arranquen automticamente al iniciarse Windows. - - - Para DESINTALAR esta aplicacin una vez que se ha instalado como servicio hay que hacer: - 1) Abrir una consola y posicionarse en la carpeta donde est el ejecutable del servicio - 2) Teclear: - c>ogAdmClient t -remove - - - -*** El fichero de log del servicio se llama por defecto ogAdmWinClient.log y estar en el caso de que la carpeta del ejecutable sea c:\Windows\system32\opengnsys, - este archivo estar en c:\Windows\system32\ diff --git a/admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.cpp b/admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.cpp deleted file mode 100644 index 2f164d41..00000000 --- a/admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.cpp +++ /dev/null @@ -1,713 +0,0 @@ -// ******************************************************************************************************** -// Cliente: ogAdmWinClient -// Autor: Jos Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creacin: Febrero-2012 -// Fecha ltima modificacin: Febrero-2012 -// Nombre del fichero: ogAdmWinClient.cpp -// Descripcin :Este fichero implementa el cliente windows del sistema -// ******************************************************************************************************** -#include "ogAdmWinClient.h" -#include "ogAdmLib.c" -#include "registrow.c" -//________________________________________________________________________________________________________ -// Funcin: tomaConfiguracion -// -// Descripcin: -// Lee el fichero de configuracin del servicio -// Parmetros: -// filecfg : Ruta completa al fichero de configuracin -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -//________________________________________________________________________________________________________ -BOOLEAN tomaConfiguracion(char* filecfg) -{ - char modulo[] = "tomaConfiguracion()"; - - if (filecfg == NULL || strlen(filecfg) == 0) { - errorLog(modulo, 1, FALSE); // Fichero de configuracin del cliente vaco - return (FALSE); - } - FILE *fcfg; - int lSize; - char * buffer, *lineas[MAXPRM], *dualparametro[2]; - int i, numlin, resul; - - fcfg = fopen(filecfg, "rt"); - if (fcfg == NULL) { - errorLog(modulo, 2, FALSE); // No existe fichero de configuracin del cliente - return (FALSE); - } - - fseek(fcfg, 0, SEEK_END); - lSize = ftell(fcfg); // Obtiene tamao del fichero. - rewind(fcfg); - buffer = (char*) reservaMemoria(lSize+1); // Toma memoria para el buffer de lectura. - if (buffer == NULL) { // No hay memoria suficiente para el buffer - errorLog(modulo, 3, FALSE); - return (FALSE); - } - lSize=fread(buffer, 1, lSize, fcfg); // Lee contenido del fichero - buffer[lSize]=CHARNULL; - fclose(fcfg); - - /* Inicializar variables globales */ - servidoradm[0]=CHARNULL; - puerto[0] = CHARNULL; - IPlocal[0]=CHARNULL; - - numlin = splitCadena(lineas, buffer, '\n'); - for (i = 0; i < numlin; i++){ - splitCadena(dualparametro, lineas[i], '='); - - resul = strcmp(StrToUpper(dualparametro[0]), "SERVIDORADM"); - if (resul == 0) - strcpy(servidoradm, dualparametro[1]); - - resul = strcmp(StrToUpper(dualparametro[0]), "PUERTO"); - if (resul == 0) - strcpy(puerto, dualparametro[1]); - - resul = strcmp(StrToUpper(dualparametro[0]), "IPLOCAL"); - if (resul == 0) - strcpy(IPlocal, dualparametro[1]); - } - - if (servidoradm[0] == CHARNULL) { - errorLog(modulo,4, FALSE); // Falta parmetro SERVIDORADM - return (FALSE); - } - - if (puerto[0] == CHARNULL) { - errorLog(modulo,5, FALSE); // Falta parmetro PUERTO - return (FALSE); - } - if (IPlocal[0] == CHARNULL) { - errorLog(modulo, 92, FALSE); // Falta parmetro IPLOCAL - return (FALSE); - } - return (TRUE); -} -//______________________________________________________________________________________________________ -// Funcin: InclusionClienteWinLnx -// Descripcin: -// Abre una sesin en el servidor de administracin y registra al cliente en el sistema -// Parmetros: -// Ninguno -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -//______________________________________________________________________________________________________ -BOOLEAN InclusionClienteWinLnx(TRAMA* ptrTrama) -{ - int lon; - SOCKET socket_c; - char modulo[] = "InclusionClienteWinLnx()"; - - initParametros(ptrTrama,0); - lon=sprintf(ptrTrama->parametros,"nfn=InclusionClienteWinLnx\r"); // Nombre de la funcin a ejecutar en el servidor - - if(!enviaMensajeServidor(&socket_c,ptrTrama,MSG_PETICION)){ - errorLog(modulo,37,FALSE); - return(FALSE); - } - ptrTrama=recibeMensaje(&socket_c); - if(!ptrTrama){ - errorLog(modulo,22,FALSE); - return(FALSE); - } - closesocket(socket_c); - - if(!gestionaTrama(ptrTrama)){ // Anlisis de la trama - errorLog(modulo,39,FALSE); - return(FALSE); - } - - return(TRUE); -} -//______________________________________________________________________________________________________ -// Funcin: RESPUESTA_InclusionClienteWinLnx -// -// Descripcin: -// Respuesta del servidor de administracin a la peticin de inicio -// enviando los datos identificativos del cliente -// Parmetros: -// - ptrTrama: Trama recibida por el servidor con el contenido y los parmetros -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -//______________________________________________________________________________________________________ -BOOLEAN RESPUESTA_InclusionClienteWinLnx(TRAMA* ptrTrama) -{ - char* res; - char modulo[] = "RESPUESTA_InclusionClienteWinLnx()"; - int err; - - res=copiaParametro("res",ptrTrama); // Resultado del proceso de inclusin - err=(int)atoi(res); // Cdigo de error devuelto por el servidor - if(err>0){ // Error en el proceso de inclusin - errorLog(modulo,41,FALSE); - errorLog(modulo,err,FALSE); - return (FALSE); - } - strcpy(idordenador,copiaParametro("ido",ptrTrama)); // Identificador del ordenador - strcpy(nombreordenador,copiaParametro("npc",ptrTrama)); // Nombre del ordenador - - if(idordenador==NULL || nombreordenador==NULL){ - errorLog(modulo,40,FALSE); - return (FALSE); - } - return(TRUE); -} -//______________________________________________________________________________________________________ -// Funcin: ProcesaComandos -// -// Descripcin: -// Espera comando desde el Servidor de Administracin para ejecutarlos -// Parmetros: -// Ninguno -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -// ________________________________________________________________________________________________________ -void procesaComandos(TRAMA* ptrTrama) -{ - int lon; - SOCKET socket_c; - char modulo[] = "procesaComandos()"; - - initParametros(ptrTrama,0); - while(TRUE){ - lon=sprintf(ptrTrama->parametros,"nfn=DisponibilidadComandos\r"); - lon+=sprintf(ptrTrama->parametros+lon,"tpc=%s\r",CLIENTE_WIN); // Activar disponibilidad - if(!enviaMensajeServidor(&socket_c,ptrTrama,MSG_INFORMACION)){ - errorLog(modulo,43,FALSE); - return; - } - infoLog(19); // Disponibilidad de cliente activada - ptrTrama=recibeMensaje(&socket_c); - if(!ptrTrama){ - errorLog(modulo,46,FALSE); - return; - } - - closesocket(socket_c); - - if(!gestionaTrama(ptrTrama)){ // Anlisis de la trama - errorLog(modulo,39,FALSE); - return; - } - } -} -//_____________________________________________________________________________________________________ -// Funcin: Apagar -// -// Descripcin: -// Apaga el cliente -// Parmetros: -// ptrTrama: contenido del mensaje -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -//_____________________________________________________________________________________________________ -BOOLEAN Apagar(TRAMA* ptrTrama) -{ - int lon; - char *ids,msglog[LONSTD]; - char modulo[] = "Apagar()"; - - if (ndebug>=DEBUG_MAXIMO) { - sprintf(msglog, "%s:%s",tbMensajes[21],modulo); - infoDebug(msglog); - } - ids=copiaParametro("ids",ptrTrama); - - initParametros(ptrTrama,0); - lon=sprintf(ptrTrama->parametros,"nfn=%s\r","RESPUESTA_Apagar"); - respuestaEjecucionComando(ptrTrama,0,ids); - - if(versionWin<5) - ApagarReiniciar(EWX_POWEROFF | EWX_FORCE,ids,0); - else - ApagarReiniciar(EWX_SHUTDOWN | EWX_FORCE,ids,0); - return(TRUE); -} -//_____________________________________________________________________________________________________ -// Funcin: Reiniciar -// -// Descripcin: -// Apaga el cliente -// Parmetros: -// ptrTrama: contenido del mensaje -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn errorservidoradm -//_____________________________________________________________________________________________________ -BOOLEAN Reiniciar(TRAMA* ptrTrama) -{ - int lon; - char *ids,msglog[LONSTD]; - char modulo[] = "Reiniciar()"; - - if (ndebug>=DEBUG_MAXIMO) { - sprintf(msglog, "%s:%s",tbMensajes[21],modulo); - infoDebug(msglog); - } - ids=copiaParametro("ids",ptrTrama); - - initParametros(ptrTrama,0); - lon=sprintf(ptrTrama->parametros,"nfn=%s\r","RESPUESTA_Reiniciar"); - respuestaEjecucionComando(ptrTrama,0,ids); - - if(versionWin<5) - ApagarReiniciar(EWX_REBOOT | EWX_FORCE,ids,1); - else - ApagarReiniciar(EWX_REBOOT | EWX_FORCE,ids,1); - - return(TRUE); -} -// _____________________________________________________________________________________________________________ -// -// Funcin: ApagarReiniciar -// -// Descripcin: -// Apaga o reinicia el ordenador o bien hace logout del usuario -// -// Parmetros: -// - uFlags : Especifica el tipo de shutdown -// _____________________________________________________________________________________________________________ -BOOLEAN ApagarReiniciar(UINT uFlags,char *ids,int sw) -{ - HANDLE hToken; - TOKEN_PRIVILEGES tkp; - char modulo[] = "Reiniciar()"; - - if (versionWin>4){ - if (!ExitWindowsEx(uFlags, 0)) { - errorLog(modulo,86,FALSE); - return(FALSE); - } - return TRUE; - } - // Get a token for this process. - if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { - errorLog(modulo,86,FALSE); - return(FALSE); - } - - // Get the LUID for the shutdown privilege. - LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid); - - tkp.PrivilegeCount = 1; // one privilege to set - tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - - // Get the shutdown privilege for this process. - AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); - - if (GetLastError() != ERROR_SUCCESS) { - errorLog(modulo,86,FALSE); - return(FALSE); - } - - // Shut down the system and force all applications to close. - if (!ExitWindowsEx(uFlags, 0)) { - errorLog(modulo,86,FALSE); - return(FALSE); - } - - return TRUE; -} -// _____________________________________________________________________________________________________________ -// -// Funcin: TomaVersionWindows -// -// Descripcin: -// Toma la versin del sistema operativo -// -// Valores de retorno: -// 1.- Microsoft Windows Server 2003 -// 2.- Microsoft Windows XP -// 3.- Microsoft Windows 2000 -// 4.- Microsoft Windows NT -// 5.- Microsoft Windows 95 -// 6.- Microsoft Windows 98 -// 7.- Microsoft Windows Millennium Edition -// _____________________________________________________________________________________________________________ -int TomaVersionWindows() -{ - OSVERSIONINFOEX osvi; - BOOL bOsVersionInfoEx; - - // Intenta tomar la version usando la estructura OSVERSIONINFOEX - // Si falla lo intentausando la estructura OSVERSIONINFO. - - ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - - if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ){ - osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); - if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) - return -1; - } - switch (osvi.dwPlatformId){ - // Test for the Windows NT product family. - case VER_PLATFORM_WIN32_NT: - if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 ) - return(1); // Microsoft Windows Server 2003 - if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 ) - return(2); // Microsoft Windows XP - if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 ) - return(3); // Microsoft Windows 2000 - if ( osvi.dwMajorVersion <= 4 ) - return(4); // Microsoft Windows NT - break; - - // Test for the Windows Me/98/95. - case VER_PLATFORM_WIN32_WINDOWS: - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) - return(5); // Microsoft Windows 95 - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) - return(6); // Microsoft Windows 98 - if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) - return(7); // Microsoft Windows Millennium Edition - break; - } - return -1; -} -//______________________________________________________________________________________________________ -// Funcin: Sondeo -// -// Descripcin: -// Enva al servidor una confirmacin de que est dentro del sistema -// Parmetros: -// ptrTrama: contenido del mensajede -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -//______________________________________________________________________________________________________ -BOOLEAN Sondeo(TRAMA* ptrTrama) -{ - return(TRUE); -} -//______________________________________________________________________________________________________ -// Funcin: Actualizar -// -// Descripcin: -// Enva al servidor una confirmacin de que est dentro del sistema -// Parmetros: -// ptrTrama: contenido del mensajede -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -//______________________________________________________________________________________________________ -BOOLEAN Actualizar(TRAMA* ptrTrama) -{ - return(TRUE); -} -//______________________________________________________________________________________________________ -// Funcin: respuestaEjecucionComando -// -// Descripcin: -// Envia una respuesta a una ejecucion de comando al servidor de Administracin -// Parmetros: -// - ptrTrama: contenido del mensaje -// - res: Resultado de la ejecucin (Cdigo de error devuelto por el script ejecutado) -// - ids: Identificador de la sesion (En caso de no haber seguimiento es NULO) -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -// ________________________________________________________________________________________________________ -BOOLEAN respuestaEjecucionComando(TRAMA* ptrTrama,int res,char *ids) -{ - int lon; - SOCKET socket_c; - char modulo[] = "respuestaEjecucionComando()"; - - lon=strlen(ptrTrama->parametros); - if(ids){ // Existe seguimiento - lon+=sprintf(ptrTrama->parametros+lon,"ids=%s\r",ids); // Aade identificador de la sesin - } - if (res==0){ // Resultado satisfactorio - lon+=sprintf(ptrTrama->parametros+lon,"res=%s\r","1"); - lon+=sprintf(ptrTrama->parametros+lon,"der=%s\r",""); - } - else{ // Algn error - lon+=sprintf(ptrTrama->parametros+lon,"res=%s\r","2"); - lon+=sprintf(ptrTrama->parametros+lon,"der=%s\r",tbErrores[res]);// Descripcin del error - } - if(!(enviaMensajeServidor(&socket_c,ptrTrama,MSG_NOTIFICACION))){ - errorLog(modulo,44,FALSE); - return(FALSE); - } - closesocket(socket_c); - return(TRUE); -} -// ________________________________________________________________________________________________________ -// Funcin: gestionaTrama -// -// Descripcin: -// Procesa las tramas recibidas.servidoradm -// Parametros: -// ptrTrama: contenido del mensaje -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -// ________________________________________________________________________________________________________ -BOOLEAN gestionaTrama(TRAMA *ptrTrama) -{ - int i, res; - char *nfn; - char modulo[] = "gestionaTrama()"; - - INTROaFINCAD(ptrTrama); - nfn = copiaParametro("nfn", ptrTrama); // Toma nombre de funcin - for (i = 0; i < MAXIMAS_FUNCIONES; i++) { // Recorre funciones que procesan las tramas - res = strcmp(tbfuncionesClient[i].nf, nfn); - if (res == 0) { // Encontrada la funcin que procesa el mensaje - return(tbfuncionesClient[i].fptr(ptrTrama)); // Invoca la funcin - } - } - errorLog(modulo, 18, FALSE); - return (FALSE); -} -//______________________________________________________________________________________________________ -// Funcin: enviaMensajeServidor -// -// Descripcin: -// Envia un mensaje al servidor de Administracin -// Parmetros: -// - socket_c: (Salida) Socket utilizado para el envo -// - ptrTrama: contenido del mensaje -// - tipo: Tipo de mensaje -// C=Comando, N=Respuesta a un comando, P=Peticion,R=Respuesta a una peticin, I=Informacion -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -// ________________________________________________________________________________________________________ -BOOLEAN enviaMensajeServidor(SOCKET *socket_c,TRAMA *ptrTrama,char tipo) -{ - int lon; - char modulo[] = "enviaMensajeServidor()"; - - *socket_c=abreConexion(); - if(*socket_c==INVALID_SOCKET){ - errorLog(modulo,38,FALSE); // Error de conexin con el servidor - return(FALSE); - } - ptrTrama->arroba='@'; // Cabecera de la trama - strncpy(ptrTrama->identificador,"JMMLCAMDJ_MCDJ",14); // identificador de la trama - ptrTrama->tipo=tipo; // Tipo de mensaje - lon=strlen(ptrTrama->parametros); // Compone la trama - lon+=sprintf(ptrTrama->parametros+lon,"iph=%s\r",IPlocal); // Ip del ordenador - lon+=sprintf(ptrTrama->parametros+lon,"ido=%s\r",idordenador); // Identificador del ordenador - lon+=sprintf(ptrTrama->parametros+lon,"npc=%s\r",nombreordenador); // Nombre del ordenador - - if (!mandaTrama(socket_c,ptrTrama)) { - errorLog(modulo,26,FALSE); - return (FALSE); - } - return(TRUE); -} -// _____________________________________________________________________________________________________________ -// Funcin: TomaParametrosReg -// -// Descripcin: -// Toma los parmetros de conexin del registro -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -// _____________________________________________________________________________________________________________ -BOOLEAN TomaParametrosReg() -{ - if(!ReadRegistryString(HIVE,BASE,"servidoradm",servidoradm,20)) - return(FALSE); - - if(!ReadRegistryString(HIVE,BASE,"puerto",puerto,20)) - return(FALSE); - - if(!ReadRegistryString(HIVE,BASE,"Iplocal",IPlocal,20)) - return(FALSE); - - return(TRUE); -} -//______________________________________________________________________________________________________ -// Funcin: TomaIP -// -// Descripcin: -// Recupera la ip de la mquina -// Parmetros: -// Ninguno -// Devuelve: -// TRUE: Si el proceso es correcto -// FALSE: En caso de ocurrir algn error -// ________________________________________________________________________________________________________ -BOOLEAN TomaIP(char* ip) -{ - char ac[80]; - struct in_addr addr; - BOOLEAN ipv; - - if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) { - return (FALSE); - } - struct hostent *phe = gethostbyname(ac); - if (phe == 0) { - return (FALSE); - } - ipv=FALSE; - for (int i = 0; phe->h_addr_list[i] != 0 && !ipv; ++i) { - memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); - strcpy(ip,inet_ntoa(addr)); - if(strcmp(IPlocal,"127.0.0.1")==0) - ipv=FALSE; - else{ - ipv=true; // IP vlida distinta a loop - break; - } - } - - return(ipv); -} -// ******************************************************************************************************** -// PROGRAMA PRINCIPAL (CLIENTE) -// ******************************************************************************************************** -//int main(int argc, char *argv[]) -VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv) - { - //___________________________________________________________ - // - // Service initialization (Report the status to the service control manager) - //___________________________________________________________ - // - if (!ReportStatusToSCMgr( - SERVICE_START_PENDING, // service state - NO_ERROR, // exit code - 3000)) // wait hint - return; - //__________________________________________ - - TRAMA *ptrTrama; - char modulo[] = "main()"; - - strcpy(szPathFileLog, "ogAdmWinClient.log"); // de configuracin y de logs - - - WSADATA wsd; - if (WSAStartup(MAKEWORD(2,2),&wsd)!=0){ // Carga librera Winsock - errorLog(modulo, 93, FALSE); - exit(EXIT_FAILURE); - } - - ptrTrama=(TRAMA *)reservaMemoria(sizeof(TRAMA)); - if (ptrTrama == NULL) { // No hay memoria suficiente para el bufer de las tramas - errorLog(modulo, 3, FALSE); - exit(EXIT_FAILURE); - } - /*-------------------------------------------------------------------------------------------------------- - Validacin de parmetros de ejecucin y fichero de configuracin - ---------------------------------------------------------------------------------------------------------*/ - if(!TomaParametrosReg()) // Toma parametros de configuracion - exit(EXIT_FAILURE); - - //___________________________________________________________ - // - // Service initialization (Report the status to the service control manager) - //___________________________________________________________ - // - if (!ReportStatusToSCMgr( - SERVICE_START_PENDING, // service state - NO_ERROR, // exit code - 3000)) // wait hint - return; - //__________________________________________ - // - // Toma IP local - //___________________________________________ - // - // Toma la ip tambin del registro - /*if(!TomaIP(IPlocal)){ - errorLog(modulo,85,FALSE); - exit(EXIT_FAILURE); - } - */ - versionWin=TomaVersionWindows(); // Toma versin de windows - - /*-------------------------------------------------------------------------------------------------------- - Carga catlogo de funciones que procesan las tramas - ---------------------------------------------------------------------------------------------------------*/ - int cf = 0; - - strcpy(tbfuncionesClient[cf].nf, "RESPUESTA_InclusionClienteWinLnx"); - tbfuncionesClient[cf++].fptr = &RESPUESTA_InclusionClienteWinLnx; - - strcpy(tbfuncionesClient[cf].nf, "Apagar"); - tbfuncionesClient[cf++].fptr = &Apagar; - - strcpy(tbfuncionesClient[cf].nf, "Reiniciar"); - tbfuncionesClient[cf++].fptr = &Reiniciar; - - strcpy(tbfuncionesClient[cf].nf, "Sondeo"); - tbfuncionesClient[cf++].fptr = &Sondeo; - - strcpy(tbfuncionesClient[cf].nf, "Actualizar"); - tbfuncionesClient[cf++].fptr = &Actualizar; - - /*-------------------------------------------------------------------------------------------------------- - Inicio de sesin - ---------------------------------------------------------------------------------------------------------*/ - infoLog(1); // Inicio de sesin - infoLog(3); // Abriendo sesin en el servidor de Administracin; - /*-------------------------------------------------------------------------------------------------------- - Inclusin del cliente en el sistema - ---------------------------------------------------------------------------------------------------------*/ - if(!InclusionClienteWinLnx(ptrTrama)){ // Ha habido algn problema al abrir sesin - errorLog(modulo,0,FALSE); - exit(EXIT_FAILURE); - } - infoLog(4); // Cliente iniciado - - //__________________________________________ - // El servicio est instalado y debe ser iniciado - // -- report the status to the service control manager.-- - // - if (!ReportStatusToSCMgr( - SERVICE_RUNNING, // service state - NO_ERROR, // exit code - 0)) // wait hint - return; - // End of initialization - //__________________________________________ - - // - // Service is now running, perform work until shutdown - // - while (ssStatus.dwCurrentState == SERVICE_RUNNING) { // Bucle para escuchar peticiones de clientes - procesaComandos(ptrTrama); // Bucle para procesar comandos interactivos - } - WSACleanup(); - // El servicio de detiene -} -/* _____________________________________________________________________________________________________________ - FUNCTION: ServiceStop - - PURPOSE: Stops the service - PARAMETERS: - none - - RETURN VALUE: - none - - COMMENTS: - - If a ServiceStop procedure is going to - take longer than 3 seconds to execute, - it should spawn a thread to execute the - stop code, and return. Otherwise, the - ServiceControlManager will believe that - the service has stopped responding. - _____________________________________________________________________________________________________________*/ -VOID ServiceStop() -{ - // Incluir aqu el cdigo necesario antes de parar el servicio - ReportStatusToSCMgr(SERVICE_STOPPED, NO_ERROR, 0); -} \ No newline at end of file diff --git a/admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.h b/admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.h deleted file mode 100644 index 55e33ad8..00000000 --- a/admin/Sources/Clients/ogAdmWinClient/sources/ogAdmWinClient.h +++ /dev/null @@ -1,60 +0,0 @@ -// ******************************************************************************************************** -// Cliente: ogAdmWinClient -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Febrero-2012 -// Fecha Última modificación: Febrero-2012 -// Nombre del fichero: ogAdmWinClient.h -// Descripción :Este fichero implementa el cliente general del sistema -// ******************************************************************************************************** -#define __WINDOWS__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "registrow.h" -#include "ogAdmLib.h" -#include "servicio.h" -// ________________________________________________________________________________________________________ -// Variables globales -// ________________________________________________________________________________________________________ -// -int versionWin; -char idordenador[LONPRM]; // Identificador del ordenador -char nombreordenador[LONPRM]; // Nombre del ordenador - -char servidoradm[LONPRM]; // Dirección IP del servidor de administración -char puerto[LONPRM]; // Puerto de comunicación -char IPlocal[LONPRM]; // Ip local por donde se van a enviar las comunicaciones - - -typedef struct{ // Estructura usada para referenciar las funciones que procesan las tramas - char nf[LONFUN]; // Nombre de la función - BOOLEAN (*fptr)(TRAMA*); // Puntero a la función que procesa la trama -}MSGFUN; -MSGFUN tbfuncionesClient[MAXIMAS_FUNCIONES]; -// ________________________________________________________________________________________________________ -// Prototipo de funciones -// ________________________________________________________________________________________________________ - -void procesaComandos(TRAMA*); -BOOLEAN gestionaTrama(TRAMA *); -BOOLEAN InclusionClienteWinLnx(); -BOOLEAN RESPUESTA_InclusionClienteWinLnx(TRAMA *); -BOOLEAN respuestaEjecucionComando(TRAMA *,int,char*); - -BOOLEAN Apagar(TRAMA *); -BOOLEAN Reiniciar(TRAMA *); -BOOLEAN Sondeo(TRAMA *); - -BOOLEAN enviaMensajeServidor(SOCKET *,TRAMA *,char); -BOOLEAN ApagarReiniciar(UINT,char *,int sw); - -SOCKADDR_IN *GetIPInterfaceList(SOCKET , int *); \ No newline at end of file diff --git a/admin/Sources/Clients/ogAdmWinClient/sources/servicio.c b/admin/Sources/Clients/ogAdmWinClient/sources/servicio.c deleted file mode 100644 index 773ac883..00000000 --- a/admin/Sources/Clients/ogAdmWinClient/sources/servicio.c +++ /dev/null @@ -1,628 +0,0 @@ -// ****************************************************************************************************************************************************************************** -// Aplicacin HIDRA -// Copyright 2003-2005 Jos Manuel Alonso. Todos los derechos reservados. -// Fichero: servicio.c -// Descripcin: -// Este proyecto implementa el servicio hidra en un ordenador con plataforma windows NT. Este fichero aporta las funciones para crear el servicio -// ****************************************************************************************************************************************************************************** -//____________________________________________________________________________________________________________________________ -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (C) 1993-1997 Microsoft Corporation. All Rights Reserved. -// -// MODULE: service.c -// PURPOSE: Implements functions required by all services windows. -// -// FUNCTIONS: -// main(int argc, char **argv); -// service_ctrl(DWORD dwCtrlCode); -// service_main(DWORD dwArgc, LPTSTR *lpszArgv); -// CmdInstallService(); -// CmdRemoveService(); -// CmdDebugService(int argc, char **argv); -// ControlHandler ( DWORD dwCtrlType ); -// GetLastErrorText( LPTSTR lpszBuf, DWORD dwSize ); -// -// COMMENTS: -// AUTHOR: Craig Link - Microsoft Developer Support -//____________________________________________________________________________________________________________________________ -#include "servicio.h" -//____________________________________________________________________________________________________________________________ -// internal variables -DWORD dwErr = 0; -BOOL bDebug = FALSE; -TCHAR szErr[256]; - -// internal function prototypes -VOID WINAPI service_ctrl(DWORD dwCtrlCode); -VOID WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv); -VOID CmdInstallService(); -VOID CmdRemoveService(); -VOID CmdDebugService(int argc, char **argv); -BOOL WINAPI ControlHandler ( DWORD dwCtrlType ); -LPTSTR GetLastErrorText( LPTSTR lpszBuf, DWORD dwSize ); -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: tomarestoparametros -// -// Descripcin: -// -// Toma los parametros de conexin de la linea de comando y los graba en el Registro -//____________________________________________________________________________________________________________________________ -int tomarestoparametros(int argc, char **argv) -{ - int i,lon; - char servidorhidra[20]; - char puerto[10]; - char iplocal[20]; - - strcpy(servidorhidra,SERVIDOR_DEFAULT); - strcpy(puerto,PUERTO_DEFAULT); - strcpy(iplocal,IPLOCAL_DEFAULT); - - for(i=2;i 1) && - ((*argv[1] == '-') || (*argv[1] == '/')) ) - { - if ( _stricmp( "install", argv[1]+1 ) == 0 ) - { - if (!tomarestoparametros(argc,argv)) - exit(1); - CmdInstallService(); - } - else if ( _stricmp( "remove", argv[1]+1 ) == 0 ) - { - borraparametros(); - CmdRemoveService(); - } - else if ( _stricmp( "debug", argv[1]+1 ) == 0 ) - { - bDebug = TRUE; - CmdDebugService(argc, argv); - } - else - { - goto dispatch; - } - exit(0); - } - // if it doesn't match any of the above parameters - // the service control manager may be starting the service - // so we must call StartServiceCtrlDispatcher - dispatch: - // this is just to be friendly - printf( "%s -install to install the service\n", SZAPPNAME ); - printf( "%s -remove to remove the service\n", SZAPPNAME ); - printf( "%s -debug to run as a console app for debugging\n", SZAPPNAME ); - printf( "\nStartServiceCtrlDispatcher being called.\n" ); - printf( "This may take several seconds. Please wait.\n" ); - - if (!StartServiceCtrlDispatcher(dispatchTable)) - AddToMessageLog(TEXT("StartServiceCtrlDispatcher failed.")); -} -//____________________________________________________________________________________________________________________________ -// FUNCTION: service_main -// -// PURPOSE: To perform actual initialization of the service -// -// PARAMETERS: -// dwArgc - number of command line arguments -// lpszArgv - array of command line arguments -// -// RETURN VALUE: -// none -// -// COMMENTS: -// This routine performs the service initialization and then calls -// the user defined ServiceStart() routine to perform majority -// of the work. -// -//____________________________________________________________________________________________________________________________ -void WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv) -{ - // register our service control handler: - // - sshStatusHandle = RegisterServiceCtrlHandler( TEXT(SZSERVICENAME), service_ctrl); - - if (!sshStatusHandle) - goto cleanup; - - // SERVICE_STATUS members that don't change in example - // - ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; - ssStatus.dwServiceSpecificExitCode = 0; - - - // report the status to the service control manager. - // - if (!ReportStatusToSCMgr( - SERVICE_START_PENDING, // service state - NO_ERROR, // exit code - 3000)) // wait hint - goto cleanup; - - ServiceStart( dwArgc, lpszArgv ); - -cleanup: - - // try to report the stopped status to the service control manager. - // - if (sshStatusHandle) - (VOID)ReportStatusToSCMgr( - SERVICE_STOPPED, - dwErr, - 0); - return; -} -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: service_ctrl -// -// PURPOSE: This function is called by the SCM whenever -// ControlService() is called on this service. -// -// PARAMETERS: -// dwCtrlCode - type of control requested -// -// RETURN VALUE: -// none -// -// COMMENTS: -// -//____________________________________________________________________________________________________________________________ -VOID WINAPI service_ctrl(DWORD dwCtrlCode) -{ - // Handle the requested control code. - // - switch(dwCtrlCode) - { - // Stop the service. - // - // SERVICE_STOP_PENDING should be reported before - // setting the Stop Event - hServerStopEvent - in - // ServiceStop(). This avoids a race condition - // which may result in a 1053 - The Service did not respond... - // error. - case SERVICE_CONTROL_STOP: - ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 0); - ServiceStop(); - return; - - // Update the service status. - // - case SERVICE_CONTROL_INTERROGATE: - break; - - // invalid control code - // - default: - break; - - } - ReportStatusToSCMgr(ssStatus.dwCurrentState, NO_ERROR, 0); -} -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: ReportStatusToSCMgr() -// -// PURPOSE: Sets the current status of the service and -// reports it to the Service Control Manager -// -// PARAMETERS: -// dwCurrentState - the state of the service -// dwWin32ExitCode - error code to report -// dwWaitHint - worst case estimate to next checkpoint -// -// RETURN VALUE: -// TRUE - success -// FALSE - failure -// -// COMMENTS: -// -//____________________________________________________________________________________________________________________________ -BOOL ReportStatusToSCMgr(DWORD dwCurrentState,DWORD dwWin32ExitCode,DWORD dwWaitHint) -{ - static DWORD dwCheckPoint = 1; - BOOL fResult = TRUE; - - - if ( !bDebug ) // when debugging we don't report to the SCM - { - if (dwCurrentState == SERVICE_START_PENDING) - ssStatus.dwControlsAccepted = 0; - else - ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; - - ssStatus.dwCurrentState = dwCurrentState; - ssStatus.dwWin32ExitCode = dwWin32ExitCode; - ssStatus.dwWaitHint = dwWaitHint; - - if ( ( dwCurrentState == SERVICE_RUNNING ) || - ( dwCurrentState == SERVICE_STOPPED ) ) - ssStatus.dwCheckPoint = 0; - else - ssStatus.dwCheckPoint = dwCheckPoint++; - - // Report the status of the service to the service control manager. - // - if (!(fResult = SetServiceStatus( sshStatusHandle, &ssStatus))) { - AddToMessageLog(TEXT("SetServiceStatus")); - } - } - return fResult; -} -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: AddToMessageLog(LPTSTR lpszMsg) -// -// PURPOSE: Allows any thread to log an error message -// -// PARAMETERS: -// lpszMsg - text for message -// -// RETURN VALUE: -// none -// -// COMMENTS: -// -//____________________________________________________________________________________________________________________________ -VOID AddToMessageLog(LPTSTR lpszMsg) -{ - TCHAR szMsg[256]; - HANDLE hEventSource; - LPTSTR lpszStrings[2]; - - if ( !bDebug ) - { - dwErr = GetLastError(); - - // Use event logging to log the error. - // - hEventSource = RegisterEventSource(NULL, TEXT(SZSERVICENAME)); - - _stprintf(szMsg, TEXT("%s error: %d"), TEXT(SZSERVICENAME), dwErr); - lpszStrings[0] = szMsg; - lpszStrings[1] = lpszMsg; - - if (hEventSource != NULL) { - ReportEvent(hEventSource, // handle of event source - EVENTLOG_ERROR_TYPE, // event type - 0, // event category - 0, // event ID - NULL, // current user's SID - 2, // strings in lpszStrings - 0, // no bytes of raw data - lpszStrings, // array of error strings - NULL); // no raw data - - (VOID) DeregisterEventSource(hEventSource); - } - } -} -//____________________________________________________________________________________________________________________________ -// -// The following code handles service installation and removal -// -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: CmdInstallService() -// -// PURPOSE: Installs the service -// PARAMETERS: -// none -// -// RETURN VALUE: -// none -// -// COMMENTS: -//____________________________________________________________________________________________________________________________ -void CmdInstallService() -{ - SC_HANDLE schService; - SC_HANDLE schSCManager; - - TCHAR szPath[512]; - - if ( GetModuleFileName( NULL, szPath, 512 ) == 0 ) - { - _tprintf(TEXT("Unable to install %s - %s\n"), TEXT(SZSERVICEDISPLAYNAME), GetLastErrorText(szErr, 256)); - return; - } - schSCManager = OpenSCManager( - NULL, // machine (NULL == local) - NULL, // database (NULL == default) - SC_MANAGER_ALL_ACCESS // access required - ); - if ( schSCManager ) - { - schService = CreateService( - schSCManager, // SCManager database - TEXT(SZSERVICENAME), // name of service - TEXT(SZSERVICEDISPLAYNAME), // name to display - SERVICE_ALL_ACCESS, // desired access - SERVICE_WIN32_OWN_PROCESS, // service type - SERVICE_AUTO_START, // start type - SERVICE_ERROR_NORMAL, // error control type - szPath, // service's binary - NULL, // no load ordering group - NULL, // no tag identifier - TEXT(SZDEPENDENCIES), // dependencies - NULL, // LocalSystem account - NULL); // no password - - if ( schService ) - { - _tprintf(TEXT("%s installed.\n"), TEXT(SZSERVICEDISPLAYNAME) ); - CloseServiceHandle(schService); - } - else - { - _tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256)); - } - - CloseServiceHandle(schSCManager); - } - else - _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256)); -} -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: CmdRemoveService() -// -// PURPOSE: Stops and removes the service -// -// PARAMETERS: -// none -// -// RETURN VALUE: -// none -// -// COMMENTS: -// -//____________________________________________________________________________________________________________________________ -void CmdRemoveService() -{ - SC_HANDLE schService; - SC_HANDLE schSCManager; - - schSCManager = OpenSCManager( - NULL, // machine (NULL == local) - NULL, // database (NULL == default) - SC_MANAGER_ALL_ACCESS // access required - ); - if ( schSCManager ) - { - schService = OpenService(schSCManager, TEXT(SZSERVICENAME), SERVICE_ALL_ACCESS); - - if (schService) - { - // try to stop the service - if ( ControlService( schService, SERVICE_CONTROL_STOP, &ssStatus ) ) - { - _tprintf(TEXT("Stopping %s."), TEXT(SZSERVICEDISPLAYNAME)); - Sleep( 1000 ); - - while( QueryServiceStatus( schService, &ssStatus ) ) - { - if ( ssStatus.dwCurrentState == SERVICE_STOP_PENDING ) - { - _tprintf(TEXT(".")); - Sleep( 1000 ); - } - else - break; - } - - if ( ssStatus.dwCurrentState == SERVICE_STOPPED ) - _tprintf(TEXT("\n%s stopped.\n"), TEXT(SZSERVICEDISPLAYNAME) ); - else - _tprintf(TEXT("\n%s failed to stop.\n"), TEXT(SZSERVICEDISPLAYNAME) ); - - } - - // now remove the service - if( DeleteService(schService) ) - _tprintf(TEXT("%s removed.\n"), TEXT(SZSERVICEDISPLAYNAME) ); - else - _tprintf(TEXT("DeleteService failed - %s\n"), GetLastErrorText(szErr,256)); - - - CloseServiceHandle(schService); - } - else - _tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr,256)); - - CloseServiceHandle(schSCManager); - } - else - _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr,256)); -} -//____________________________________________________________________________________________________________________________ -// -// The following code is for running the service as a console app -// -// -// FUNCTION: CmdDebugService(int argc, char ** argv) -// -// PURPOSE: Runs the service as a console application -// -// PARAMETERS: -// argc - number of command line arguments -// argv - array of command line arguments -// -// RETURN VALUE: -// none -// -// COMMENTS: -// -//____________________________________________________________________________________________________________________________ -void CmdDebugService(int argc, char ** argv) -{ - DWORD dwArgc; - LPTSTR *lpszArgv; - -#ifdef UNICODE - lpszArgv = CommandLineToArgvW(GetCommandLineW(), &(dwArgc) ); -#else - dwArgc = (DWORD) argc; - lpszArgv = argv; -#endif - - _tprintf(TEXT("Debugging %s.\n"), TEXT(SZSERVICEDISPLAYNAME)); - - SetConsoleCtrlHandler( ControlHandler, TRUE ); - - ServiceStart( dwArgc, lpszArgv ); -} -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: ControlHandler ( DWORD dwCtrlType ) -// -// PURPOSE: Handled console control events -// -// PARAMETERS: -// dwCtrlType - type of control event -// -// RETURN VALUE: -// True - handled -// False - unhandled -// -// COMMENTS: -// -//____________________________________________________________________________________________________________________________ -BOOL WINAPI ControlHandler ( DWORD dwCtrlType ) -{ - switch( dwCtrlType ) - { - case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate - case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode - _tprintf(TEXT("Stopping %s.\n"), TEXT(SZSERVICEDISPLAYNAME)); - ServiceStop(); - return TRUE; - break; - - } - return FALSE; -} -//____________________________________________________________________________________________________________________________ -// -// FUNCTION: GetLastErrorText -// -// PURPOSE: copies error message text to string -// -// PARAMETERS: -// lpszBuf - destination buffer -// dwSize - size of buffer -// -// RETURN VALUE: -// destination buffer -// -// COMMENTS: -// -//____________________________________________________________________________________________________________________________ -LPTSTR GetLastErrorText( LPTSTR lpszBuf, DWORD dwSize ) -{ - DWORD dwRet; - LPTSTR lpszTemp = NULL; - - dwRet = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ARGUMENT_ARRAY, - NULL, - GetLastError(), - LANG_NEUTRAL, - (LPTSTR)&lpszTemp, - 0, - NULL ); - - // supplied buffer is not long enough - if ( !dwRet || ( (long)dwSize < (long)dwRet+14 ) ) - lpszBuf[0] = TEXT('\0'); - else - { - lpszTemp[lstrlen(lpszTemp)-2] = TEXT('\0'); //remove cr and newline character - _stprintf( lpszBuf, TEXT("%s (0x%x)"), lpszTemp, GetLastError() ); - } - - if ( lpszTemp ) - LocalFree((HLOCAL) lpszTemp ); - - return lpszBuf; -} diff --git a/admin/Sources/Clients/ogAdmWinClient/sources/servicio.h b/admin/Sources/Clients/ogAdmWinClient/sources/servicio.h deleted file mode 100644 index 760d2c1a..00000000 --- a/admin/Sources/Clients/ogAdmWinClient/sources/servicio.h +++ /dev/null @@ -1,153 +0,0 @@ -// ****************************************************************************************************************************************************************************** -// Aplicacin HIDRA -// Copyright 2003-2005 Jos Manuel Alonso. Todos los derechos reservados. -// Fichero: servicio.h -// Descripcin: -// Este proyecto implementa el servicio hidra en un ordenador con plataforma windows NT. Este fichero aporta las funciones para crear el servicio -// ****************************************************************************************************************************************************************************** -//____________________________________________________________________________________________________________________________ -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (C) 1993-1997 Microsoft Corporation. All Rights Reserved. -// -// MODULE: service.h -// AUTHOR: Craig Link -// -// Comments: The use of this header file and the accompanying service.c -// file simplifies the process of writting a service. You as a developer -// simply need to follow the TODO's outlined in this header file, and -// implement the ServiceStart() and ServiceStop() functions. -// -// There is no need to modify the code in service.c. Just add service.c -// to your project and link with the following libraries... -// -// libcmt.lib kernel32.lib advapi.lib shell32.lib -// -// This code also supports unicode. Be sure to compile both service.c and -// and code #include "service.h" with the same Unicode setting. -// -// Upon completion, your code will have the following command line interface -// -// -? to display this list -// -install to install the service -// -remove to remove the service -// -debug to run as a console app for debugging -// -// Note: This code also implements Ctrl+C and Ctrl+Break handlers -// when using the debug option. These console events cause -// your ServiceStop routine to be called -// -// Also, this code only handles the OWN_SERVICE service type -// running in the LOCAL_SYSTEM security context. -// -// To control your service ( start, stop, etc ) you may use the -// Services control panel applet or the NET.EXE program. -// -// To aid in writing/debugging service, the -// SDK contains a utility (MSTOOLS\BIN\SC.EXE) that -// can be used to control, configure, or obtain service status. -// SC displays complete status for any service/driver -// in the service database, and allows any of the configuration -// parameters to be easily changed at the command line. -// For more information on SC.EXE, type SC at the command line. -// -//____________________________________________________________________________________________________________________________ -#include -#include -#include -#include -#include -#include "registrow.h" - -#ifndef _SERVICE_H -#define _SERVICE_H - -#ifdef __cplusplus -extern "C" { -#endif - -// name of the executable -#define SZAPPNAME "ogAdmWinClient" -// internal name of the service -#define SZSERVICENAME "Cliente Opengnsys" -// displayed name of the service -#define SZSERVICEDISPLAYNAME "Cliente Opengnsys" -// list of service dependencies - "dep1\0dep2\0\0" -#define SZDEPENDENCIES "" - -#define SERVIDOR_DEFAULT "0.0.0.0" -#define PUERTO_DEFAULT "2003" -#define IPLOCAL_DEFAULT "0.0.0.0" - -#define CHKREGISTRY(f) if (!(f)) { return 0;} -#define RMVREGISTRY(f) if (!(f)) { return 0;} -#define TOMAPARAMINT(p) p=atoi(&argv[i][3]); -#define TOMAPARAMSTR(p) strcpy(p,&argv[i][3]); - -#define HIVE HKEY_LOCAL_MACHINE // Rama del registro donde estarn los parametros de conexin -#define BASEKEY "SOFTWARE\\opengnsys" // Key del registro para parametros de conexin -#define BASE "SOFTWARE\\opengnsys\\cliente" // SubKey del registro para parametros de conexin - -//____________________________________________________________________________________________________________________________ -// -SERVICE_STATUS ssStatus; // current status of the service -SERVICE_STATUS_HANDLE sshStatusHandle; -// -//____________________________________________________________________________________________________________________________ -// ServiceStart()must be defined by in your code. -// The service should use ReportStatusToSCMgr to indicate -// progress. This routine must also be used by StartService() -// to report to the SCM when the service is running. -// -// If a ServiceStop procedure is going to take longer than -// 3 seconds to execute, it should spawn a thread to -// execute the stop code, and return. Otherwise, the -// ServiceControlManager will believe that the service has -// stopped responding -// -//____________________________________________________________________________________________________________________________ -VOID ServiceStart(DWORD dwArgc, LPTSTR *lpszArgv); -VOID ServiceStop(); -//____________________________________________________________________________________________________________________________ -// The following are procedures which -// may be useful to call within the above procedures, -// but require no implementation by the user. -// They are implemented in service.c -// -// FUNCTION: ReportStatusToSCMgr() -// -// PURPOSE: Sets the current status of the service and -// reports it to the Service Control Manager -// -// PARAMETERS: -// dwCurrentState - the state of the service -// dwWin32ExitCode - error code to report -// dwWaitHint - worst case estimate to next checkpoint -// -// RETURN VALUE: -// TRUE - success -// FALSE - failure -//____________________________________________________________________________________________________________________________ -BOOL ReportStatusToSCMgr(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint); -//____________________________________________________________________________________________________________________________ -// FUNCTION: AddToMessageLog(LPTSTR lpszMsg) -// -// PURPOSE: Allows any thread to log an error message -// -// PARAMETERS: -// lpszMsg - text for message -// -// RETURN VALUE: -// none -//____________________________________________________________________________________________________________________________ -void AddToMessageLog(LPTSTR lpszMsg); -//____________________________________________________________________________________________________________________________ -// -#ifdef __cplusplus -} -#endif - -#endif diff --git a/admin/Sources/Clients/ogagent/INSTALL.es.txt b/admin/Sources/Clients/ogagent/INSTALL.es.txt new file mode 100644 index 00000000..3f43206f --- /dev/null +++ b/admin/Sources/Clients/ogagent/INSTALL.es.txt @@ -0,0 +1,89 @@ +OGAgent: agente OpenGnsys para sistemas operativos INSTALL.es.txt +==================================================================== + + +Requisitos de creación +---------------------- +Sisitema operativo Linux con los siguientes paquetes instalados: +- Subversion +- GNU C++, Python, librerías PyQt4 +- Creación de instalador Exe (Wine 32 bits, Wine Gecko, Wine Mono, Samba Winbind, Cabextrct) +- Creación de paquetes Deb (debhelper, dpkg-dev) +- Creación de paquetes RPM (rpm-build) +- Creación de paquetes Pkg (xar, bomutils) + + +Crear instaladores de OGAgent +----------------------------- +- Paso previo: actaulizar componentes gráficos de PyQt para OGAgnet: + src/update.sh + +- Crear paquetes Deb y RPM para distribuciones Linux (requiere permisos de "root"): + sudo linux/build-packages.sh + +- Crear paquete Pkg para sistemas operativos macOS X: + sudo macos/build-pkg.sh + +- Crear el programa instalador para sistemas operativos Windows: + windows/build-windows.sh + +- Subir los nuevos ficheros .deb, .rpm, .pkg y .exe generados al directorio +/opt/opengnsys/www/descargas del servidor OpenGnsys. + + +Instalar OGAgent en cliente modelo +---------------------------------- +- Descargar el fichero correspondiente en el sistema operativo del cliente. + +- Ubuntu, Debian y derivados: + - Instalar dependencias (NOTA: revisar dependencias para Ubuntu 12.04): + sudo apt-get install -y libxss1 policykit-1 python python-requests python-qt4 python-six python-prctl + - Descargar e instalar el agente: + sudo dpkg -i ogagent_Version_all.deb + - Configurar el agente: + sudo sed -i "0,/remote=/ s,remote=.*,remote=https://IPServidorOpenGnsys/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg + - Iniciar el servicio (se iniciará automáticamente en el proceso de arranque): + sudo service ogagent start + +- Red Hat, Fedora y derivados (como root): + - Descargar e instalar el agente: + yum install ogagent-Version.noarch.rpm (Red Hat/CentOS) + dnf install ogagent-Version.noarch.rpm (Fedora) + - Configurar el agente: + sed -i "0,/remote=/ s,remote=.*,remote=https://IPServidorOpenGnsys/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg + - Puede ser necesario corregir permisos antes de iniciar el servicio: + chmod +x /etc/init.d/ogagent + - Iniciar el servicio (se iniciará automáticamente en el proceso de arranque): + service ogagent start + +- OpenSuSE: + (en preparación) + +- Windows (como usuario administrador): + - Descargar e instalar el agente ejecutando: + OGAgentSetup-Version.exe + - Seguir las instrucciones del instalador. + - Editar el fichero de configuación "C:\Program Files\OGAgent\cfg\ogagent.cfg" (o C:\Archivos de programa\OGAgent\cfg\ogagent.cfg) y modificar el valor de la cláusula "remote" de la sección [OGAgent] inclyendo la dirección IP del servidor OpenGnsys. + - Iniciar el servicio (se iniciará automáticamente en el proceso de arranque): + NET START OGAgent + +- macOS: + - Instalar dependencias: + sudo easy_install pip + sudo pip install netifaces requests six + - Descargar e instalar el agente: + sudo installer -pkg OGAgentInstaller-Version.pkg -target / + - Descargar el paquete y usar Finder pulsando sobre el fichero para instalarlo. + - Configurar el agente: + sed -i "0,/remote=/ s,remote=.*,remote=https://IPServidorOpenGnsys/opengnsys/rest/," /Applications/OGAgent.app/cfg/ogagent.cfg + - Iniciar el servicio (se iniciará automáticamente en el proceso de arranque): + sudo ogagent start + + +Postconfiguración para clientes clonados +---------------------------------------- +- Ejecutar manualmente o configurar automáticamente OGAgent en los clientes clonados +en el script de postconfiguración tras restuarar imagen: + ogConfigureOgagent NDisco Npart + + diff --git a/admin/Sources/Clients/ogagent/linux/Makefile b/admin/Sources/Clients/ogagent/linux/Makefile new file mode 100644 index 00000000..6ada91f5 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/Makefile @@ -0,0 +1,72 @@ +#!/usr/bin/make -f +# -*- makefile -*- + +# Directories +SOURCEDIR := ../src +LIBDIR := $(DESTDIR)/usr/share/OGAgent +BINDIR := $(DESTDIR)/usr/bin +SBINDIR = $(DESTDIR)/usr/sbin +APPSDIR := $(DESTDIR)/usr/share/applications +CFGDIR := $(DESTDIR)/etc/ogagent +INITDIR := $(DESTDIR)/etc/init.d +XDGAUTOSTARTDIR := $(DESTDIR)/etc/xdg/autostart +KDEAUTOSTARTDIR := $(DESTDIR)/usr/share/autostart + +PYC := $(shell find $(SOURCEDIR) -name '*.py[co]') +CACHES := $(shell find $(SOURCEDIR) -name '__pycache__') + +clean: + rm -rf $(PYC) $(CACHES) $(DESTDIR) +install-ogagent: + rm -rf $(DESTDIR) + mkdir -p $(LIBDIR) + mkdir -p $(BINDIR) + mkdir -p $(SBINDIR) + mkdir -p $(APPSDIR) + mkdir -p $(CFGDIR) + mkdir -p $(XDGAUTOSTARTDIR) + mkdir -p $(KDEAUTOSTARTDIR) + + mkdir $(LIBDIR)/img + + # Cleans up .pyc and cache folders + rm -f $(PYC) $(CACHES) + + cp -r $(SOURCEDIR)/opengnsys $(LIBDIR)/opengnsys + cp -r $(SOURCEDIR)/cfg $(LIBDIR)/cfg + cp $(SOURCEDIR)/img/oga.png $(LIBDIR)/img + + cp $(SOURCEDIR)/OGAgentUser.py $(LIBDIR) + # QT Dialogs & resources + cp $(SOURCEDIR)/*_ui.py $(LIBDIR) + cp $(SOURCEDIR)/OGAgent_rc.py $(LIBDIR) + + # Autostart elements for gnome/kde + cp desktop/OGAgentTool.desktop $(XDGAUTOSTARTDIR) + cp desktop/OGAgentTool.desktop $(KDEAUTOSTARTDIR) + + # scripts + cp scripts/ogagent $(BINDIR) + cp scripts/OGAgentTool-startup $(BINDIR) + cp scripts/OGAgentTool $(BINDIR) + + # Fix permissions + chmod 755 $(BINDIR)/ogagent + chmod 755 $(BINDIR)/OGAgentTool-startup + chmod 755 $(LIBDIR)/OGAgentUser.py + chmod 600 $(LIBDIR)/cfg/ogagent.cfg + + # If for red hat based, copy init.d +ifeq ($(DISTRO),rh) + mkdir -p $(INITDIR) + cp debian/ogagent.init $(INITDIR)/ogagent + chmod +x $(INITDIR)/ogagent + ln -fs /usr/share/OGAgent/cfg/ogagent.cfg $(CFGDIR) + ln -fs /usr/share/OGAgent/cfg/ogclient.cfg $(CFGDIR) +endif + + # chmod 0755 $(BINDIR)/ogagent +uninstall: + rm -rf $(LIBDIR) + # rm -f $(BINDIR)/ogagent + rm -rf $(CFGDIR) diff --git a/admin/Sources/Clients/ogagent/linux/build-packages.sh b/admin/Sources/Clients/ogagent/linux/build-packages.sh new file mode 100755 index 00000000..b4f11077 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/build-packages.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +VERSION=1.1.0 +RELEASE=1 + +cd $(dirname "$0") +top=`pwd` + +# Debian based +dpkg-buildpackage -b -d + +cat ogagent-template.spec | + sed -e s/"version 0.0.0"/"version ${VERSION}"/g | + sed -e s/"release 1"/"release ${RELEASE}"/g > ogagent-$VERSION.spec + +# Now fix dependencies for opensuse +cat ogagent-template.spec | + sed -e s/"version 0.0.0"/"version ${VERSION}"/g | + sed -e s/"name ogagent"/"name ogagent-opensuse"/g | + sed -e s/"PyQt4"/"python-qt4"/g | + sed -e s/"libXScrnSaver"/"libXss1"/g > ogagent-opensuse-$VERSION.spec + + +# Right now, ogagent-xrdp-1.7.0.spec is not needed +for pkg in ogagent-$VERSION.spec ogagent-opensuse-$VERSION.spec; do + + rm -rf rpm + for folder in SOURCES BUILD RPMS SPECS SRPMS; do + mkdir -p rpm/$folder + done + + rpmbuild -v -bb --clean --buildroot=$top/rpm/BUILD/$pkg-root --target noarch $pkg 2>&1 +done + +#rm ogagent-$VERSION diff --git a/admin/Sources/Clients/ogagent/linux/debian/changelog b/admin/Sources/Clients/ogagent/linux/debian/changelog new file mode 100644 index 00000000..01fd564d --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/changelog @@ -0,0 +1,12 @@ +ogagent (1.1.0) stable; urgency=medium + + * Functional OpenGnsys Agent interacting with OpenGnsys Server 1.1.0 + + -- Ramón M. Gómez Tue, 13 Oct 2016 17:00:00 +0200 + +ogagent (1.0.0) stable; urgency=medium + + * Initial release for OpenGnsys Agent + + -- Adolfo Gómez García Tue, 18 Jul 2015 03:18:22 +0200 + diff --git a/admin/Sources/Clients/ogagent/linux/debian/compat b/admin/Sources/Clients/ogagent/linux/debian/compat new file mode 100644 index 00000000..f11c82a4 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/compat @@ -0,0 +1 @@ +9 \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/linux/debian/control b/admin/Sources/Clients/ogagent/linux/debian/control new file mode 100644 index 00000000..34d25de7 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/control @@ -0,0 +1,15 @@ +Source: ogagent +Section: admin +Priority: optional +Maintainer: Ramón M. Gómez +Build-Depends: debhelper (>= 7), po-debconf +Standards-Version: 3.9.2 +Homepage: https://opengnsys.es + +Package: ogagent +Section: admin +Priority: optional +Architecture: all +Depends: policykit-1(>=0.100), python-requests (>=0.8.2), python-qt4 (>=4.9), python-six(>=1.1), python-prctl(>=1.1.1), python (>=2.7), libxss1, ${misc:Depends} +Description: OpenGnsys Agent for Operating Systems + This package provides the required components to allow this machine to work on an environment managed by OpenGnsys. diff --git a/admin/Sources/Clients/ogagent/linux/debian/copyright b/admin/Sources/Clients/ogagent/linux/debian/copyright new file mode 100644 index 00000000..7b6ef31b --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/copyright @@ -0,0 +1,26 @@ +Format-Specification: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?op=file&rev=135 +Name: ogagent +Maintainer: Ramón M. Gómez +Source: https://opengnsys.es + +Copyright: 2014 Virtual Cable S.L.U. +License: BSD-3-clause + +License: GPL-2+ +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +. +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +. +On Debian systems, the full text of the GNU General Public +License version 2 can be found in the file +`/usr/share/common-licenses/GPL-2'. diff --git a/admin/Sources/Clients/ogagent/linux/debian/docs b/admin/Sources/Clients/ogagent/linux/debian/docs new file mode 100644 index 00000000..b2b2a781 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/docs @@ -0,0 +1 @@ +readme.txt diff --git a/admin/Sources/Clients/ogagent/linux/debian/ogagent.init b/admin/Sources/Clients/ogagent/linux/debian/ogagent.init new file mode 100644 index 00000000..3eee35c1 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/ogagent.init @@ -0,0 +1,23 @@ +#!/bin/sh -e +### BEGIN INIT INFO +# Provides: ogagent +# Required-Start: $local_fs $remote_fs $network $syslog $named +# Required-Stop: $local_fs $remote_fs $network $syslog $named +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: OpenGnsys Agent Service +### END INIT INFO +# + +# . /lib/lsb/init-functions + +case "$1" in + start|stop|restart) + /usr/bin/ogagent $1 + ;; + force-reload) + /usr/bin/ogagent restart + ;; + *) echo "Usage: $0 {start|stop|restart|force-reload}" >&2; exit 1 ;; +esac + diff --git a/admin/Sources/Clients/ogagent/linux/debian/ogagent.links b/admin/Sources/Clients/ogagent/linux/debian/ogagent.links new file mode 100644 index 00000000..9b970d7b --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/ogagent.links @@ -0,0 +1,2 @@ +/usr/share/OGAgent/cfg/ogagent.cfg /etc/ogagent/ogagent.cfg +/usr/share/OGAgent/cfg/ogclient.cfg /etc/ogagent/ogclient.cfg diff --git a/admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst new file mode 100644 index 00000000..b59cfa6f --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst @@ -0,0 +1,21 @@ +#!/bin/sh + +. /usr/share/debconf/confmodule + +set -e +case "$1" in + configure) + chmod 600 /usr/share/OGAgent/cfg/ogagent.cfg + ;; + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 diff --git a/admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst.debhelper b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst.debhelper new file mode 100644 index 00000000..e75924dc --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postinst.debhelper @@ -0,0 +1,5 @@ +# Automatically added by dh_installinit +if [ -x "/etc/init.d/ogagent" ]; then + update-rc.d ogagent defaults >/dev/null || exit $? +fi +# End automatically added section diff --git a/admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm new file mode 100644 index 00000000..a46fa487 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm @@ -0,0 +1,10 @@ +#!/bin/sh -e + +. /usr/share/debconf/confmodule + +set -e + +if [ "$1" = "purge" ] ; then + rm -rf /usr/share/OGAgent || true > /dev/null 2>&1 +fi + diff --git a/admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm.debhelper b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm.debhelper new file mode 100644 index 00000000..3167f1f8 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/ogagent.postrm.debhelper @@ -0,0 +1,12 @@ +# Automatically added by dh_installinit +if [ "$1" = "purge" ] ; then + update-rc.d ogagent remove >/dev/null +fi + + +# In case this system is running systemd, we make systemd reload the unit files +# to pick up changes. +if [ -d /run/systemd/system ] ; then + systemctl --system daemon-reload >/dev/null || true +fi +# End automatically added section diff --git a/admin/Sources/Clients/ogagent/linux/debian/ogagent.substvars b/admin/Sources/Clients/ogagent/linux/debian/ogagent.substvars new file mode 100644 index 00000000..978fc8b5 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/ogagent.substvars @@ -0,0 +1,2 @@ +misc:Depends= +misc:Pre-Depends= diff --git a/admin/Sources/Clients/ogagent/linux/debian/rules b/admin/Sources/Clients/ogagent/linux/debian/rules new file mode 100755 index 00000000..fbe82e67 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/rules @@ -0,0 +1,44 @@ +#!/usr/bin/make -f +# -*- makefile -*- +configure: configure-stamp +configure-stamp: + dh_testdir + touch configure-stamp +build: build-arch build-indep +build-arch: build-stamp +build-indep: build-stamp +build-stamp: configure-stamp + dh_testdir + $(MAKE) + touch $@ +clean: + dh_testdir + dh_testroot + rm -f build-stamp configure-stamp + dh_clean +install: build + dh_testdir + dh_testroot + dh_prep + dh_installdirs + $(MAKE) DESTDIR=$(CURDIR)/debian/ogagent install-ogagent +binary-arch: build install + # emptyness +binary-indep: build install + dh_testdir + dh_testroot + dh_installchangelogs + dh_installdocs + dh_installdebconf + dh_installinit --no-start + dh_python2=python + dh_compress + dh_link + dh_fixperms + dh_installdeb + dh_shlibdeps + dh_gencontrol + dh_md5sums + dh_builddeb +binary: binary-indep +.PHONY: build clean binary-indep binary install configure diff --git a/admin/Sources/Clients/ogagent/linux/debian/source/format b/admin/Sources/Clients/ogagent/linux/debian/source/format new file mode 100644 index 00000000..9f674278 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/debian/source/format @@ -0,0 +1 @@ +3.0 (native) \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop b/admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop new file mode 100644 index 00000000..fd3867d3 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop @@ -0,0 +1,12 @@ +[Desktop Entry] +Name=OpenGnsys Agent Tools +Comment=OpenGnsys Userspace tools +Exec=/usr/bin/OGAgentTool-startup +Icon=/usr/share/OGAgent/img/oga.png +Terminal=false +Type=Application +NoDisplay=true +X-KDE-autostart-after=panel +X-KDE-StartupNotify=false +X-DBUS-StartupType=Unique +X-KDE-UniqueApplet=true diff --git a/admin/Sources/Clients/ogagent/linux/ogagent-template.spec b/admin/Sources/Clients/ogagent/linux/ogagent-template.spec new file mode 100644 index 00000000..1368cccb --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/ogagent-template.spec @@ -0,0 +1,65 @@ +%define _topdir %(echo $PWD)/rpm +%define name ogagent +%define version 0.0.0 +%define release 1 +%define buildroot %{_topdir}/%{name}-%{version}-%{release}-root + +BuildRoot: %{buildroot} +Name: %{name} +Version: %{version} +Release: %{release} +Summary: OpenGnsys Agent & tools +License: BSD3 +Group: Admin +Requires: python-six python-requests PyQt4 libXScrnSaver +Vendor: OpenGnsys Project +URL: https://opengnsys.es +Provides: ogagent + +%define _rpmdir ../ +%define _rpmfilename %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm + + +%install +curdir=`pwd` +cd ../.. +make DESTDIR=$RPM_BUILD_ROOT DISTRO=rh install-ogagent +cd $curdir + +%clean +rm -rf $RPM_BUILD_ROOT +curdir=`pwd` +cd ../.. +make DESTDIR=$RPM_BUILD_ROOT DISTRO=rh clean +cd $curdir + + +%post +systemctl enable ogagent.service > /dev/null 2>&1 + +%preun +systemctl disable ogagent.service > /dev/null 2>&1 +systemctl stop ogagent.service > /dev/null 2>&1 + +%postun +# $1 == 0 on uninstall, == 1 on upgrade for preun and postun (just a reminder for me... :) ) +if [ $1 -eq 0 ]; then + rm -rf /etc/ogagent + rm /var/log/ogagent.log +fi +# And, posibly, the .pyc leaved behind on /usr/share/OGAgent +rm -rf /usr/share/OGAgent > /dev/null 2>&1 + +%description +This package provides the required components to allow this machine to work on an environment managed by OpenGnsys. + +%files +%defattr(-,root,root) +/etc/ogagent +/etc/xdg/autostart/OGAgentTool.desktop +/etc/init.d/ogagent +/usr/bin/OGAgentTool-startup +/usr/bin/ogagent +/usr/bin/OGAgentTool +/usr/share/OGAgent/* +/usr/share/autostart/OGAgentTool.desktop diff --git a/admin/Sources/Clients/ogagent/linux/policy/org.openuds.pkexec.UDSActorConfig.policy b/admin/Sources/Clients/ogagent/linux/policy/org.openuds.pkexec.UDSActorConfig.policy new file mode 100644 index 00000000..9afd775a --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/policy/org.openuds.pkexec.UDSActorConfig.policy @@ -0,0 +1,20 @@ + + + + + + + Run UDS Actor Configuration Program + Authentication is required to run UDS Actor Configuration + + no + no + auth_admin_keep + + /usr/sbin/UDSActorConfig + TRUE + + + \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/linux/readme.txt b/admin/Sources/Clients/ogagent/linux/readme.txt new file mode 100644 index 00000000..a2771def --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/readme.txt @@ -0,0 +1,3 @@ +OGAgent is the agent intended for OpengGnsys interaction. + +Please, visit https://opengnsys.es for more information diff --git a/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool new file mode 100644 index 00000000..5b300523 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool @@ -0,0 +1,6 @@ +#!/bin/sh + +FOLDER=/usr/share/OGAgent + +cd $FOLDER +python OGAgentUser.py $@ diff --git a/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup new file mode 100644 index 00000000..bb3a848e --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup @@ -0,0 +1,10 @@ +#!/bin/sh + +# Simple hack to wait for systray to be present +# Exec tool if not already runned by session manager +ps -ef | grep "$USER" | grep -v grep | grep -v OGAgentTool-startup | grep 'OGAgentTool' -q +# If not already running +if [ $? -eq 1 ]; then + sleep 5 + exec /usr/bin/OGAgentTool +fi \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/linux/scripts/ogagent b/admin/Sources/Clients/ogagent/linux/scripts/ogagent new file mode 100644 index 00000000..1bcc29b0 --- /dev/null +++ b/admin/Sources/Clients/ogagent/linux/scripts/ogagent @@ -0,0 +1,6 @@ +#!/bin/sh + +FOLDER=/usr/share/OGAgent + +cd $FOLDER +python -m opengnsys.linux.OGAgentService $@ diff --git a/admin/Sources/Clients/ogagent/macos/build-pkg.sh b/admin/Sources/Clients/ogagent/macos/build-pkg.sh new file mode 100755 index 00000000..500da58e --- /dev/null +++ b/admin/Sources/Clients/ogagent/macos/build-pkg.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Create macOS installation packages. +# Based on bomutils tutorail: http://bomutils.dyndns.org/tutorial.html + +VERSION=1.1.0 +AUTHOR="OpenGnsys Project" + +# Create empty directories. +cd $(dirname $0) +rm -fr build +mkdir -p build && cd build +mkdir -p flat/base.pkg flat/Resources/en.lproj +mkdir -p root/Applications + +# Copy application and script files. +cp -a ../../src root/Applications/OGAgent.app +cp -a ../scripts . + +# Create plist file. +cat << EOT > root/Applications/OGAgent.app/OGAgent.plist + + + + + BuildAliasOf + OGAgent + BuildVersion + $VERSION + $AUTHOR + + +EOT + +# Add files in the base package. +( cd root && find . | cpio -o --format odc --owner 0:80 | gzip -c ) > flat/base.pkg/Payload + +# Create PackageInfo file. +cat << EOT > flat/base.pkg/PackageInfo + + + + + + + + + +EOT + +# Compress the scripts folder. +( cd scripts && find . | cpio -o --format odc --owner 0:80 | gzip -c ) > flat/base.pkg/Scripts + +# Create BOM file. +mkbom -u 0 -g 80 root flat/base.pkg/Bom + +# Create Distribution file. +cat << EOT > flat/Distribution + + + OGAgent 1.1.0 + + + + + + + + + + + #base.pkg + +EOT + +# Create new Xar application archive. +rm -f ../../../OGAgentInstaller-$VERSION.pkg +( cd flat && xar --compression none -cf "../../../OGAgentInstaller-$VERSION.pkg" * ) + diff --git a/admin/Sources/Clients/ogagent/macos/scripts/es.opengnsys.ogagent.plist b/admin/Sources/Clients/ogagent/macos/scripts/es.opengnsys.ogagent.plist new file mode 100644 index 00000000..5ec11fa5 --- /dev/null +++ b/admin/Sources/Clients/ogagent/macos/scripts/es.opengnsys.ogagent.plist @@ -0,0 +1,15 @@ + + + + Label + es.opengnsys.ogagent + ProgramArguments + + /usr/bin/ogagent + start + + RunAtLoad + + + + diff --git a/admin/Sources/Clients/ogagent/macos/scripts/ogagent b/admin/Sources/Clients/ogagent/macos/scripts/ogagent new file mode 100755 index 00000000..b139d7f2 --- /dev/null +++ b/admin/Sources/Clients/ogagent/macos/scripts/ogagent @@ -0,0 +1,6 @@ +#!/bin/sh + +FOLDER=/Applications/OGAgent.app + +cd $FOLDER +python -m opengnsys.linux.OGAgentService $@ diff --git a/admin/Sources/Clients/ogagent/macos/scripts/postinstall b/admin/Sources/Clients/ogagent/macos/scripts/postinstall new file mode 100755 index 00000000..ebb2ca48 --- /dev/null +++ b/admin/Sources/Clients/ogagent/macos/scripts/postinstall @@ -0,0 +1,17 @@ +#!/usr/bin/env sh + +# Directories +SRCDIR=$(dirname "$0") +BINDIR=/usr/bin +INITDIR=/Library/LaunchDaemons + +# Check if it needs to install Python dependencies: +if ! which pip &>/dev/null; then + easy_install pip + pip install netifaces requests six +fi + +# Copying files. +cp $SRCDIR/ogagent $BINDIR +cp $SRCDIR/es.opengnsys.ogagent.plist $INITDIR + diff --git a/admin/Sources/Clients/ogagent/requires.txt b/admin/Sources/Clients/ogagent/requires.txt new file mode 100644 index 00000000..07ce387c --- /dev/null +++ b/admin/Sources/Clients/ogagent/requires.txt @@ -0,0 +1,3 @@ +six +requests + diff --git a/admin/Sources/Clients/ogagent/src/OGAServiceHelper.py b/admin/Sources/Clients/ogagent/src/OGAServiceHelper.py new file mode 100644 index 00000000..79a6c81d --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/OGAServiceHelper.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import win32service +import win32serviceutil + +svc_name = "UDSActor" + +try: + hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) + + try: + hs = win32serviceutil.SmartOpenService(hscm, svc_name, win32service.SERVICE_ALL_ACCESS) + service_failure_actions = { + 'ResetPeriod': 864000, # Time in ms after which to reset the failure count to zero. + 'RebootMsg': u'', # Not using reboot option + 'Command': u'', # Not using run-command option + 'Actions': [ + (win32service.SC_ACTION_RESTART, 5000), # action, delay in ms + (win32service.SC_ACTION_RESTART, 5000) + ] + } + win32service.ChangeServiceConfig2(hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, service_failure_actions) + finally: + win32service.CloseServiceHandle(hs) +finally: + win32service.CloseServiceHandle(hscm) diff --git a/admin/Sources/Clients/ogagent/src/OGAgent.manifest b/admin/Sources/Clients/ogagent/src/OGAgent.manifest new file mode 100644 index 00000000..0e5ff974 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/OGAgent.manifest @@ -0,0 +1,17 @@ + + + + Description + + + + + + + + diff --git a/admin/Sources/Clients/ogagent/src/OGAgent.qrc b/admin/Sources/Clients/ogagent/src/OGAgent.qrc new file mode 100644 index 00000000..59177668 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/OGAgent.qrc @@ -0,0 +1,5 @@ + + + img/oga.png + + diff --git a/admin/Sources/Clients/ogagent/src/OGAgentUser.py b/admin/Sources/Clients/ogagent/src/OGAgentUser.py new file mode 100644 index 00000000..1c9bf30e --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/OGAgentUser.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import sys +import time +import signal +import json +import six +import atexit +from PyQt4 import QtGui +from PyQt4 import QtCore + +from opengnsys import ipc +from opengnsys import utils +from opengnsys.log import logger +from opengnsys.service import IPC_PORT +from opengnsys import operations +from about_dialog_ui import Ui_OGAAboutDialog +from message_dialog_ui import Ui_OGAMessageDialog +from opengnsys.scriptThread import ScriptExecutorThread +from opengnsys import VERSION +from opengnsys.config import readConfig +from opengnsys.loader import loadModules + +# Set default characters encoding to UTF-8 +reload(sys) +if hasattr(sys, 'setdefaultencoding'): + sys.setdefaultencoding('utf-8') + +trayIcon = None + +def sigAtExit(): + if trayIcon: + trayIcon.quit() + +#def sigTerm(sigNo, stackFrame): +# logger.debug("Exec sigTerm") +# if trayIcon: +# trayIcon.quit() + +# About dialog +class OGAAboutDialog(QtGui.QDialog): + def __init__(self, parent=None): + QtGui.QDialog.__init__(self, parent) + self.ui = Ui_OGAAboutDialog() + self.ui.setupUi(self) + self.ui.VersionLabel.setText("Version " + VERSION) + + def closeDialog(self): + self.hide() + + +class OGAMessageDialog(QtGui.QDialog): + def __init__(self, parent=None): + QtGui.QDialog.__init__(self, parent) + self.ui = Ui_OGAMessageDialog() + self.ui.setupUi(self) + + def message(self, message): + self.ui.message.setText(message) + self.show() + + def closeDialog(self): + self.hide() + + +class MessagesProcessor(QtCore.QThread): + + logoff = QtCore.pyqtSignal(name='logoff') + message = QtCore.pyqtSignal(tuple, name='message') + script = QtCore.pyqtSignal(QtCore.QString, name='script') + exit = QtCore.pyqtSignal(name='exit') + + def __init__(self, port): + super(self.__class__, self).__init__() + # Retries connection for a while + for _ in range(10): + try: + self.ipc = ipc.ClientIPC(port) + self.ipc.start() + break + except Exception: + logger.debug('IPC Server is not reachable') + self.ipc = None + time.sleep(2) + + self.running = False + + def stop(self): + self.running = False + if self.ipc: + self.ipc.stop() + + def isAlive(self): + return self.ipc is not None + + def sendLogin(self, userName, language): + if self.ipc: + self.ipc.sendLogin(userName, language) + + def sendLogout(self, userName): + if self.ipc: + self.ipc.sendLogout(userName) + + def run(self): + if self.ipc is None: + return + self.running = True + + # Wait a bit so we ensure IPC thread is running... + time.sleep(2) + + while self.running and self.ipc.running: + try: + msg = self.ipc.getMessage() + if msg is None: + break + msgId, data = msg + logger.debug('Got Message on User Space: {}:{}'.format(msgId, data)) + if msgId == ipc.MSG_MESSAGE: + module, message, data = data.split('\0') + self.message.emit((module, message, data)) + elif msgId == ipc.MSG_LOGOFF: + self.logoff.emit() + elif msgId == ipc.MSG_SCRIPT: + self.script.emit(QtCore.QString.fromUtf8(data)) + except Exception as e: + try: + logger.error('Got error on IPC thread {}'.format(utils.exceptionToMessage(e))) + except: + logger.error('Got error on IPC thread (an unicode error??)') + + if self.ipc.running is False and self.running is True: + logger.warn('Lost connection with Service, closing program') + + self.exit.emit() + + +class OGASystemTray(QtGui.QSystemTrayIcon): + def __init__(self, app_, parent=None): + self.app = app_ + self.config = readConfig(client=True) + + # Get opengnsys section as dict + cfg = dict(self.config.items('opengnsys')) + + # Set up log level + logger.setLevel(cfg.get('log', 'INFO')) + + self.ipcport = int(cfg.get('ipc_port', IPC_PORT)) + + # style = app.style() + # icon = QtGui.QIcon(style.standardPixmap(QtGui.QStyle.SP_ComputerIcon)) + icon = QtGui.QIcon(':/images/img/oga.png') + + QtGui.QSystemTrayIcon.__init__(self, icon, parent) + self.menu = QtGui.QMenu(parent) + exitAction = self.menu.addAction("About") + exitAction.triggered.connect(self.about) + self.setContextMenu(self.menu) + self.ipc = MessagesProcessor(self.ipcport) + + if self.ipc.isAlive() is False: + raise Exception('No connection to service, exiting.') + + self.timer = QtCore.QTimer() + self.timer.timeout.connect(self.timerFnc) + + + self.stopped = False + + self.ipc.message.connect(self.message) + self.ipc.exit.connect(self.quit) + self.ipc.script.connect(self.executeScript) + self.ipc.logoff.connect(self.logoff) + + self.aboutDlg = OGAAboutDialog() + self.msgDlg = OGAMessageDialog() + + self.timer.start(1000) # Launch idle checking every 1 seconds + + self.ipc.start() + + def initialize(self): + # Load modules and activate them + # Also, sends "login" event to service + self.modules = loadModules(self, client=True) + logger.debug('Modules: {}'.format(list(v.name for v in self.modules))) + + # Send init to all modules + validMods = [] + for mod in self.modules: + try: + logger.debug('Activating module {}'.format(mod.name)) + mod.activate() + validMods.append(mod) + except Exception as e: + logger.exception() + logger.error("Activation of {} failed: {}".format(mod.name, utils.exceptionToMessage(e))) + + self.modules[:] = validMods # copy instead of assignment + + # If this is running, it's because he have logged in, inform service of this fact + self.ipc.sendLogin(operations.getCurrentUser(), operations.getSessionLanguage()) + + def deinitialize(self): + for mod in reversed(self.modules): # Deinitialize reversed of initialization + try: + logger.debug('Deactivating module {}'.format(mod.name)) + mod.deactivate() + except Exception as e: + logger.exception() + logger.error("Deactivation of {} failed: {}".format(mod.name, utils.exceptionToMessage(e))) + + def timerFnc(self): + pass + + def message(self, msg): + ''' + Processes the message sent asynchronously, msg is an QString + ''' + try: + logger.debug('msg: {}, {}'.format(type(msg), msg)) + module, message, data = msg + except Exception as e: + logger.error('Got exception {} processing message {}'.format(e, msg)) + return + + for v in self.modules: + if v.name == module: # Case Sensitive!!!! + try: + logger.debug('Notifying message {} to module {} with json data {}'.format(message, v.name, data)) + v.processMessage(message, json.loads(data)) + return + except Exception as e: + logger.error('Got exception {} processing generic message on {}'.format(e, v.name)) + + logger.error('Module {} not found, messsage {} not sent'.format(module, message)) + + def executeScript(self, script): + logger.debug('Executing script') + script = six.text_type(script.toUtf8()).decode('base64') + th = ScriptExecutorThread(script) + th.start() + + def logoff(self): + logger.debug('Logoff invoked') + operations.logoff() # Invoke log off + + def about(self): + self.aboutDlg.exec_() + + def cleanup(self): + logger.debug('Quit invoked') + if self.stopped is False: + self.stopped = True + try: + self.deinitialize() + except Exception: + logger.exception() + logger.error('Got exception deinitializing modules') + + try: + # If we close Client, send Logoff to Broker + self.ipc.sendLogout(operations.getCurrentUser()) + time.sleep(1) + self.timer.stop() + self.ipc.stop() + except Exception: + # May we have lost connection with server, simply log and exit in that case + logger.exception() + logger.exception("Got an exception, processing quit") + + try: + # operations.logoff() # Uncomment this after testing to logoff user + pass + except Exception: + pass + + def quit(self): + #logger.debug("Exec quit {}".format(self.stopped)) + if self.stopped is False: + self.cleanup() + self.app.quit() + + def closeEvent(self, event): + logger.debug("Exec closeEvent") + event.accept() + self.quit() + +if __name__ == '__main__': + app = QtGui.QApplication(sys.argv) + + if not QtGui.QSystemTrayIcon.isSystemTrayAvailable(): + # QtGui.QMessageBox.critical(None, "Systray", "I couldn't detect any system tray on this system.") + sys.exit(1) + + # This is important so our app won't close on messages windows (alerts, etc...) + QtGui.QApplication.setQuitOnLastWindowClosed(False) + + try: + trayIcon = OGASystemTray(app) + except Exception as e: + logger.exception() + logger.error('OGA Service is not running, or it can\'t contact with OGA Server. User Tools stopped: {}'.format(utils.exceptionToMessage(e))) + sys.exit(1) + + try: + trayIcon.initialize() # Initialize modules, etc.. + except Exception as e: + logger.exception() + logger.error('Exception initializing OpenGnsys User Agent {}'.format(utils.exceptionToMessage(e))) + trayIcon.quit() + sys.exit(1) + + app.aboutToQuit.connect(trayIcon.cleanup) + trayIcon.show() + + # Catch kill and logout user :) + #signal.signal(signal.SIGTERM, sigTerm) + atexit.register(sigAtExit) + + res = app.exec_() + + logger.debug('Exiting') + trayIcon.quit() + + sys.exit(res) diff --git a/admin/Sources/Clients/ogagent/src/OGAgent_rc.py b/admin/Sources/Clients/ogagent/src/OGAgent_rc.py new file mode 100644 index 00000000..867ca2ab --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/OGAgent_rc.py @@ -0,0 +1,289 @@ +# -*- coding: utf-8 -*- + +# Resource object code +# +# Created by: The Resource Compiler for PyQt4 (Qt v4.8.6) +# +# WARNING! All changes made in this file will be lost! + +from PyQt4 import QtCore + +qt_resource_data = b"\ +\x00\x00\x0f\x42\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x30\x00\x00\x00\x30\x08\x06\x00\x00\x01\x20\x05\xc9\x11\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc7\x00\x00\x0e\xc7\ +\x01\x38\x92\x2f\x76\x00\x00\x0e\xf4\x49\x44\x41\x54\x78\xda\xc5\ +\x59\x07\x58\x53\xd9\x12\xbe\x29\xd4\x84\x12\x21\xf4\x22\x08\x08\ +\x02\x22\xa2\x22\x22\x22\x8a\xa0\xa0\x14\x1b\xae\x62\x05\xac\xb8\ +\x76\xd7\xde\xd6\xde\x15\xf5\xd9\x7b\x17\x51\x41\x50\x14\x10\x04\ +\x44\x94\x8e\xd2\x25\x80\x80\x48\xef\x24\xb4\xbc\x39\x59\x6e\x4c\ +\x42\xe2\x0a\xea\x7b\xf3\x7d\xe1\xde\x7b\xca\xcc\x9c\x73\xe6\xcc\ +\xfc\x33\x90\xd9\x6c\x36\x86\xe8\xe8\xe9\x9b\xe9\xab\x97\x79\x9a\ +\x62\x5d\x44\x46\x7f\xd6\x6f\x3f\xc1\xb6\xb7\x1d\xf6\xf7\xc3\xc0\ +\xf0\xf3\x53\x5c\xc6\x2e\xe4\x74\x9c\xbe\x78\xff\xcd\xc1\x9d\x2b\ +\x08\xf8\x48\x34\x48\x55\x85\x9e\x4a\x5e\xe6\x3d\x7d\x04\xfa\x40\ +\x8d\xd3\xdd\xc6\x6d\x73\x1c\x6b\x55\xd8\xd9\xd1\xf9\x88\xc3\x0a\ +\x9f\x11\x19\x93\xc8\x4e\x4e\xcb\xce\x5e\xeb\x3b\x7b\x07\x19\xe3\ +\xa1\xd1\x23\x2d\x08\xd0\x91\xcc\x91\x81\x6b\x15\x15\x9b\xb4\xd6\ +\xd6\x7a\xf0\x61\xae\x56\x1b\x77\x9d\x62\xed\xdb\xe6\x2b\x11\xfc\ +\x22\xfa\x10\x5f\x47\x47\x47\x87\x38\xc6\x4f\x6c\xee\x3a\x0e\x9f\ +\xba\x91\xd1\xa5\x00\x6a\x24\x30\x99\x2c\x39\x32\xef\x1a\x10\xed\ +\x3e\x7c\x91\xb5\x65\xad\xb7\x38\x9f\x56\x57\x6f\x3f\x79\xda\xd9\ +\xc9\x76\xae\xaa\xae\xd5\xe7\x6a\x85\x2f\x12\x71\x40\xef\x82\x9c\ +\xba\xed\xe1\x9c\x19\x13\x27\x9b\x18\xf5\x7b\x84\x77\xf8\x07\x86\ +\x5f\x98\xea\x32\xd6\x07\xbd\x57\xd7\xd4\xe9\xef\x3f\x7e\x35\x47\ +\x4d\x85\xde\x40\x3e\x70\xe2\x6a\x1e\x6a\xec\xec\xec\xe4\x4c\x6e\ +\x6f\xef\x90\x44\x4f\x34\xf8\xaf\x1d\x27\xd8\x07\x76\xac\xc0\x52\ +\xd3\x73\x36\x4d\x18\x67\x1d\x6a\x37\x72\x88\x23\xf9\xaf\x15\xf3\ +\xf4\xf8\x44\x92\x49\x4c\xa4\xce\xd5\xdb\x81\x9c\xc1\x70\x58\x71\ +\x70\x2e\xfb\x22\x5e\xbf\xdb\xcb\x55\x49\x18\x95\x55\xd4\xb4\xc0\ +\x43\x0a\x06\x5b\x9d\xba\x70\xaf\xc8\xd7\xc7\x03\xdb\xb0\xd3\xaf\ +\x43\xe4\x84\x0d\x2b\xe6\x4a\x27\xa5\x64\xb2\x07\x0f\x32\xc2\x5c\ +\x27\xd8\x6a\xc2\xc9\xb4\xed\xdf\xbe\x5c\x9c\xbb\x4b\x88\x92\xd3\ +\xb2\x66\xdd\x79\x18\x7a\x53\xd4\x0e\x71\x55\x82\x3d\x26\x6d\xd8\ +\x79\xb2\x7d\xa9\xd7\x34\x9b\x95\x4b\x66\x9a\xff\xeb\xb6\xa2\xc1\ +\x5b\xd7\xf9\xa8\xca\x50\xa5\xcb\xf0\xf3\x10\x29\x01\x1f\x80\x06\ +\xa3\xe7\xd0\xc1\xc6\x97\xdf\x27\x7d\x5c\xc0\x3b\x68\xdf\xb1\xcb\ +\x0d\x34\x79\x39\xaa\x89\xa1\xee\xca\x6e\x8b\xd6\xd3\xd1\x88\xc0\ +\x27\x7c\x29\xab\x1c\x25\x2f\x27\x13\x45\xa5\x50\x72\x86\x0e\x32\ +\x32\xa0\x50\xa4\x8f\x77\x9b\x80\x16\xbd\x69\xf5\x02\xed\xd6\xd6\ +\x36\x8a\xaa\x8a\x62\x14\xd8\x6b\xd6\xf2\x85\x1e\x46\x99\xd9\x05\ +\xec\x80\xa7\xaf\x0a\xc9\x72\xb2\xd4\xe2\xba\xfa\x46\x0d\x5c\x35\ +\xdd\xbe\xea\x51\xc0\xb5\x28\xe8\xf9\x6b\xf6\xa4\xf1\xa3\x30\x65\ +\xba\xc2\x01\xd4\x2e\x21\x21\x6e\xeb\x3e\xd1\x4e\x86\xbc\x79\x8d\ +\x97\xa6\xb0\xc5\xa1\xc1\x88\x86\x98\x0f\xb8\xfa\x22\x22\x2e\xc8\ +\x61\x8c\xd5\xc4\x80\xa0\x08\x86\xd0\x83\xcb\xc9\x2b\x74\x34\xd0\ +\xd3\xe6\x7e\x9b\x9b\x19\x4d\x44\xcf\xf8\xc4\xf4\xbe\x42\x27\xc0\ +\xe0\x50\xde\x2b\x95\x5f\x50\x82\xd1\x15\xe4\x31\xb0\x2d\xa2\x48\ +\xd3\x68\x6a\x6e\xa1\x1f\x3e\x75\x93\xb1\x75\xad\x17\xcd\xd2\xc2\ +\xb8\xcd\xef\xfc\xbd\x42\x58\xbc\x68\xe3\xcb\x67\x14\x8f\xd9\xbe\ +\xde\x87\xfa\x24\x24\xaa\xcd\xd5\xc9\x16\xf3\x99\xe3\x66\xc6\xe7\ +\x07\x78\xe9\xdc\xd5\x87\x11\x9f\x18\xc5\x76\xf8\xb7\xa6\xba\xf2\ +\xfb\xe5\x0b\x67\x0c\xc3\x7a\x41\x7c\x1a\xf1\x9a\x11\x5a\x1f\x81\ +\x80\xb1\x13\x53\x32\xe7\xdc\x7b\xf4\xe2\x1a\xde\xb7\x78\xfe\xd4\ +\xd1\xe8\xa8\x7a\x24\x20\x2a\x36\x71\x5d\xf0\x8b\x98\x83\xe8\x5d\ +\x52\x52\xa2\x6e\xd7\xc6\xc5\xf2\xf8\x00\x8b\x41\x46\xd7\x91\x00\ +\xfc\x1b\x8d\xed\x91\x80\xbc\xfc\xcf\x63\x71\xe6\x88\x78\x99\xe3\ +\xb4\x68\xfe\x14\xbb\x73\x57\x1e\xbe\xfa\xc7\xf6\x07\x5c\xe6\xf3\ +\x92\x6c\x36\x71\xcb\x9e\x33\x6d\xfa\xba\x5a\xc4\xd9\x1e\xce\x18\ +\x89\x44\xe4\xf1\x7e\x81\x35\xe4\xf3\xd7\x02\xc2\x04\x27\x10\x08\ +\x84\x4e\x3e\x73\xf7\x7f\x7e\x0b\x3d\x89\x44\x62\xbb\x89\x91\x5e\ +\x00\x7a\x2f\x2a\x2e\x73\x3a\x7b\xc5\x3f\x78\xef\x56\x5f\x6c\xcf\ +\x96\x65\xd8\xf6\xfd\x67\xeb\xd3\x3e\xe6\x2c\x95\x92\x92\x6c\xaf\ +\xab\x6f\xba\x0b\x96\x81\xa9\xa9\x2a\x7d\x21\x7b\xcf\x76\x1b\x7f\ +\xf1\xc6\xe3\xe7\x5c\xcf\xb2\xd3\xaf\xed\xc0\x8e\x3f\x49\x82\xe7\ +\x62\xa8\xdf\x37\x64\x81\xa7\xab\x33\xde\x06\xde\x06\x43\xcc\xbb\ +\xbe\x91\x3b\x96\xe3\x84\xb2\x33\x37\xd9\x43\x06\x0d\xa8\xdd\xba\ +\xe7\x0c\x79\xc3\xca\x79\xa3\xc9\xc8\x88\x91\x33\x89\x8e\x4b\x5e\ +\x05\xf7\xeb\x28\x5a\x01\xce\x14\x1d\xf2\x8a\xc5\x33\x07\xab\xab\ +\xd2\x93\x79\x05\xc2\x78\x5e\xc3\xc0\x78\x9d\x51\x7f\x3d\xed\xa0\ +\xa7\xa1\xd1\x93\xf4\x74\x34\xb1\xf8\x84\x8f\xe5\x5c\x2b\xb2\xb1\ +\x32\x3f\x86\x7e\xdf\x3b\xb0\x82\xa2\x52\x6b\xfb\xd1\x96\x22\xfb\ +\x71\x37\xef\xec\x60\xc3\x15\x4e\xee\x89\x4d\xab\x2a\xd3\xd3\xc2\ +\xa3\xde\xf3\xb5\x59\x5a\x98\x60\x17\xae\x3d\xea\xd4\xd6\x54\x21\ +\xcc\xfd\x63\x12\x8f\x7f\xce\xae\x9a\x60\x3f\xe2\x48\x8f\x04\x48\ +\x48\x88\x35\x8c\xb2\x1e\x3c\xee\xef\x43\x17\x43\x60\x7f\xc5\xc4\ +\xc4\xc8\x10\xbd\x87\x74\x1c\xf2\xbb\xce\xae\xad\xab\xaf\xb6\xb6\ +\x1c\xa4\xd4\x15\xc4\xc0\xb1\x7c\x48\x5f\x3c\x7f\xca\x3e\x72\x4f\ +\x6f\xa6\xbe\xae\x66\x18\xc4\x22\x83\x0b\xd7\x1f\x31\x1c\xc7\x58\ +\x61\xe9\x19\xb9\x24\x63\xc3\x7e\xfe\x39\x9f\x0a\xa7\x52\x28\x52\ +\x1c\xe6\x7b\x8f\x5e\x29\xdd\xb2\xd6\xcb\xee\xbb\x81\xed\x7b\xd4\ +\x87\x26\x5b\x00\x91\xfd\x6b\x42\x4a\x46\x2b\xf8\x4f\xcd\xe6\x66\ +\xe6\x54\x3b\x1b\x8b\x57\x87\xfd\xae\xab\x8d\xb7\xb7\xde\x08\xcc\ +\xb9\x31\x5b\xa8\x2f\x42\x04\x93\x14\x82\x42\x5f\x1f\x49\xfb\x98\ +\x3b\x8d\x4c\x22\xb5\xee\xdc\xb8\x98\xf6\xd3\xbe\x88\x13\x92\xbf\ +\x56\x9a\x1e\x3d\x73\x2b\x8d\xb7\x0d\xc5\x47\xac\x97\xc4\x27\xe0\ +\xc1\x93\xb0\x4b\x78\x44\x43\xb6\x8f\xee\x00\x7a\x87\xd8\x1f\x07\ +\x37\x77\xb8\xcb\x04\xdb\x15\x23\x87\x0f\x3a\xd9\x2b\x01\x8f\x9e\ +\xbe\x3a\x83\x33\x47\x0e\xce\xc3\xdd\x61\xae\xa0\x87\x0d\x7c\x16\ +\x75\xa2\x57\x02\x8a\x4b\xcb\x2d\xe2\xde\xa7\x2d\x41\xef\x52\x92\ +\x12\xb5\x38\xf3\x5f\x41\x1c\x01\x27\xcf\xdd\x49\xc0\x1b\x04\xa3\ +\xae\x9b\xd3\xe8\xe5\x8f\x43\x22\xfd\x7a\x2d\x20\x3c\xea\xdd\x16\ +\xde\x06\x71\x71\xb1\x46\xde\xef\x11\x96\x66\xa7\x7e\x44\x40\xc8\ +\xcb\xd8\x07\x1f\x33\x3f\xb9\x56\x54\xd5\x88\x71\x6e\xbd\x0a\x3d\ +\x6f\xd5\x92\x99\xfa\xe4\xd0\x88\xb8\xbf\xf1\x41\x70\x33\x5b\x7a\ +\xaa\xe1\xeb\x37\x49\x67\x82\x43\xa3\x97\x78\x7a\x38\x61\x4e\xe3\ +\xac\xb9\xed\x8d\x8d\x2d\x7a\x27\xcf\xde\x49\xe0\xb3\x22\x8a\xb4\ +\x54\xc5\xf7\x98\xa9\x28\x2b\xa6\xf3\x7e\xef\x39\x72\x89\xa9\xa3\ +\xad\x2e\x71\x00\xbc\x6b\x65\x55\x6d\x33\x18\x84\xb4\x9a\x32\xbd\ +\x73\xe5\xd2\x99\x44\x2a\x55\x0a\x6b\x6d\x6f\x97\xe1\x13\xd0\xd0\ +\xd8\xa4\x2a\xc8\x14\x07\xc7\x88\x16\xcc\x72\x71\xc6\xdf\xc1\xc1\ +\x35\xb9\x39\xdb\x49\x18\x1b\xea\x62\xe5\x15\xd5\x0d\xc7\xfe\x73\ +\x5b\x02\xb9\xed\x93\xe7\xef\x72\xad\x8e\x2a\x2d\x55\xc6\x27\xa0\ +\xa3\xa3\x53\x4c\x50\x00\x4a\x17\xba\xb6\xaf\x19\x30\xd9\x67\xf4\ +\x7e\xe4\xf4\xcd\xba\x31\x36\x43\xa4\x11\x73\x8e\xb0\xeb\x01\xf5\ +\x90\x88\x68\x7c\xcb\x34\x30\xec\xfe\xe3\x97\x59\x66\x03\x0d\xee\ +\x74\xbb\xc9\x9f\x4b\xbe\x0e\x45\x30\xa5\x6b\x7f\x57\xc3\xd2\xf5\ +\x39\x29\xc7\xe6\x65\xd4\x2e\x58\xe6\x29\x21\x2e\x26\x6b\x3e\xd0\ +\x90\x33\x1e\x00\x41\xb6\xfb\xc4\x31\xeb\xd1\x7b\x62\x6a\xe6\x5e\ +\x2a\x45\x1a\xbb\x7c\x2b\x30\xbd\xae\xbe\xa1\x13\x32\xab\xb3\x1c\ +\x30\x08\x7b\xf9\x19\x17\xe0\x77\xfe\xee\x3b\x04\x6e\x11\xf2\x42\ +\x50\x1a\xb5\x21\x3f\x84\xa2\x1b\x7a\x87\xf0\x7a\x83\x37\xa2\x01\ +\xac\xe9\x0f\xf7\x26\x90\x83\x3c\xb5\xd5\xcf\x41\x40\xcf\x30\x32\ +\xd0\x09\x2a\xfd\x5a\x69\xd6\xd8\xd8\xac\xc4\x81\xa7\x28\xcf\x82\ +\xcc\x24\x1f\x60\xaa\xfa\x3f\x67\xd1\xac\xc2\xc1\x84\xfd\xb4\x5e\ +\x78\xcf\x71\x77\xc4\x99\x65\xe5\x16\x4c\x1b\x31\xcc\x8c\xcb\xbc\ +\xbc\xb2\x06\x1b\x64\xda\xff\x0e\xfe\x2d\x29\x21\x51\xff\x30\x28\ +\xe2\x9a\x96\x9a\x32\xb1\xbf\x7e\x5f\x2c\x3c\x22\x21\x9a\xb3\x45\ +\x24\xf0\x96\xb0\x12\x8d\x7f\x33\xc9\x98\xf8\x94\x63\xde\x9e\x6e\ +\xdc\xef\xac\x1c\x46\xae\xf5\x70\x33\xee\x1d\xb9\xf7\xf8\x65\xf5\ +\xce\x0d\x8b\x10\x3f\xce\x77\xf0\xcb\x18\x9b\x1e\xc5\x83\x9c\xdc\ +\x42\x75\xde\x6f\x70\x2b\xc5\xb5\xb5\x0d\x5a\xda\x1a\xaa\x71\x57\ +\x6e\x05\x66\x8f\xb2\xb6\xe0\x32\xaf\xad\x6b\xc0\x10\xc4\x21\xff\ +\x8c\x9f\xa9\x6f\x68\x1a\x06\xfb\xbd\xa6\xa9\xa9\x45\xad\xb0\xf8\ +\x8b\x41\xbf\xbe\xdf\xe4\x83\xf3\xcc\x07\xc4\xbf\xb2\x47\x02\xe8\ +\x8a\xb4\x6a\x14\xd0\xbe\x21\x91\xc1\x94\x4b\x37\x1f\x27\x12\xe1\ +\x64\xb7\xad\x5b\xc8\x37\x36\x33\x87\xa1\x3b\x5f\xce\xe5\x73\x8f\ +\x04\x8c\xb2\x1a\xbc\xf1\x55\x74\xc2\x39\x3b\x9b\x21\x5d\x7e\x8b\ +\x8c\x2d\x59\x30\x95\xc0\x62\xb5\xb2\xf7\x1f\xbf\x4c\xd8\xb4\xda\ +\xab\xeb\xc2\x36\x63\xda\x9a\xaa\x6f\x7a\x1c\x93\x2d\x87\x98\x9c\ +\xdf\xb4\xeb\x94\x9f\xa4\xb8\xb8\xb8\x95\xe5\x40\x4e\x5b\x58\x64\ +\x7c\xea\xcb\xc8\x78\x53\x49\x09\x71\x2e\xf8\xba\x1b\x10\x9a\xe6\ +\x33\xc7\xdd\xa1\x57\x41\x7f\x2f\x98\x34\x30\xdd\xb6\x69\xf7\xa9\ +\x8d\x04\x36\x81\x34\xc5\x65\xec\x11\x40\x19\x0c\xd8\x92\x68\x7c\ +\x0c\xe4\x16\x03\xc0\x2b\x37\xf5\x1a\x55\xa4\x7e\xcc\x5d\xa4\xad\ +\xa1\x26\xe9\x3d\xdb\x1d\xdb\xb8\xeb\xe4\x75\x45\x05\x5a\xdd\xea\ +\xa5\xb3\x38\x7d\x37\xef\x3f\x7b\xb7\x7a\x99\xe7\x5c\x91\x41\xff\ +\x47\x48\xa1\x8f\x9c\xfc\xbc\x2e\x14\xb7\x6f\xdb\x72\xec\xdc\xb5\ +\x00\x39\x48\xfc\x31\x46\x61\x49\x45\x51\xf1\x17\x55\x25\x45\x5a\ +\xd6\x4f\x09\xb0\x1e\x66\xe6\x76\xe6\xd2\xfd\x13\x0e\x76\x23\x34\ +\x5a\x98\x4c\x19\x27\xfb\x11\xf5\x00\x9e\x1f\x46\xc6\x24\x4c\x80\ +\xa4\x5b\x8b\x2f\xa2\x89\xc2\x45\xc2\xe8\x53\x41\xf1\xe8\x98\xb8\ +\x94\x15\x59\xb9\x0c\x67\x61\x9e\x17\x05\x2c\x2f\x4f\xb7\x09\x3d\ +\xc9\x80\x7e\x49\xcc\xff\x1e\xa1\xb4\xe1\x59\x58\xec\xbe\xf6\xf6\ +\x0e\x89\x6e\x01\x4e\x49\xe1\x83\xa9\xb1\xbe\x3f\x84\x85\x27\x6a\ +\x2a\xf4\x14\xd8\x0b\x42\x76\x5e\xc1\xf8\xd0\xf0\xb8\xdd\xda\x5a\ +\xaa\xb1\x90\xb3\x3c\xfb\xbf\x2c\x00\x45\x81\x3b\x0f\x9f\xdf\x4a\ +\xfd\x90\xe3\x21\xd8\x87\x20\xd9\x94\x49\x63\x17\x82\xcd\xb0\xf0\ +\xb6\xf8\x84\x0f\x0b\x01\xfb\xbd\x15\x5c\x24\x44\xf8\xca\x2d\x6b\ +\xbd\xd5\x20\x2d\x6c\xfb\x9f\x2d\x20\xe6\x6d\xca\x9f\x08\x1f\x76\ +\x4f\x0a\xb4\xc2\xbc\x20\x5b\x04\xaf\xd6\xc1\xdb\x8e\x83\x56\x11\ +\xc5\x08\x45\x74\x82\xa3\x47\x5a\x1c\xfc\xed\x0b\x40\x36\x7d\xfc\ +\xec\xed\xe4\xaf\xe5\x55\xc6\x82\x83\x20\xcf\xda\x64\x67\x33\x74\ +\x9f\x30\x06\x28\x05\x3e\x70\xf2\x5a\x2e\xc4\x03\xba\xb0\x7e\xb8\ +\xd5\xc3\x7f\xbb\x09\xb5\x30\x59\xf2\xfb\x8f\x5d\x61\xa0\x67\x37\ +\xef\x6c\x61\x72\x41\x94\xf2\x78\x59\x63\xd3\xaa\x05\xda\x00\x4a\ +\x8a\x9b\x5b\x98\x7d\xba\x8f\x20\xb0\x7b\xab\x5c\x45\x65\xad\x41\ +\x69\x59\xb9\x65\x6d\x5d\xa3\xa1\x18\x99\xc4\x6c\xef\xe8\x60\x2a\ +\xd1\x69\x19\xba\xda\x1a\x91\x5c\x47\x8d\xec\x1d\xd5\xb0\x85\x29\ +\x8f\x08\x52\xee\x9d\xff\x26\x08\x79\x9f\x49\xe3\x47\xad\x06\xf8\ +\x75\x55\xb0\x4f\x5d\x8d\x9e\xf4\x23\xca\x02\x3c\xe8\x17\x1b\x9f\ +\x72\x36\x3a\x2e\xc5\x1e\xe5\xa8\x70\x7f\x50\xb9\x11\xa3\xc9\xcb\ +\x00\x1a\x56\x40\xd0\x02\x83\x0d\x42\xe8\x17\x8b\x7e\x9b\xca\x66\ +\xb6\xb0\xb2\x2d\xcc\x0c\x4f\x93\x43\x5e\xc6\x1c\x44\x05\x41\x61\ +\x4c\x11\x1a\x83\x5f\xc9\x8f\x28\x40\xa3\xc9\x32\x84\xb5\x0f\x35\ +\x37\xbe\x22\x6a\x0e\x04\x6d\xcd\xdb\xfe\xcf\x62\x21\xf4\x69\xca\ +\xca\x50\xb0\x89\x8e\x36\x9c\xc0\x02\xf0\x11\x4c\xba\x03\x7b\x9f\ +\x94\x91\x99\x99\xcb\xc0\xc0\xbb\x19\x59\x0f\x1b\x84\x2a\x31\x70\ +\x19\x31\x0c\xf2\x37\x42\xf4\x9b\x64\x03\x94\xb0\x90\x01\xa8\xce\ +\x16\x25\x00\xee\x85\xf8\x8f\x1e\x37\xca\xa3\x05\xdb\x1c\xc6\x58\ +\x6d\x03\xc5\x4a\x85\x14\x53\xdc\x01\x18\xfb\xb7\xb6\xb6\x12\x27\ +\x3a\x8e\xc2\x16\xcd\x9b\xc2\xed\x2b\x2e\xfd\x5a\x7d\xf1\xfa\x63\ +\x12\x84\xdf\x4c\x4d\x75\xa5\xf7\x03\x8d\xf5\x13\x60\x21\x57\x5a\ +\x5b\x59\x44\x5e\x1e\xb2\xb2\x14\xe4\x05\xa5\xc8\x4c\x66\xab\x9c\ +\x28\xa5\x1a\x9b\x9a\x95\xe0\x68\xb5\x50\x89\xf6\x7b\xca\xa7\xa4\ +\xe7\xcc\x78\x13\x9f\xea\x2b\xe8\x6e\xd1\x7f\x51\x78\xdb\xaa\xaa\ +\x6b\x4d\x4f\x5d\xbc\x9f\x04\x32\xc9\x0b\x3c\x5d\x51\xb9\x83\xdb\ +\xd7\xda\xda\x86\x9d\xbd\xe2\xff\xa9\xe4\x4b\xb9\xee\x8c\xc9\x8e\ +\xb3\x21\x2b\xe0\x14\xd7\xb2\x73\x0b\xd6\x80\x1e\xc4\xc6\x26\x26\ +\x77\x2c\x93\xc9\x62\x07\x3e\x7b\xdd\x02\x9b\x53\x4b\x36\x33\xd1\ +\xbf\x9f\x94\x9a\xe5\x29\x4a\xb9\xa0\xe7\xd1\x47\x66\x7b\x38\x4d\ +\x13\xd5\x8f\x5c\x2e\x72\xbd\x02\xe5\xe5\xd5\x82\x25\x2d\xff\x27\ +\x61\x31\xef\x92\x3e\x5a\x83\x4b\x85\x14\x71\x24\x1f\x0f\xb0\xeb\ +\xd6\x23\xa7\x6f\x10\x15\x68\x72\x6d\x7b\xb6\xf8\x4a\xe1\x31\x06\ +\xcc\x48\x02\x92\x80\x7d\x80\x17\x61\x43\x0c\x51\x7c\xc2\x9e\x85\ +\xc5\x64\x15\x7d\x2e\xab\xea\x43\x93\x25\x2e\x9e\x3f\xd5\x96\xec\ +\xe1\xee\x38\xa7\xae\xae\x51\x03\xc1\x04\x61\x0a\xa6\x67\xe4\x4e\ +\xdd\x7d\xf8\x62\x29\xda\x15\x3d\x5d\xcd\x70\x3c\x2b\x81\xe8\xbc\ +\x37\x21\x39\x63\x3e\xef\x58\x0d\x35\xe5\x84\x85\x73\xdd\xed\x91\ +\x67\xe2\x75\xcf\xe0\x24\x60\xf3\xeb\x64\xd6\xf8\xce\xc6\x94\xe9\ +\x7d\x04\x61\x39\x1b\x92\xb8\x0f\x06\x7a\x7d\x8b\xe7\xcf\x9c\xe4\ +\xca\xdb\xf7\x34\x34\xe6\x04\x91\x4d\xac\x01\x07\xa3\x04\xe9\x54\ +\x2c\x89\x48\x68\xd7\xd1\xd6\x78\x0d\xf1\xe8\x20\x9e\xc4\x93\x51\ +\xbe\x85\x8a\xad\xd5\x35\xf5\x3a\x37\xee\x3d\x7d\x58\xf2\xa5\xc2\ +\x5c\x08\xf6\x57\x15\xac\xa9\x72\x9d\x24\x81\xd0\x39\x6a\xc4\xe0\ +\x23\xe3\xc7\x8e\xd8\x2c\x18\x71\x51\xd5\x12\x32\xd3\x2a\x29\x49\ +\x71\x99\xcd\x6b\xbc\x31\x2a\x45\x4a\x58\x6d\xbc\x02\xf8\xeb\x6f\ +\x5b\xe7\xd3\xad\x4c\xe4\xea\x64\xbb\x18\xfd\x5a\x5a\x58\x34\xb8\ +\xab\x9b\xe0\xee\x38\x47\x44\xbf\xdb\x12\x9f\x98\xbe\x59\x49\x51\ +\xa1\x91\x4a\x95\x7c\x41\xe6\xa9\x8c\x31\xf0\x92\x10\xda\xb5\xdc\ +\xfc\x22\x7b\xb0\xbf\x09\x5f\xca\x2a\xcd\xea\x1a\x1a\xd5\x11\xce\ +\x41\xee\x52\xb1\x8f\x5c\x9e\x96\x86\xea\x5b\x93\x01\xfd\x02\xe8\ +\x0a\xb4\x9c\xef\xdd\x8d\x07\x4f\xc2\xa2\x60\xeb\x65\x56\x2c\xfe\ +\x43\xa8\xf2\xef\x12\x33\xea\xc0\x5d\xe6\x3a\xd8\x59\xf9\xa1\xd4\ +\x5b\xa0\xc8\xa6\x88\xee\x04\x89\x48\x92\x6d\x61\xb1\x50\xa5\x15\ +\x9b\x3c\x69\x0c\xe6\x39\xdd\x89\xb3\x6f\xc9\x69\xd9\x84\xc4\xd4\ +\x2c\xaa\x50\x2c\x84\x76\x12\x01\xb1\x9f\x01\x63\xb0\xab\x6a\x60\ +\x62\x23\xcd\x4c\x0c\x30\x75\x55\x25\xa1\x63\x5a\x98\x2d\x79\xa8\ +\xbc\xeb\x60\x37\x7c\x3b\x6f\xfb\x97\xaf\x95\x56\xfe\x81\x61\x51\ +\x10\x43\xc4\xa6\xb9\x3a\x60\x00\x5f\xba\xcd\x85\xac\xa4\x05\xa0\ +\xca\x30\xf2\xef\x0a\xf1\xa0\x84\x29\x28\xde\x01\xf7\x86\x24\xba\ +\xb2\x2b\x4e\xfc\x67\x21\x4c\x6e\x09\x13\x4e\x7e\xd6\xbd\x80\x17\ +\x37\x54\x94\x15\x09\x1e\xdf\x92\x7e\x3e\x8a\x4f\xfc\x50\x51\x51\ +\x55\xa3\x04\xa0\x72\xd1\x6f\x5b\x00\x95\x22\x5d\x0e\x2e\x91\x54\ +\x59\x55\x23\x7a\x10\x9b\x68\x0e\xc9\x74\xc9\xe7\xe2\x72\x6b\x22\ +\x81\x44\x09\x7f\x1d\x7f\x1c\x2e\xa7\xfc\xe8\x91\x43\x21\x58\x99\ +\x09\x9d\x82\x3c\xd2\x93\x90\x48\x39\x0d\x35\xa5\x44\x94\x84\xfe\ +\xb6\x05\xa0\x32\x2b\x78\xa5\xcc\x37\xef\xd2\x8c\xc6\xd8\x58\x62\ +\x52\x52\xdd\x63\xe2\xf0\xa1\xc6\x90\x09\x1b\xab\x17\x14\x95\xac\ +\xac\xa9\x6b\xc0\xa6\xbb\x39\x40\x6e\x2f\x0f\x59\xef\x0b\x80\x16\ +\xf5\x9c\xc8\x2c\x48\xb7\x1e\x3c\xfb\x04\xee\x55\x17\xee\xc2\xf4\ +\x5e\xa7\x7c\x3f\x4a\x8b\xe6\x4d\xb6\x3c\xe4\x77\x3d\xef\xf2\xad\ +\xc7\x34\xf0\x26\x62\xb0\x20\x21\x5e\x0c\xc3\x74\xb4\xd5\x31\xc9\ +\xb2\xca\xfa\x9b\xf7\x83\xeb\xcb\x2b\x6b\x38\xb0\x66\xde\x4c\x97\ +\x6e\x63\x23\x5e\xbf\x67\x64\xe5\x16\xf4\x9b\xe6\x6a\xef\xd5\x87\ +\x26\x97\xff\xdb\x17\x00\x36\xde\x00\x09\x8d\x32\xa4\xfc\xce\x90\ +\xa5\x2d\xcf\xce\x2b\x74\xd4\xd3\xd5\xca\x07\x08\x41\x55\x52\xec\ +\x53\x0d\xb0\x41\x16\x14\x56\x42\xa5\x65\x9a\x1c\xb5\xc8\xd5\xc9\ +\x6e\xfd\xad\x07\x21\x21\x14\x8a\x94\xf8\x80\xfe\x3a\xfc\x99\xfe\ +\x87\xdc\xca\xe7\xe1\x6f\x74\x00\x07\x9d\x40\xff\x53\xfe\xa9\xa4\ +\xbb\xa7\x64\x64\xa0\x13\x8c\x7e\x2c\x56\x1b\x35\x22\xfa\xfd\xc5\ +\x9c\xbc\xc2\xc9\x48\x71\x0d\xf0\x4e\x54\xaa\x74\xbe\x32\x5d\x21\ +\x04\xa2\xf7\xca\x97\x91\x6f\xaf\x01\xe2\x14\xf7\x98\xec\x20\x58\ +\x06\xaa\x84\x85\x29\x9a\x0f\xec\x7f\xdb\x65\x82\xed\xca\x1e\xe5\ +\xc4\xbf\x8a\x62\xe3\x53\xd7\x31\x0a\x4b\xf6\xd3\x15\xe4\x89\xbe\ +\x3e\xd3\xb9\x55\xb6\xb6\xb6\x76\xdd\xab\xb7\x83\x7c\x37\xec\x3c\ +\xe9\xdb\x85\xa1\xd0\x82\xb9\xf3\x22\x63\x12\xf2\x42\x5e\xc6\xea\ +\x41\x1c\x38\x0e\x8b\x5c\xd5\xe3\xa4\xfe\x57\xd1\x40\x63\xbd\x1b\ +\x99\xd9\x0c\x97\xe2\xd2\x0a\xd3\x8c\x6c\x86\x9c\xe9\x00\x3d\x3c\ +\x97\xc0\x7c\xe6\xba\xe3\x48\x14\xc3\xef\xc9\xe7\x92\xaf\x99\x37\ +\xee\x05\xcb\x4b\x4b\x4b\x36\x2c\xf5\x9a\x36\xb2\xaf\x96\x5a\x6c\ +\xaf\xaa\x12\xbf\x8a\x64\xa8\x94\x32\xef\x39\x6e\x36\xa8\x26\xfd\ +\x28\xf8\xd5\x19\x00\x81\x86\x60\x52\xb2\x4c\x16\x4b\x16\xb0\x53\ +\x23\x20\x4c\x4e\x8d\x1a\xd5\xaf\xc5\xc4\xc4\x9a\xca\x2b\xaa\x07\ +\xfc\x31\xc5\x71\xa6\x7e\x3f\xad\xf0\xef\xf1\xfd\x2f\x9a\x21\xe5\ +\x2e\x6b\x8c\x93\x5e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +" + +qt_resource_name = b"\ +\x00\x06\ +\x07\x03\x7d\xc3\ +\x00\x69\ +\x00\x6d\x00\x61\x00\x67\x00\x65\x00\x73\ +\x00\x03\ +\x00\x00\x70\x37\ +\x00\x69\ +\x00\x6d\x00\x67\ +\x00\x07\ +\x05\xd4\x57\xa7\ +\x00\x6f\ +\x00\x67\x00\x61\x00\x2e\x00\x70\x00\x6e\x00\x67\ +" + +qt_resource_struct = b"\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\ +\x00\x00\x00\x12\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ +\x00\x00\x00\x1e\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ +" + +def qInitResources(): + QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) + +def qCleanupResources(): + QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) + +qInitResources() diff --git a/admin/Sources/Clients/ogagent/src/VERSION b/admin/Sources/Clients/ogagent/src/VERSION new file mode 100644 index 00000000..9084fa2f --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/VERSION @@ -0,0 +1 @@ +1.1.0 diff --git a/admin/Sources/Clients/ogagent/src/about-dialog.ui b/admin/Sources/Clients/ogagent/src/about-dialog.ui new file mode 100644 index 00000000..ab0cac1d --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/about-dialog.ui @@ -0,0 +1,244 @@ + + + OGAAboutDialog + + + + 0 + 0 + 466 + 402 + + + + + Verdana + 9 + + + + About OGAgent + + + + + + true + + + + 9 + + + 9 + + + + + <html><head/><body><p><img src=":/images/img/oga.png"/>OpenGnsys Agent Tools</p></body></html> + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 5 + + + + + + + + <html><head/><body><p><span style=" font-family:'Sans Serif'; font-size:9pt; font-weight:600;">OpenGnsys Agent</span></p></body></html> + + + + + + + Version 1.1.0 + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 5 + + + + + + + + 0 + + + + &About + + + + 6 + + + 9 + + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Verdana'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif'; font-weight:600;">OpenGnsys Agent for Operating Systems (OGAgent) is based on UDS Actor from Virtual Cable S.L.U.</span></p> +<p style=" margin-top:5px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif'; font-weight:600;">UDS Actor is (c) 2014, Virtual Cable S.L.U.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-style:italic;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif'; font-size:8pt; color:#000000;">More info:</span></a></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:10px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://opengnsys.es/"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">OpenGnsys Project</span></a></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:10px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://github.com/dkmstr/openuds/tree/master"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">openuds on GitHub</span></a></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';"><br /></p></body></html> + + + true + + + + + + + + A&uthors + + + + 6 + + + 9 + + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Verdana'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:5px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">OGAgent developer: Ramón M. Gómez &lt;ramongomez@us.es&gt;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans Serif';">UDS Actor developer: Adolfo Gómez García &lt;agomez@virtualcable.es&gt;</span></p> +</body></html> + + + true + + + + + + + + &License Agreement + + + + 6 + + + 9 + + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Verdana'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Copyright (c) 2014 Virtual Cable S.L.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">All rights reserved.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Redistribution and use in source and binary forms, with or without modification,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">are permitted provided that the following conditions are met:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> * Redistributions of source code must retain the above copyright notice,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> this list of conditions and the following disclaimer.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> * Redistributions in binary form must reproduce the above copyright notice,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> this list of conditions and the following disclaimer in the documentation</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> and/or other materials provided with the distribution.</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> * Neither the name of Virtual Cable S.L. nor the names of its contributors</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> may be used to endorse or promote products derived from this software</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> without specific prior written permission.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot;</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"><br /></p></body></html> + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Close + + + + + + + + + + + buttonBox + clicked(QAbstractButton*) + OGAAboutDialog + closeDialog() + + + 432 + 381 + + + 282 + 362 + + + + + + closeDialog() + + diff --git a/admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg b/admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg new file mode 100644 index 00000000..8888e88a --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/cfg/ogagent.cfg @@ -0,0 +1,21 @@ +[opengnsys] +# Listen address & port of REST +address=0.0.0.0 +port=8000 + +# This is a comma separated list of paths where to look for modules to load +path=test_modules/server + +# Remote OpenGnsys Service +remote=https://192.168.2.10/opengnsys/rest + +# Log Level, if ommited, will be set to INFO +log=DEBUG + +# Module specific +# The sections must match the module name +# This section will be passes on activation to module +#[Sample1] +#value1=Mariete +#value2=Yo +#remote=https://172.27.0.1:9999/rest diff --git a/admin/Sources/Clients/ogagent/src/cfg/ogclient.cfg b/admin/Sources/Clients/ogagent/src/cfg/ogclient.cfg new file mode 100644 index 00000000..d39fc965 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/cfg/ogclient.cfg @@ -0,0 +1,11 @@ +[opengnsys] +# Log Level, if ommited, will be set to INFO +log=DEBUG + +# Module specific +# The sections must match the module name +# This section will be passes on activation to module +#[Sample1] +#value1=Mariete +#value2=Yo +#remote=https://172.27.0.1:9999/rest diff --git a/admin/Sources/Clients/ogagent/src/img/oga-48x48.ico b/admin/Sources/Clients/ogagent/src/img/oga-48x48.ico new file mode 100644 index 00000000..37ded487 Binary files /dev/null and b/admin/Sources/Clients/ogagent/src/img/oga-48x48.ico differ diff --git a/admin/Sources/Clients/ogagent/src/img/oga-512.png b/admin/Sources/Clients/ogagent/src/img/oga-512.png new file mode 100644 index 00000000..37a0dbe4 Binary files /dev/null and b/admin/Sources/Clients/ogagent/src/img/oga-512.png differ diff --git a/admin/Sources/Clients/ogagent/src/img/oga.ico b/admin/Sources/Clients/ogagent/src/img/oga.ico new file mode 100644 index 00000000..37ded487 Binary files /dev/null and b/admin/Sources/Clients/ogagent/src/img/oga.ico differ diff --git a/admin/Sources/Clients/ogagent/src/img/oga.png b/admin/Sources/Clients/ogagent/src/img/oga.png new file mode 100644 index 00000000..70db4564 Binary files /dev/null and b/admin/Sources/Clients/ogagent/src/img/oga.png differ diff --git a/admin/Sources/Clients/ogagent/src/license.txt b/admin/Sources/Clients/ogagent/src/license.txt new file mode 100644 index 00000000..bdb7d25d --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2012-2015 Virtual Cable S.L. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Virtual Cable S.L. nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/admin/Sources/Clients/ogagent/src/message-dialog.ui b/admin/Sources/Clients/ogagent/src/message-dialog.ui new file mode 100644 index 00000000..75137037 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/message-dialog.ui @@ -0,0 +1,89 @@ + + + OGAMessageDialog + + + + 0 + 0 + 339 + 188 + + + + + 0 + 0 + + + + + Verdana + 10 + + + + UDS Actor + + + + + 10 + 10 + 321 + 171 + + + + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 15 + + + + + + + + QDialogButtonBox::Ok + + + + + + + + + + buttonBox + clicked(QAbstractButton*) + OGAMessageDialog + closeDialog() + + + 203 + 161 + + + 337 + 125 + + + + + + closeDialog() + + diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py b/admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py new file mode 100644 index 00000000..5caaf8c4 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/RESTApi.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 201 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' + +# pylint: disable-msg=E1101,W0703 + +from __future__ import unicode_literals + +import requests +import logging +import json +import warnings + +from .log import logger + +from .utils import exceptionToMessage + +VERIFY_CERT = False + + +class RESTError(Exception): + ERRCODE = 0 + + +class ConnectionError(RESTError): + ERRCODE = -1 + + +# Disable warnings log messages +try: + import urllib3 # @UnusedImport +except Exception: + from requests.packages import urllib3 # @Reimport + +try: + urllib3.disable_warnings() # @UndefinedVariable + warnings.simplefilter("ignore") +except Exception: + pass # In fact, isn't too important, but wil log warns to logging file + +class REST(object): + ''' + Simple interface to remote REST apis. + The constructor expects the "base url" as parameter, that is, the url that will be common on all REST requests + Remember that this is a helper for "easy of use". You can provide your owns using requests lib for example. + Examples: + v = REST('https://example.com/rest/v1/') (Can omit trailing / if desired) + v.sendMessage('hello?param1=1¶m2=2') + This will generate a GET message to https://example.com/rest/v1/hello?param1=1¶m2=2, and return the deserialized JSON result or an exception + v.sendMessage('hello?param1=1¶m2=2', {'name': 'mario' }) + This will generate a POST message to https://example.com/rest/v1/hello?param1=1¶m2=2, with json encoded body {'name': 'mario' }, and also returns + the deserialized JSON result or raises an exception in case of error + ''' + def __init__(self, url): + ''' + Initializes the REST helper + url is the full url of the REST API Base, as for example "https://example.com/rest/v1". + @param url The url of the REST API Base. The trailing '/' can be included or omitted, as desired. + ''' + self.endpoint = url + + if self.endpoint[-1] != '/': + self.endpoint += '/' + + # Some OSs ships very old python requests lib implementations, workaround them... + try: + self.newerRequestLib = requests.__version__.split('.')[0] >= '1' + except Exception: + self.newerRequestLib = False # I no version, guess this must be an old requests + + # Disable logging requests messages except for errors, ... + logging.getLogger("requests").setLevel(logging.CRITICAL) + # Tries to disable all warnings + try: + warnings.simplefilter("ignore") # Disables all warnings + except Exception: + pass + + def _getUrl(self, method): + ''' + Internal method + Composes the URL based on "method" + @param method: Method to append to base url for composition + ''' + url = self.endpoint + method + + return url + + def _request(self, url, data=None): + ''' + Launches the request + @param url: The url to obtain + @param data: if None, the request will be sent as a GET request. If != None, the request will be sent as a POST, with data serialized as JSON in the body. + ''' + try: + if data is None: + logger.debug('Requesting using GET (no data provided) {}'.format(url)) + # Old requests version does not support verify, but they do not checks ssl certificate by default + if self.newerRequestLib: + r = requests.get(url, verify=VERIFY_CERT) + else: + r = requests.get(url) + else: # POST + logger.debug('Requesting using POST {}, data: {}'.format(url, data)) + if self.newerRequestLib: + r = requests.post(url, data=data, headers={'content-type': 'application/json'}, verify=VERIFY_CERT) + else: + r = requests.post(url, data=data, headers={'content-type': 'application/json'}) + + r = json.loads(r.content) # Using instead of r.json() to make compatible with oooold rquests lib versions + except requests.exceptions.RequestException as e: + raise ConnectionError(e) + except Exception as e: + raise ConnectionError(exceptionToMessage(e)) + + return r + + def sendMessage(self, msg, data=None, processData=True): + ''' + Sends a message to remote REST server + @param data: if None or omitted, message will be a GET, else it will send a POST + @param processData: if True, data will be serialized to json before sending, else, data will be sent as "raw" + ''' + logger.debug('Invoking post message {} with data {}'.format(msg, data)) + + if processData and data is not None: + data = json.dumps(data) + + url = self._getUrl(msg) + logger.debug('Requesting {}'.format(url)) + + return self._request(url, data) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/__init__.py new file mode 100644 index 00000000..48453fb7 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/__init__.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +# On centos, old six release does not includes byte2int, nor six.PY2 +import six + +import modules +from RESTApi import REST, RESTError + +VERSION = '1.1.0' + +__title__ = 'OpenGnsys Agent' +__version__ = VERSION +__build__ = 0x010750 +__author__ = 'Adolfo Gómez' +__license__ = "BSD 3-clause" +__copyright__ = "Copyright VirtualCable S.L.U." + + +if not hasattr(six, 'byte2int'): + if six.PY3: + import operator + six.byte2int = operator.itemgetter(0) + else: + def _byte2int(bs): + return ord(bs[0]) + six.byte2int = _byte2int diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/certs.py b/admin/Sources/Clients/ogagent/src/opengnsys/certs.py new file mode 100644 index 00000000..e4c070e8 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/certs.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' + +from tempfile import gettempdir +from os.path import exists, join + +CERTFILE = 'OGAgent.pem' + + +def createSelfSignedCert(force=False): + + certFile = join(gettempdir(), CERTFILE) + + if exists(certFile) and not force: + return certFile + + certData = '''-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCb50K3mIznNklz +yVAD7xSQOSJQ6+NPXj7U9/4zLZ+TvmbQ7RqUUsxbfxHbeRnoYTWV2nKk4+tHqmvz +ujLSS/loFhTSMqtrLn7rowSYJoQhKOUkAiQlWkqCfItWgL5pJopDpNHFul9Rn3ds +PMWQTiGeUNR4Y3RnBhr1Q1BsqAzf4m6zFUmgLPPmVLdF4uJ3Tuz8TSy2gWLs5aSr +5do4WamwUfYjRSVMJECmwjUM4rQ8SQgg0sHBeBuDUGNBvBQFac1G7qUcMReeu8Zr +DUtMsXma/l4rA8NB5CRmTrQbTBF4l+jb2BDFebDqDUK1Oqs9X35yOQfDOAFYHiix +PX0IsXOZAgMBAAECggEBAJi3000RrIUZUp6Ph0gzPMuCjDEEwWiQA7CPNX1gpb8O +dp0WhkDhUroWIaICYPSXtOwUTtVjRqivMoxPy1Thg3EIoGC/rdeSdlXRHMEGicwJ +yVyalFnatr5Xzg5wkxVh4XMd0zeDt7e3JD7s0QLo5lm1CEzd77qz6lhzFic5/1KX +bzdULtTlq60dazg2hEbcS4OmM1UMCtRVDAsOIUIZPL0M9j1C1d1iEdYnh2xshKeG +/GOfo95xsgdMlGjtv3hUT5ryKVoEsu+36rGb4VfhPfUvvoVbRx5QZpW+QvxaYh5E +Fi0JEROozFwG31Y++8El7J3yQko8cFBa1lYYUwwpNAECgYEAykT+GiM2YxJ4uVF1 +OoKiE9BD53i0IG5j87lGPnWqzEwYBwnqjEKDTou+uzMGz3MDV56UEFNho7wUWh28 +LpEkjJB9QgbsugjxIBr4JoL/rYk036e/6+U8I95lvYWrzb+rBMIkRDYI7kbQD/mQ +piYUpuCkTymNAu2RisK6bBzJslkCgYEAxVE23OQvkCeOV8hJNPZGpJ1mDS+TiOow +oOScMZmZpail181eYbAfMsCr7ri812lSj98NvA2GNVLpddil6LtS1cQ5p36lFBtV +xQUMZiFz4qVbEak+izL+vPaev/mXXsOcibAIQ+qI/0txFpNhJjpaaSy6vRCBYFmc +8pgSoBnBI0ECgYAUKCn2atnpp5aWSTLYgNosBU4vDA1PShD14dnJMaqyr0aZtPhF +v/8b3btFJoGgPMLxgWEZ+2U4ju6sSFhPf7FXvLJu2QfQRkHZRDbEh7t5DLpTK4Fp +va9vl6Ml7uM/HsGpOLuqfIQJUs87OFCc7iCSvMJDDU37I7ekT2GKkpfbCQKBgBrE +0NeY0WcSJrp7/oqD2sOcYurpCG/rrZs2SIZmGzUhMxaa0vIXzbO59dlWELB8pmnE +Tf20K//x9qA5OxDe0PcVPukdQlH+/1zSOYNliG44FqnHtyd1TJ/gKVtMBiAiE4uO +aSClod5Yosf4SJbCFd/s5Iyfv52NqsAyp1w3Aj/BAoGAVCnEiGUfyHlIR+UH4zZW +GXJMeqdZLfcEIszMxLePkml4gUQhoq9oIs/Kw+L1DDxUwzkXN4BNTlFbOSu9gzK1 +dhuIUGfS6RPL88U+ivC3A0y2jT43oUMqe3hiRt360UQ1GXzp2dMnR9odSRB1wHoO +IOjEBZ8341/c9ZHc5PCGAG8= +-----END PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIJAIrEIthCfxUCMA0GCSqGSIb3DQEBCwUAMIGNMQswCQYD +VQQGEwJFUzEPMA0GA1UECAwGTWFkcmlkMREwDwYDVQQHDAhBbGNvcmNvbjEMMAoG +A1UECgwDVURTMQ4wDAYDVQQLDAVBY3RvcjESMBAGA1UEAwwJVURTIEFjdG9yMSgw +JgYJKoZIhvcNAQkBFhlzdXBwb3J0QHVkc2VudGVycHJpc2UuY29tMB4XDTE0MTAy +NjIzNDEyNFoXDTI0MTAyMzIzNDEyNFowgY0xCzAJBgNVBAYTAkVTMQ8wDQYDVQQI +DAZNYWRyaWQxETAPBgNVBAcMCEFsY29yY29uMQwwCgYDVQQKDANVRFMxDjAMBgNV +BAsMBUFjdG9yMRIwEAYDVQQDDAlVRFMgQWN0b3IxKDAmBgkqhkiG9w0BCQEWGXN1 +cHBvcnRAdWRzZW50ZXJwcmlzZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCb50K3mIznNklzyVAD7xSQOSJQ6+NPXj7U9/4zLZ+TvmbQ7RqUUsxb +fxHbeRnoYTWV2nKk4+tHqmvzujLSS/loFhTSMqtrLn7rowSYJoQhKOUkAiQlWkqC +fItWgL5pJopDpNHFul9Rn3dsPMWQTiGeUNR4Y3RnBhr1Q1BsqAzf4m6zFUmgLPPm +VLdF4uJ3Tuz8TSy2gWLs5aSr5do4WamwUfYjRSVMJECmwjUM4rQ8SQgg0sHBeBuD +UGNBvBQFac1G7qUcMReeu8ZrDUtMsXma/l4rA8NB5CRmTrQbTBF4l+jb2BDFebDq +DUK1Oqs9X35yOQfDOAFYHiixPX0IsXOZAgMBAAGjUDBOMB0GA1UdDgQWBBRShS90 +5lJTNvYPIEqP3GxWwG5iiDAfBgNVHSMEGDAWgBRShS905lJTNvYPIEqP3GxWwG5i +iDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAU0Sp4gXhQmRVzq+7+ +vRFUkQuPj4Ga/d9r5Wrbg3hck3+5pwe9/7APoq0P/M0DBhQpiJKjrD6ydUevC+Y/ +43ZOJPhMlNw0o6TdQxOkX6FDwQanLLs7sfvJvqtVzYn3nuRFKT3dvl7Zg44QMw2M +ay42q59fAcpB4LaDx/i7gOYSS5eca3lYW7j7YSr/+ozXK2KlgUkuCUHN95lOq+dF +trmV9mjzM4CNPZqKSE7kpHRywgrXGPCO000NvEGSYf82AtgRSFKiU8NWLQSEPdcB +k//2dsQZw2cRZ8DrC2B6Tb3M+3+CA6wVyqfqZh1SZva3LfGvq/C+u+ItguzPqNpI +xtvM +-----END CERTIFICATE-----''' + with open(certFile, "wt") as f: + f.write(certData) + + return certFile diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/config.py b/admin/Sources/Clients/ogagent/src/opengnsys/config.py new file mode 100644 index 00000000..c86c6979 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/config.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +# pylint: disable=unused-wildcard-import, wildcard-import +from __future__ import unicode_literals + +from ConfigParser import SafeConfigParser +from .log import logger + +config = None + +def readConfig(client=False): + ''' + Reads configuration file + If client is False, will read ogagent.cfg as configuration + If client is True, will read ogclient.cfg as configuration + + This is this way so we can protect ogagent.cfg against reading for non admin users on all platforms. + ''' + cfg = SafeConfigParser() + if client is True: + fname = 'ogclient.cfg' + else: + fname = 'ogagent.cfg' + + if len(cfg.read('cfg/{}'.format(fname))) == 0: + # No configuration found + return None + + return cfg + \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/httpserver.py b/admin/Sources/Clients/ogagent/src/opengnsys/httpserver.py new file mode 100644 index 00000000..a06ae6bb --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/httpserver.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +# pylint: disable=unused-wildcard-import,wildcard-import +from __future__ import unicode_literals, print_function + +# Pydev can't parse "six.moves.xxxx" because it is loaded lazy +import six +from six.moves.socketserver import ThreadingMixIn # @UnresolvedImport +from six.moves.BaseHTTPServer import BaseHTTPRequestHandler # @UnresolvedImport +from six.moves.BaseHTTPServer import HTTPServer # @UnresolvedImport +from six.moves.urllib.parse import unquote # @UnresolvedImport + +import json +import threading +import ssl + +from .utils import exceptionToMessage +from .certs import createSelfSignedCert +from .log import logger + +class HTTPServerHandler(BaseHTTPRequestHandler): + service = None + protocol_version = 'HTTP/1.0' + server_version = 'OpenGnsys Agent Server' + sys_version = '' + + def sendJsonError(self, code, message): + self.send_response(code) + self.send_header('Content-type', 'application/json') + self.end_headers() + self.wfile.write(json.dumps({'error': message})) + return + + def sendJsonResponse(self, data): + self.send_response(200) + data = json.dumps(data) + self.send_header('Content-type', 'application/json') + self.send_header('Content-Length', len(data)) + self.end_headers() + # Send the html message + self.wfile.write(data) + + + # parseURL + def parseUrl(self): + # Very simple path & params splitter + path = self.path.split('?')[0][1:].split('/') + + try: + params = dict((v[0], unquote(v[1])) for v in (v.split('=') for v in self.path.split('?')[1].split('&'))) + except Exception: + params = {} + + for v in self.service.modules: + if v.name == path[0]: # Case Sensitive!!!! + return (v, path[1:], params) + + return (None, path, params) + + def notifyMessage(self, module, path, getParams, postParams): + ''' + Locates witch module will process the message based on path (first folder on url path) + ''' + try: + data = module.processServerMessage(path, getParams, postParams, self) + self.sendJsonResponse(data) + except Exception as e: + logger.exception() + self.sendJsonError(500, exceptionToMessage(e)) + + def do_GET(self): + module, path, params = self.parseUrl() + + self.notifyMessage(module, path, params, None) + + def do_POST(self): + module, path, getParams = self.parseUrl() + + # Tries to get JSON content (UTF-8 encoded) + try: + length = int(self.headers.getheader('content-length')) + content = self.rfile.read(length).decode('utf-8') + logger.debug('length: {}, content >>{}<<'.format(length, content)) + postParams = json.loads(content) + except Exception as e: + self.sendJsonError(500, exceptionToMessage(e)) + + self.notifyMessage(module, path, getParams, postParams) + + + def log_error(self, fmt, *args): + logger.error('HTTP ' + fmt % args) + + def log_message(self, fmt, *args): + logger.info('HTTP ' + fmt % args) + + +class HTTPThreadingServer(ThreadingMixIn, HTTPServer): + pass + +class HTTPServerThread(threading.Thread): + def __init__(self, address, service): + super(self.__class__, self).__init__() + + HTTPServerHandler.service = service # Keep tracking of service so we can intercact with it + + self.certFile = createSelfSignedCert() + self.server = HTTPThreadingServer(address, HTTPServerHandler) + self.server.socket = ssl.wrap_socket(self.server.socket, certfile=self.certFile, server_side=True) + + logger.debug('Initialized HTTPS Server thread on {}'.format(address)) + + def getServerUrl(self): + return 'https://{}:{}/'.format(self.server.server_address[0], self.server.server_address[1]) + + def stop(self): + self.server.shutdown() + + def run(self): + self.server.serve_forever() + + diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/ipc.py b/admin/Sources/Clients/ogagent/src/opengnsys/ipc.py new file mode 100644 index 00000000..dd3663df --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/ipc.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import socket +import threading +import six +import traceback +import json + +from opengnsys.utils import toUnicode +from opengnsys.log import logger + +# The IPC Server will wait for connections from clients +# Clients will open socket, and wait for data from server +# The messages sent (from server) will be the following (subject to future changes): +# Message_id Data Action +# ------------ -------- -------------------------- +# MSG_LOGOFF None Logout user from session +# MSG_MESSAGE message,level Display a message with level (INFO, WARN, ERROR, FATAL) # TODO: Include level, right now only has message +# MSG_POPUP title,message Display a popup box with a title +# MSG_SCRIPT python script Execute an specific python script INSIDE CLIENT environment (this messages is not sent right now) +# The messages received (sent from client) will be the following: +# Message_id Data Action +# ------------ -------- -------------------------- +# REQ_LOGOUT Logout user from session +# REQ_INFORMATION None Request information from ipc server (maybe configuration parameters in a near future) +# REQ_LOGIN python script Execute an specific python script INSIDE CLIENT environment (this messages is not sent right now) +# +# All messages are in the form: +# BYTE +# 0 1-2 3 4 ... +# MSG_ID DATA_LENGTH (little endian) Data (can be 0 length) +# With a previos "MAGIC" header in fron of each message + +# Client messages +MSG_LOGOFF = 0xA1 # Request log off from an user +MSG_MESSAGE = 0xB2 +MSG_POPUP = 0xB3 +MSG_SCRIPT = 0xC3 + +# Request messages +REQ_MESSAGE = 0xD4 +REQ_POPUP = 0xD5 +REQ_LOGIN = 0xE5 +REQ_LOGOUT = 0xF6 + +# Reverse msgs dict for debugging +REV_DICT = { + MSG_LOGOFF: 'MSG_LOGOFF', + MSG_MESSAGE: 'MSG_MESSAGE', + MSG_POPUP: 'MSG_POPUP', + MSG_SCRIPT: 'MSG_SCRIPT', + REQ_LOGIN: 'REQ_LOGIN', + REQ_LOGOUT: 'REQ_LOGOUT', + REQ_MESSAGE: 'REQ_MESSAGE' +} + +MAGIC = b'\x4F\x47\x41\x00' # OGA in hexa with a padded 0 to the right + + +# States for client processor +ST_SECOND_BYTE = 0x01 +ST_RECEIVING = 0x02 +ST_PROCESS_MESSAGE = 0x02 + + +class ClientProcessor(threading.Thread): + def __init__(self, parent, clientSocket): + super(self.__class__, self).__init__() + self.parent = parent + self.clientSocket = clientSocket + self.running = False + self.messages = six.moves.queue.Queue(32) # @UndefinedVariable + + def stop(self): + logger.debug('Stoping client processor') + self.running = False + + def processRequest(self, msg, data): + logger.debug('Got Client message {}={}'.format(msg, REV_DICT.get(msg))) + if self.parent.clientMessageProcessor is not None: + self.parent.clientMessageProcessor(msg, data) + + def run(self): + self.running = True + self.clientSocket.setblocking(0) + + state = None + recv_msg = None + recv_data = None + while self.running: + try: + counter = 1024 + while counter > 0: # So we process at least the incoming queue every XX bytes readed + counter -= 1 + b = self.clientSocket.recv(1) + if b == b'': + # Client disconnected + self.running = False + break + buf = six.byte2int(b) # Empty buffer, this is set as non-blocking + if state is None: + if buf in (REQ_MESSAGE, REQ_LOGIN, REQ_LOGOUT): + logger.debug('State set to {}'.format(buf)) + state = buf + recv_msg = buf + continue # Get next byte + else: + logger.debug('Got unexpected data {}'.format(buf)) + elif state in (REQ_MESSAGE, REQ_LOGIN, REQ_LOGOUT): + logger.debug('First length byte is {}'.format(buf)) + msg_len = buf + state = ST_SECOND_BYTE + continue + elif state == ST_SECOND_BYTE: + msg_len += buf << 8 + logger.debug('Second length byte is {}, len is {}'.format(buf, msg_len)) + if msg_len == 0: + self.processRequest(recv_msg, None) + state = None + break + state = ST_RECEIVING + recv_data = b'' + continue + elif state == ST_RECEIVING: + recv_data += six.int2byte(buf) + msg_len -= 1 + if msg_len == 0: + self.processRequest(recv_msg, recv_data) + recv_data = None + state = None + break + else: + logger.debug('Got invalid message from request: {}, state: {}'.format(buf, state)) + except socket.error as e: + # If no data is present, no problem at all, pass to check messages + pass + except Exception as e: + tb = traceback.format_exc() + logger.error('Error: {}, trace: {}'.format(e, tb)) + + if self.running is False: + break + + try: + msg = self.messages.get(block=True, timeout=1) + except six.moves.queue.Empty: # No message got in time @UndefinedVariable + continue + + logger.debug('Got message {}={}'.format(msg, REV_DICT.get(msg[0]))) + + try: + m = msg[1] if msg[1] is not None else b'' + l = len(m) + data = MAGIC + six.int2byte(msg[0]) + six.int2byte(l & 0xFF) + six.int2byte(l >> 8) + m + try: + self.clientSocket.sendall(data) + except socket.error as e: + # Send data error + logger.debug('Socket connection is no more available: {}'.format(e.args)) + self.running = False + except Exception as e: + logger.error('Invalid message in queue: {}'.format(e)) + + logger.debug('Client processor stopped') + try: + self.clientSocket.close() + except Exception: + pass # If can't close, nothing happens, just end thread + + +class ServerIPC(threading.Thread): + + def __init__(self, listenPort, clientMessageProcessor=None): + super(self.__class__, self).__init__() + self.port = listenPort + self.running = False + self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.threads = [] + self.clientMessageProcessor = clientMessageProcessor + + def stop(self): + logger.debug('Stopping Server IPC') + self.running = False + for t in self.threads: + t.stop() + socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(('localhost', self.port)) + self.serverSocket.close() + + for t in self.threads: + t.join() + + def sendMessage(self, msgId, msgData): + ''' + Notify message to all listening threads + ''' + logger.debug('Sending message {}({}),{} to all clients'.format(msgId, REV_DICT.get(msgId), msgData)) + + # Convert to bytes so length is correctly calculated + if isinstance(msgData, six.text_type): + msgData = msgData.encode('utf8') + + for t in self.threads: + if t.isAlive(): + logger.debug('Sending to {}'.format(t)) + t.messages.put((msgId, msgData)) + + def sendLoggofMessage(self): + self.sendMessage(MSG_LOGOFF, '') + + def sendMessageMessage(self, message): + self.sendMessage(MSG_MESSAGE, message) + + def sendPopupMessage(self, title, message): + self.sendMessage(MSG_POPUP, {'title':title, 'message':message}) + + def sendScriptMessage(self, script): + self.sendMessage(MSG_SCRIPT, script) + + def cleanupFinishedThreads(self): + ''' + Cleans up current threads list + ''' + aliveThreads = [] + for t in self.threads: + if t.isAlive(): + logger.debug('Thread {} is alive'.format(t)) + aliveThreads.append(t) + self.threads[:] = aliveThreads + + def run(self): + self.running = True + + self.serverSocket.bind(('localhost', self.port)) + self.serverSocket.setblocking(1) + self.serverSocket.listen(4) + + while True: + try: + (clientSocket, address) = self.serverSocket.accept() + # Stop processing if thread is mean to stop + if self.running is False: + break + logger.debug('Got connection from {}'.format(address)) + + self.cleanupFinishedThreads() # House keeping + + logger.debug('Starting new thread, current: {}'.format(self.threads)) + t = ClientProcessor(self, clientSocket) + self.threads.append(t) + t.start() + except Exception as e: + logger.error('Got an exception on Server ipc thread: {}'.format(e)) + + +class ClientIPC(threading.Thread): + def __init__(self, listenPort): + super(ClientIPC, self).__init__() + self.port = listenPort + self.running = False + self.clientSocket = None + self.messages = six.moves.queue.Queue(32) # @UndefinedVariable + + self.connect() + + def stop(self): + self.running = False + + def getMessage(self): + while self.running: + try: + return self.messages.get(timeout=1) + except six.moves.queue.Empty: # @UndefinedVariable + continue + + return None + + def sendRequestMessage(self, msg, data=None): + logger.debug('Sending request for msg: {}({}), {}'.format(msg, REV_DICT.get(msg), data)) + if data is None: + data = b'' + + if isinstance(data, six.text_type): # Convert to bytes if necessary + data = data.encode('utf-8') + + l = len(data) + msg = six.int2byte(msg) + six.int2byte(l & 0xFF) + six.int2byte(l >> 8) + data + self.clientSocket.sendall(msg) + + def sendLogin(self, username, language): + self.sendRequestMessage(REQ_LOGIN, username+','+language) + + def sendLogout(self, username): + self.sendRequestMessage(REQ_LOGOUT, username) + + def sendMessage(self, module, message, data=None): + ''' + Sends a message "message" with data (data will be encoded as json, so ensure that it is serializable) + @param module: Module that will receive this message + @param message: Message to send. This message is "customized", and understand by modules + @param data: Data to be send as message companion + ''' + msg = '\0'.join((module, message, json.dumps(data))) + self.sendRequestMessage(REQ_MESSAGE, msg) + + def messageReceived(self): + ''' + Override this method to automatically get notified on new message + received. Message is at self.messages queue + ''' + pass + + def receiveBytes(self, number): + msg = b'' + while self.running and len(msg) < number: + try: + buf = self.clientSocket.recv(number - len(msg)) + if buf == b'': + logger.debug('Buf {}, msg {}({})'.format(buf, msg, REV_DICT.get(msg))) + self.running = False + break + msg += buf + except socket.timeout: + pass + + if self.running is False: + logger.debug('Not running, returning None') + return None + return msg + + def connect(self): + self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.clientSocket.connect(('localhost', self.port)) + self.clientSocket.settimeout(2) # Static, custom socket timeout of 2 seconds for local connection (no network) + + def run(self): + self.running = True + + while self.running: + try: + msg = b'' + # We look for magic message header + while self.running: # Wait for MAGIC + try: + buf = self.clientSocket.recv(len(MAGIC) - len(msg)) + if buf == b'': + self.running = False + break + msg += buf + if len(msg) != len(MAGIC): + continue # Do not have message + if msg != MAGIC: # Skip first byte an continue searchong + msg = msg[1:] + continue + break + except socket.timeout: # Timeout is here so we can get stop thread + continue + + if self.running is False: + break + + # Now we get message basic data (msg + datalen) + msg = bytearray(self.receiveBytes(3)) + + # We have the magic header, here comes the message itself + if msg is None: + continue + + msgId = msg[0] + dataLen = msg[1] + (msg[2] << 8) + if msgId not in (MSG_LOGOFF, MSG_MESSAGE, MSG_SCRIPT): + raise Exception('Invalid message id: {}'.format(msgId)) + + data = self.receiveBytes(dataLen) + if data is None: + continue + + self.messages.put((msgId, data)) + self.messageReceived() + + except socket.error as e: + logger.error('Communication with server got an error: {}'.format(toUnicode(e.strerror))) + self.running = False + return + except Exception as e: + tb = traceback.format_exc() + logger.error('Error: {}, trace: {}'.format(e, tb)) + + try: + self.clientSocket.close() + except Exception: + pass # If can't close, nothing happens, just end thread + diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/OGAgentService.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/OGAgentService.py new file mode 100644 index 00000000..29a238da --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/OGAgentService.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from opengnsys.service import CommonService +from opengnsys.service import IPC_PORT +from opengnsys import ipc + +from opengnsys.log import logger + +from opengnsys.linux.daemon import Daemon + +import sys +import signal +import json + +try: + from prctl import set_proctitle # @UnresolvedImport +except Exception: # Platform may not include prctl, so in case it's not available, we let the "name" as is + def set_proctitle(_): + pass + + +class OGAgentSvc(Daemon, CommonService): + def __init__(self, args=None): + Daemon.__init__(self, '/var/run/opengnsys-agent.pid') + CommonService.__init__(self) + + def run(self): + logger.debug('** Running Daemon **') + set_proctitle('OGAgent') + + self.initialize() + + # Call modules initialization + # They are called in sequence, no threading is done at this point, so ensure modules onActivate always returns + + + # ********************* + # * Main Service loop * + # ********************* + # Counter used to check ip changes only once every 10 seconds, for + # example + try: + while self.isAlive: + # In milliseconds, will break + self.doWait(1000) + except (KeyboardInterrupt, SystemExit) as e: + logger.error('Requested exit of main loop') + except Exception as e: + logger.exception() + logger.error('Caught exception on main loop: {}'.format(e)) + + self.terminate() + + self.notifyStop() + + def signal_handler(self, signal, frame): + self.isAlive = False + sys.stderr.write("signal handler: {}".format(signal)) + + +def usage(): + sys.stderr.write("usage: {} start|stop|restart|fg|login 'username'|logout 'username'|message 'module' 'message' 'json'\n".format(sys.argv[0])) + sys.exit(2) + +if __name__ == '__main__': + logger.setLevel('INFO') + + if len(sys.argv) == 5 and sys.argv[1] == 'message': + logger.debug('Running client opengnsys') + client = None + try: + client = ipc.ClientIPC(IPC_PORT) + client.sendMessage(sys.argv[2], sys.argv[3], json.loads(sys.argv[4])) + sys.exit(0) + except Exception as e: + logger.error(e) + + + if len(sys.argv) == 3 and sys.argv[1] in ('login', 'logout'): + logger.debug('Running client opengnsys') + client = None + try: + client = ipc.ClientIPC(IPC_PORT) + if 'login' == sys.argv[1]: + client.sendLogin(sys.argv[2]) + sys.exit(0) + elif 'logout' == sys.argv[1]: + client.sendLogout(sys.argv[2]) + sys.exit(0) + else: + usage() + except Exception as e: + logger.error(e) + elif len(sys.argv) != 2: + usage() + + logger.debug('Executing actor') + daemon = OGAgentSvc() + + signal.signal(signal.SIGTERM, daemon.signal_handler) + signal.signal(signal.SIGINT, daemon.signal_handler) + + if len(sys.argv) == 2: + if 'start' == sys.argv[1]: + daemon.start() + elif 'stop' == sys.argv[1]: + daemon.stop() + elif 'restart' == sys.argv[1]: + daemon.restart() + elif 'fg' == sys.argv[1]: + daemon.run() + else: + usage() + sys.exit(0) + else: + usage() diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/__init__.py new file mode 100644 index 00000000..3a98c780 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/daemon.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/daemon.py new file mode 100644 index 00000000..3753808a --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/daemon.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: : http://www.jejik.com/authors/sander_marechal/ +@see: : http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ +''' + +from __future__ import unicode_literals +import sys +import os +import time +import atexit +from opengnsys.log import logger + +from signal import SIGTERM + + +class Daemon: + """ + A generic daemon class. + + Usage: subclass the Daemon class and override the run() method + """ + def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): + self.stdin = stdin + self.stdout = stdout + self.stderr = stderr + self.pidfile = pidfile + + def daemonize(self): + """ + do the UNIX double-fork magic, see Stevens' "Advanced + Programming in the UNIX Environment" for details (ISBN 0201563177) + http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 + """ + try: + pid = os.fork() + if pid > 0: + # exit first parent + sys.exit(0) + except OSError as e: + logger.error("fork #1 error: {}".format(e)) + sys.stderr.write("fork #1 failed: {}\n".format(e)) + sys.exit(1) + + # decouple from parent environment + os.chdir("/") + os.setsid() + os.umask(0) + + # do second fork + try: + pid = os.fork() + if pid > 0: + # exit from second parent + sys.exit(0) + except OSError as e: + logger.error("fork #2 error: {}".format(e)) + sys.stderr.write("fork #2 failed: {}\n".format(e)) + sys.exit(1) + + # redirect standard file descriptors + sys.stdout.flush() + sys.stderr.flush() + si = open(self.stdin, 'r') + so = open(self.stdout, 'a+') + se = open(self.stderr, 'a+', 0) + os.dup2(si.fileno(), sys.stdin.fileno()) + os.dup2(so.fileno(), sys.stdout.fileno()) + os.dup2(se.fileno(), sys.stderr.fileno()) + + # write pidfile + atexit.register(self.delpid) + pid = str(os.getpid()) + with open(self.pidfile, 'w+') as f: + f.write("{}\n".format(pid)) + + def delpid(self): + try: + os.remove(self.pidfile) + except Exception: + # Not found/not permissions or whatever... + pass + + def start(self): + """ + Start the daemon + """ + logger.debug('Starting daemon') + # Check for a pidfile to see if the daemon already runs + try: + pf = open(self.pidfile, 'r') + pid = int(pf.read().strip()) + pf.close() + except IOError: + pid = None + + if pid: + message = "pidfile {} already exist. Daemon already running?\n".format(pid) + logger.error(message) + sys.stderr.write(message) + sys.exit(1) + + # Start the daemon + self.daemonize() + try: + self.run() + except Exception as e: + logger.error('Exception running process: {}'.format(e)) + + if os.path.exists(self.pidfile): + os.remove(self.pidfile) + + def stop(self): + """ + Stop the daemon + """ + # Get the pid from the pidfile + try: + pf = open(self.pidfile, 'r') + pid = int(pf.read().strip()) + pf.close() + except IOError: + pid = None + + if pid is None: + message = "pidfile {} does not exist. Daemon not running?\n".format(self.pidfile) + logger.info(message) + # sys.stderr.write(message) + return # not an error in a restart + + # Try killing the daemon process + try: + for i in range(10): + os.kill(pid, SIGTERM) + time.sleep(1) + except OSError as err: + if err.errno == 3: # No such process + if os.path.exists(self.pidfile): + os.remove(self.pidfile) + else: + sys.stderr.write(err) + sys.exit(1) + + def restart(self): + """ + Restart the daemon + """ + self.stop() + self.start() + + # Overridables + def run(self): + """ + You should override this method when you subclass Daemon. It will be called after the process has been + daemonized by start() or restart(). + """ diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/log.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/log.py new file mode 100644 index 00000000..dc54e198 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/log.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import logging +import os +import tempfile +import six + +# Valid logging levels, from UDS Broker (uds.core.utils.log) +OTHER, DEBUG, INFO, WARN, ERROR, FATAL = (10000 * (x + 1) for x in six.moves.xrange(6)) # @UndefinedVariable + + +class LocalLogger(object): + def __init__(self): + # tempdir is different for "user application" and "service" + # service wil get c:\windows\temp, while user will get c:\users\XXX\temp + # Try to open logger at /var/log path + # If it fails (access denied normally), will try to open one at user's home folder, and if + # agaim it fails, open it at the tmpPath + + for logDir in ('/var/log', os.path.expanduser('~'), tempfile.gettempdir()): + try: + fname = os.path.join(logDir, 'opengnsys.log') + logging.basicConfig( + filename=fname, + filemode='a', + format='%(levelname)s %(asctime)s %(message)s', + level=logging.DEBUG + ) + self.logger = logging.getLogger('opengnsys') + os.chmod(fname, 0o0600) + return + except Exception: + pass + + # Logger can't be set + self.logger = None + + def log(self, level, message): + # Debug messages are logged to a file + # our loglevels are 10000 (other), 20000 (debug), .... + # logging levels are 10 (debug), 20 (info) + # OTHER = logging.NOTSET + self.logger.log(int(level / 1000) - 10, message) + + def isWindows(self): + return False + + def isLinux(self): + return True diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py new file mode 100644 index 00000000..f9534d6a --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py @@ -0,0 +1,286 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import socket +import platform +import fcntl +import os +import locale +import ctypes # @UnusedImport +import ctypes.util +import subprocess +import struct +import array +import six +from opengnsys import utils +from .renamer import rename + + +def _getMacAddr(ifname): + ''' + Returns the mac address of an interface + Mac is returned as unicode utf-8 encoded + ''' + if isinstance(ifname, list): + return dict([(name, _getMacAddr(name)) for name in ifname]) + if isinstance(ifname, six.text_type): + ifname = ifname.encode('utf-8') # If unicode, convert to bytes (or str in python 2.7) + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + info = bytearray(fcntl.ioctl(s.fileno(), 0x8927, struct.pack(str('256s'), ifname[:15]))) + return six.text_type(''.join(['%02x:' % char for char in info[18:24]])[:-1]) + except Exception: + return None + + +def _getIpAddr(ifname): + ''' + Returns the ip address of an interface + Ip is returned as unicode utf-8 encoded + ''' + if isinstance(ifname, list): + return dict([(name, _getIpAddr(name)) for name in ifname]) + if isinstance(ifname, six.text_type): + ifname = ifname.encode('utf-8') # If unicode, convert to bytes (or str in python 2.7) + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + return six.text_type(socket.inet_ntoa(fcntl.ioctl( + s.fileno(), + 0x8915, # SIOCGIFADDR + struct.pack(str('256s'), ifname[:15]) + )[20:24])) + except Exception: + return None + + +def _getInterfaces(): + ''' + Returns a list of interfaces names coded in utf-8 + ''' + max_possible = 128 # arbitrary. raise if needed. + space = max_possible * 16 + if platform.architecture()[0] == '32bit': + offset, length = 32, 32 + elif platform.architecture()[0] == '64bit': + offset, length = 16, 40 + else: + raise OSError('Unknown arquitecture {0}'.format(platform.architecture()[0])) + + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + names = array.array(str('B'), b'\0' * space) + outbytes = struct.unpack(str('iL'), fcntl.ioctl( + s.fileno(), + 0x8912, # SIOCGIFCONF + struct.pack(str('iL'), space, names.buffer_info()[0]) + ))[0] + namestr = names.tostring() + # return namestr, outbytes + return [namestr[i:i + offset].split(b'\0', 1)[0].decode('utf-8') for i in range(0, outbytes, length)] + + +def _getIpAndMac(ifname): + ip, mac = _getIpAddr(ifname), _getMacAddr(ifname) + return (ip, mac) + + +def getComputerName(): + ''' + Returns computer name, with no domain + ''' + return socket.gethostname().split('.')[0] + + +def getNetworkInfo(): + ''' + Obtains a list of network interfaces + @return: A "generator" of elements, that are dict-as-object, with this elements: + name: Name of the interface + mac: mac of the interface + ip: ip of the interface + ''' + for ifname in _getInterfaces(): + ip, mac = _getIpAndMac(ifname) + if mac != '00:00:00:00:00:00': # Skips local interfaces + yield utils.Bunch(name=ifname, mac=mac, ip=ip) + + +def getDomainName(): + return '' + + +def getLinuxVersion(): + lv = platform.linux_distribution() + return lv[0] + ', ' + lv[1] + + +def reboot(flags=0): + ''' + Simple reboot using os command + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + # Check for OpenGnsys Client or GNU/Linux distribution. + if os.path.exists('/scripts/oginit'): + subprocess.call('source /opt/opengnsys/etc/preinit/loadenviron.sh; /opt/opengnsys/scripts/reboot', shell=True) + else: + subprocess.call(['/sbin/reboot']) + + +def poweroff(flags=0): + ''' + Simple poweroff using os command + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + # Check for OpenGnsys Client or GNU/Linux distribution. + if os.path.exists('/scripts/oginit'): + subprocess.call('source /opt/opengnsys/etc/preinit/loadenviron.sh; /opt/opengnsys/scripts/poweroff', shell=True) + else: + subprocess.call(['/sbin/poweroff']) + + +def logoff(): + ''' + Kills all curent user processes, which must send a logogof + caveat: If the user has other sessions, will also disconnect from them + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + subprocess.call(['/usr/bin/pkill', '-u', os.environ['USER']]) + + +def renameComputer(newName): + rename(newName) + + +def joinDomain(domain, ou, account, password, executeInOneStep=False): + pass + + +def changeUserPassword(user, oldPassword, newPassword): + ''' + Simple password change for user using command line + ''' + os.system('echo "{1}\n{1}" | /usr/bin/passwd {0} 2> /dev/null'.format(user, newPassword)) + + +class XScreenSaverInfo(ctypes.Structure): + _fields_ = [('window', ctypes.c_long), + ('state', ctypes.c_int), + ('kind', ctypes.c_int), + ('til_or_since', ctypes.c_ulong), + ('idle', ctypes.c_ulong), + ('eventMask', ctypes.c_ulong)] + +# Initialize xlib & xss +try: + xlibPath = ctypes.util.find_library('X11') + xssPath = ctypes.util.find_library('Xss') + xlib = ctypes.cdll.LoadLibrary(xlibPath) + xss = ctypes.cdll.LoadLibrary(xssPath) + + # Fix result type to XScreenSaverInfo Structure + xss.XScreenSaverQueryExtension.restype = ctypes.c_int + xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo) # Result in a XScreenSaverInfo structure +except Exception: # Libraries not accesible, not found or whatever.. + xlib = xss = None + + +def initIdleDuration(atLeastSeconds): + ''' + On linux we set the screensaver to at least required seconds, or we never will get "idle" + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + subprocess.call(['/usr/bin/xset', 's', '{}'.format(atLeastSeconds + 30)]) + # And now reset it + subprocess.call(['/usr/bin/xset', 's', 'reset']) + + +def getIdleDuration(): + ''' + Returns idle duration, in seconds + ''' + if xlib is None or xss is None: + return 0 # Libraries not available + + # production code might want to not hardcode the offset 16... + display = xlib.XOpenDisplay(None) + + event_base = ctypes.c_int() + error_base = ctypes.c_int() + + available = xss.XScreenSaverQueryExtension(display, ctypes.byref(event_base), ctypes.byref(error_base)) + if available != 1: + return 0 # No screen saver is available, no way of getting idle + + info = xss.XScreenSaverAllocInfo() + xss.XScreenSaverQueryInfo(display, xlib.XDefaultRootWindow(display), info) + + if info.contents.state != 0: + return 3600 * 100 * 1000 # If screen saver is active, return a high enough value + + return info.contents.idle / 1000.0 + + +def getCurrentUser(): + ''' + Returns current logged in user + ''' + return os.environ['USER'] + + +def getSessionLanguage(): + ''' + Returns the user's session language + ''' + return locale.getdefaultlocale()[0] + + +def showPopup(title, message): + ''' + Displays a message box on user's session (during 1 min). + ''' + return subprocess.call('zenity --info --timeout 60 --title "{}" --text "{}"'.format(title, message), shell=True) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/__init__.py new file mode 100644 index 00000000..27198dcf --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/__init__.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import platform +import os +import sys +import pkgutil + +from opengnsys.log import logger + +renamers = {} + + +# Renamers now are for IPv4 only addresses +def rename(newName): + distribution = platform.linux_distribution()[0].lower().strip() + if distribution in renamers: + return renamers[distribution](newName) + + # Try Debian renamer, simplest one + logger.info('Renamer for platform "{0}" not found, tryin debian renamer'.format(distribution)) + return renamers['debian'](newName) + + +# Do load of packages +def _init(): + pkgpath = os.path.dirname(sys.modules[__name__].__file__) + for _, name, _ in pkgutil.iter_modules([pkgpath]): + __import__(__name__ + '.' + name, globals(), locals()) + +_init() \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/debian.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/debian.py new file mode 100644 index 00000000..be55e003 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/debian.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from opengnsys.linux.renamer import renamers +from opengnsys.log import logger + +import os + + +def rename(newName): + ''' + Debian renamer + Expects new host name on newName + Host does not needs to be rebooted after renaming + ''' + logger.debug('using Debian renamer') + + with open('/etc/hostname', 'w') as hostname: + hostname.write(newName) + + # Force system new name + os.system('/bin/hostname %s' % newName) + + # add name to "hosts" + with open('/etc/hosts', 'r') as hosts: + lines = hosts.readlines() + with open('/etc/hosts', 'w') as hosts: + hosts.write("127.0.1.1\t%s\n" % newName) + for l in lines: + if l[:9] == '127.0.1.1': # Skips existing 127.0.1.1. if it already exists + continue + hosts.write(l) + + return True + +# All names in lower case +renamers['debian'] = rename +renamers['ubuntu'] = rename diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/opensuse.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/opensuse.py new file mode 100644 index 00000000..a2d29a5c --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/opensuse.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from opengnsys.linux.renamer import renamers +from opengnsys.log import logger + +import os + + +def rename(newName): + ''' + RH, Centos, Fedora Renamer + Expects new host name on newName + Host does not needs to be rebooted after renaming + ''' + logger.debug('using SUSE renamer') + + with open('/etc/hostname', 'w') as hostname: + hostname.write(newName) + + # Force system new name + os.system('/bin/hostname %s' % newName) + + # add name to "hosts" + with open('/etc/hosts', 'r') as hosts: + lines = hosts.readlines() + with open('/etc/hosts', 'w') as hosts: + hosts.write("127.0.1.1\t{}\n".format(newName)) + for l in lines: + if l[:9] != '127.0.1.1': # Skips existing 127.0.1.1. if it already exists + hosts.write(l) + + return True + +# All names in lower case +renamers['opensuse'] = rename +renamers['suse'] = rename diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/redhat.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/redhat.py new file mode 100644 index 00000000..8821a81c --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/renamer/redhat.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from opengnsys.linux.renamer import renamers +from opengnsys.log import logger + +import os + + +def rename(newName): + ''' + RH, Centos, Fedora Renamer + Expects new host name on newName + Host does not needs to be rebooted after renaming + ''' + logger.debug('using RH renamer') + + with open('/etc/hostname', 'w') as hostname: + hostname.write(newName) + + # Force system new name + os.system('/bin/hostname %s' % newName) + + # add name to "hosts" + with open('/etc/hosts', 'r') as hosts: + lines = hosts.readlines() + with open('/etc/hosts', 'w') as hosts: + hosts.write("127.0.1.1\t{}\n".format(newName)) + for l in lines: + if l[:9] != '127.0.1.1': # Skips existing 127.0.1.1. if it already exists + hosts.write(l) + + with open('/etc/sysconfig/network', 'r') as net: + lines = net.readlines() + with open('/etc/sysconfig/network', 'w') as net: + net.write('HOSTNAME={}\n'.format(newName)) + for l in lines: + if l[:8] != 'HOSTNAME': + net.write(l) + + return True + +# All names in lower case +renamers['centos linux'] = rename +renamers['fedora'] = rename diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/loader.py b/admin/Sources/Clients/ogagent/src/opengnsys/loader.py new file mode 100644 index 00000000..23988fca --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/loader.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +# pylint: disable=unused-wildcard-import,wildcard-import + +# This is a simple module loader, so we can add "external opengnsys" modules as addons +# Modules under "opengsnsys/modules" are always autoloaded +from __future__ import unicode_literals + +import pkgutil +import os.path + +from opengnsys.workers import ServerWorker +from opengnsys.workers import ClientWorker +from .log import logger + + +def loadModules(controller, client=False): + ''' + Load own provided modules plus the modules that are in the configuration path. + The loading order is not defined (they are loaded as found, because modules MUST be "standalone" modules + @param service: The service that: + * Holds the configuration + * Will be used to initialize modules. + ''' + + ogModules = [] + + if client is False: + from opengnsys.modules.server import OpenGnSys # @UnusedImport + from .modules import server # @UnusedImport, just used to ensure opengnsys modules are initialized + modPath = 'opengnsys.modules.server' + modType = ServerWorker + else: + from opengnsys.modules.client import OpenGnSys # @UnusedImport @Reimport + from .modules import client # @UnusedImport, just used to ensure opengnsys modules are initialized + modPath = 'opengnsys.modules.client' + modType = ClientWorker + + def addCls(cls): + logger.debug('Found module class {}'.format(cls)) + try: + if cls.name is None: + # Error, cls has no name + # Log the issue and + logger.error('Class {} has no name attribute'.format(cls)) + return + ogModules.append(cls(controller)) + except Exception as e: + logger.error('Error loading module {}'.format(e)) + + def recursiveAdd(p): + subcls = p.__subclasses__() + + if len(subcls) == 0: + addCls(p) + else: + for c in subcls: + recursiveAdd(c) + + def doLoad(paths): + for (module_loader, name, ispkg) in pkgutil.iter_modules(paths, modPath + '.'): + if ispkg: + logger.debug('Found module package {}'.format(name)) + module_loader.find_module(name).load_module(name) + + + if controller.config.has_option('opengnsys', 'path') is True: + paths = tuple(os.path.abspath(v) for v in controller.config.get('opengnsys', 'path').split(',')) + else: + paths = () + + # paths += (os.path.dirname(sys.modules[modPath].__file__),) + + logger.debug('Loading modules from {}'.format(paths)) + + # Load modules + doLoad(paths) + + # Add to list of available modules + recursiveAdd(modType) + + return ogModules diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/log.py b/admin/Sources/Clients/ogagent/src/opengnsys/log.py new file mode 100644 index 00000000..e34c0874 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/log.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import traceback +import sys +import six + +if sys.platform == 'win32': + from opengnsys.windows.log import LocalLogger # @UnusedImport +else: + from opengnsys.linux.log import LocalLogger # @Reimport + +# Valid logging levels, from UDS Broker (uds.core.utils.log) +OTHER, DEBUG, INFO, WARN, ERROR, FATAL = (10000 * (x + 1) for x in six.moves.xrange(6)) # @UndefinedVariable + +_levelName = { + 'OTHER': OTHER, + 'DEBUG': DEBUG, + 'INFO': INFO, + 'WARN': WARN, + 'ERROR': ERROR, + 'FATAL': FATAL +} + +class Logger(object): + def __init__(self): + self.logLevel = INFO + self.logger = LocalLogger() + + def setLevel(self, level): + ''' + Sets log level filter (minimum level required for a log message to be processed) + :param level: Any message with a level below this will be filtered out + ''' + if isinstance(level, six.string_types): + level = _levelName.get(level, INFO) + + self.logLevel = level # Ensures level is an integer or fails + + def log(self, level, message): + if level < self.logLevel: # Skip not wanted messages + return + + self.logger.log(level, message) + + def debug(self, message): + self.log(DEBUG, message) + + def warn(self, message): + self.log(WARN, message) + + def info(self, message): + self.log(INFO, message) + + def error(self, message): + self.log(ERROR, message) + + def fatal(self, message): + self.log(FATAL, message) + + def exception(self): + try: + tb = traceback.format_exc() + except Exception: + tb = '(could not get traceback!)' + + self.log(DEBUG, tb) + + def flush(self): + pass + + +logger = Logger() diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/macos/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/macos/__init__.py new file mode 100644 index 00000000..ee5ba4c2 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/macos/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Ramón M. Gómez, ramongomez at us dot es +''' +from __future__ import unicode_literals diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/macos/operations.py b/admin/Sources/Clients/ogagent/src/opengnsys/macos/operations.py new file mode 100644 index 00000000..ea835cea --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/macos/operations.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import socket +import platform +import fcntl +import os +import locale +import ctypes # @UnusedImport +import ctypes.util +import subprocess +import struct +import array +import six +from opengnsys import utils +import netifaces + + +def _getMacAddr(ifname): + ''' + Returns the mac address of an interface + Mac is returned as unicode utf-8 encoded + ''' + if isinstance(ifname, list): + return dict([(name, _getMacAddr(name)) for name in ifname]) + if isinstance(ifname, six.text_type): + ifname = ifname.encode('utf-8') # If unicode, convert to bytes (or str in python 2.7) + try: + return netifaces.ifaddresses(ifname)[18][0]['addr'] + except Exception: + return None + + +def _getIpAddr(ifname): + ''' + Returns the IP address of an interface + IP is returned as unicode utf-8 encoded + ''' + if isinstance(ifname, list): + return dict([(name, _getIpAddr(name)) for name in ifname]) + if isinstance(ifname, six.text_type): + ifname = ifname.encode('utf-8') # If unicode, convert to bytes (or str in python 2.7) + try: + return netifaces.ifaddresses(ifname)[2][0]['addr'] + except Exception: + return None + + +def _getInterfaces(): + ''' + Returns a list of interfaces names + ''' + return netifaces.interfaces() + + +def _getIpAndMac(ifname): + ip, mac = _getIpAddr(ifname), _getMacAddr(ifname) + return (ip, mac) + + +def getComputerName(): + ''' + Returns computer name, with no domain + ''' + return socket.gethostname().split('.')[0] + + +def getNetworkInfo(): + ''' + Obtains a list of network interfaces + @return: A "generator" of elements, that are dict-as-object, with this elements: + name: Name of the interface + mac: mac of the interface + ip: ip of the interface + ''' + for ifname in _getInterfaces(): + ip, mac = _getIpAndMac(ifname) + if mac != None and ip != None: # Skips local interfaces + yield utils.Bunch(name=ifname, mac=mac, ip=ip) + + +def getDomainName(): + return '' + + +def getMacosVersion(): + return 'macOS {}'.format(platform.mac_ver()[0]) + + +def reboot(flags=0): + ''' + Simple reboot command + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + # Exec reboot command + subprocess.call('/sbin/shutdown -r now', shell=True) + + +def poweroff(flags=0): + ''' + Simple poweroff command + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + # Exec shutdown command + subprocess.call('/sbin/shutdown -h now', shell=True) + + +def logoff(): + ''' + Simple logout using AppleScript + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + # Exec logout using AppleSctipt + subprocess.call('/usr/bin/osascript -e \'tell app "System Events" to «event aevtrlgo»\'', shell=True) + + +def renameComputer(newName): + rename(newName) + + +def joinDomain(domain, ou, account, password, executeInOneStep=False): + pass + + +def changeUserPassword(user, oldPassword, newPassword): + ''' + Simple password change for user using command line + ''' + os.system('echo "{1}\n{1}" | /usr/bin/passwd {0} 2> /dev/null'.format(user, newPassword)) + + +class XScreenSaverInfo(ctypes.Structure): + _fields_ = [('window', ctypes.c_long), + ('state', ctypes.c_int), + ('kind', ctypes.c_int), + ('til_or_since', ctypes.c_ulong), + ('idle', ctypes.c_ulong), + ('eventMask', ctypes.c_ulong)] + +# Initialize xlib & xss +try: + xlibPath = ctypes.util.find_library('X11') + xssPath = ctypes.util.find_library('Xss') + xlib = ctypes.cdll.LoadLibrary(xlibPath) + xss = ctypes.cdll.LoadLibrary(xssPath) + + # Fix result type to XScreenSaverInfo Structure + xss.XScreenSaverQueryExtension.restype = ctypes.c_int + xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo) # Result in a XScreenSaverInfo structure +except Exception: # Libraries not accesible, not found or whatever.. + xlib = xss = None + + +def initIdleDuration(atLeastSeconds): + ''' + On linux we set the screensaver to at least required seconds, or we never will get "idle" + ''' + # Workaround for dummy thread + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + subprocess.call(['/usr/bin/xset', 's', '{}'.format(atLeastSeconds + 30)]) + # And now reset it + subprocess.call(['/usr/bin/xset', 's', 'reset']) + + +def getIdleDuration(): + ''' + Returns idle duration, in seconds + ''' + if xlib is None or xss is None: + return 0 # Libraries not available + + # production code might want to not hardcode the offset 16... + display = xlib.XOpenDisplay(None) + + event_base = ctypes.c_int() + error_base = ctypes.c_int() + + available = xss.XScreenSaverQueryExtension(display, ctypes.byref(event_base), ctypes.byref(error_base)) + if available != 1: + return 0 # No screen saver is available, no way of getting idle + + info = xss.XScreenSaverAllocInfo() + xss.XScreenSaverQueryInfo(display, xlib.XDefaultRootWindow(display), info) + + if info.contents.state != 0: + return 3600 * 100 * 1000 # If screen saver is active, return a high enough value + + return info.contents.idle / 1000.0 + + +def getCurrentUser(): + ''' + Returns current logged in user + ''' + return os.environ['USER'] + + +def getSessionLanguage(): + ''' + Returns the user's session language + ''' + return locale.getdefaultlocale()[0] + + +def showPopup(title, message): + ''' + Displays a message box on user's session (during 1 min). + ''' + # Show a dialog using AppleSctipt + return subprocess.call('/usr/bin/osascript -e \'display notification "{}" with title "{}"\''.format(message, title), shell=True) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/modules/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/modules/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/modules/client/OpenGnSys/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/modules/client/OpenGnSys/__init__.py new file mode 100644 index 00000000..b840d929 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/modules/client/OpenGnSys/__init__.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Ramón M. Gómez, ramongomez at us dot es +''' +from __future__ import unicode_literals + +from opengnsys.workers import ClientWorker + +from opengnsys import operations +from opengnsys.log import logger +from opengnsys.scriptThread import ScriptExecutorThread + +class OpenGnSysWorker(ClientWorker): + name = 'opengnsys' + + def onActivation(self): + logger.debug('Activate invoked') + + def onDeactivation(self): + logger.debug('Deactivate invoked') + + # Processes script execution + def process_script(self, jsonParams): + logger.debug('Processed message: script({})'.format(jsonParams)) + thr = ScriptExecutorThread(jsonParams['code']) + thr.start() + #self.sendServerMessage('script', {'op', 'launched'}) + + def process_logoff(self, jsonParams): + logger.debug('Processed message: logoff({})'.format(jsonParams)) + operations.logoff() + + def process_popup(self, jsonParams): + logger.debug('Processed message: popup({})'.format(jsonParams)) + ret = operations.showPopup(jsonParams['title'], jsonParams['message']) + #self.sendServerMessage('popup', {'op', ret}) + diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/modules/client/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/modules/client/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py new file mode 100644 index 00000000..1438e469 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/OpenGnSys/__init__.py @@ -0,0 +1,250 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Ramón M. Gómez, ramongomez at us dot es +''' +from __future__ import unicode_literals + +import subprocess +import threading +import thread +import os +import platform +import time +import random +import string +import urllib + +from opengnsys.workers import ServerWorker +from opengnsys import REST, RESTError +from opengnsys import operations +from opengnsys.log import logger +from opengnsys.scriptThread import ScriptExecutorThread + +# Error handler decorator. +def catchBackgroundError(fnc): + def wrapper(*args, **kwargs): + this = args[0] + try: + fnc(*args, **kwargs) + except Exception as e: + this.REST.sendMessage('error?id={}'.format(kwargs.get('requestId', 'error')), {'error': '{}'.format(e)}) + return wrapper + +class OpenGnSysWorker(ServerWorker): + name = 'opengnsys' + interface = None # Binded interface for OpenGnsys + loggedin = False # User session flag + locked = {} + random = None # Random string for secure connections + length = 32 # Random string length + + def checkSecret(self, server): + ''' + Checks for received secret key and raise exception if it isn't valid. + ''' + try: + if self.random != server.headers['Authorization']: + raise Exception('Unauthorized operation') + except Exception as e: + logger.error(e) + raise Exception(e) + + def onActivation(self): + ''' + Sends OGAgent activation notification to OpenGnsys server + ''' + self.cmd = None + # Ensure cfg has required configuration variables or an exception will be thrown + self.REST = REST(self.service.config.get('opengnsys', 'remote')) + # Get network interfaces until they are active or timeout (5 minutes) + for t in range(0, 300): + try: + self.interface = list(operations.getNetworkInfo())[0] # Get first network interface + except Exception as e: + # Wait 1 sec. and retry + time.sleep(1) + finally: + # Exit loop if interface is active + if self.interface: + if t > 0: + logger.debug("Fetch connection data after {} tries".format(t)) + break + # Raise error after timeout + if not self.interface: + raise e + # Delete marking files + for f in ['ogboot.me', 'ogboot.firstboot', 'ogboot.secondboot']: + try: + os.remove(os.sep + f) + except OSError: + pass + # Generate random secret to send on activation + self.random = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(self.length)) + # Send initalization message + self.REST.sendMessage('ogagent/started', {'mac': self.interface.mac, 'ip': self.interface.ip, 'secret': self.random, 'ostype': operations.osType, 'osversion': operations.osVersion}) + + def onDeactivation(self): + ''' + Sends OGAgent stopping notification to OpenGnsys server + ''' + logger.debug('onDeactivation') + self.REST.sendMessage('ogagent/stopped', {'mac': self.interface.mac, 'ip': self.interface.ip, 'ostype': operations.osType, 'osversion': operations.osVersion}) + + def processClientMessage(self, message, data): + logger.debug('Got OpenGnsys message from client: {}, data {}'.format(message, data)) + + def onLogin(self, userData): + ''' + Sends session login notification to OpenGnsys server + ''' + user, sep, language = userData.partition(',') + logger.debug('Received login for {} with language {}'.format(user, language)) + self.loggedin = True + self.REST.sendMessage('ogagent/loggedin', {'ip': self.interface.ip, 'user': user, 'language': language, 'ostype': operations.osType, 'osversion': operations.osVersion}) + + def onLogout(self, user): + ''' + Sends session logout notification to OpenGnsys server + ''' + logger.debug('Received logout for {}'.format(user)) + self.loggedin = False + self.REST.sendMessage('ogagent/loggedout', {'ip': self.interface.ip, 'user': user}) + + def process_ogclient(self, path, getParams, postParams, server): + ''' + This method can be overriden to provide your own message proccessor, or better you can + implement a method that is called exactly as "process_" + path[0] (module name has been removed from path array) and this default processMessage will invoke it + * Example: + Imagine this invocation url (no matter if GET or POST): http://example.com:9999/Sample/mazinger/Z + The HTTP Server will remove "Sample" from path, parse arguments and invoke this method as this: + module.processMessage(["mazinger","Z"], getParams, postParams) + + This method will process "mazinger", and look for a "self" method that is called "process_mazinger", and invoke it this way: + return self.process_mazinger(["Z"], getParams, postParams) + + In the case path is empty (that is, the path is composed only by the module name, like in "http://example.com/Sample", the "process" method + will be invoked directly + + The methods must return data that can be serialized to json (i.e. Ojects are not serializable to json, basic type are) + ''' + if not path: + return "ok" + try: + operation = getattr(self, 'ogclient_' + path[0]) + except Exception: + raise Exception('Message processor for "{}" not found'.format(path[0])) + return operation(path[1:], getParams, postParams) + + def process_status(self, path, getParams, postParams, server): + ''' + Returns client status. + ''' + res = {'status': '', 'loggedin': self.loggedin} + if platform.system() == 'Linux': # GNU/Linux + # Check if it's OpenGnsys Client. + if os.path.exists('/scripts/oginit'): + # Check if OpenGnsys Client is busy. + if self.locked: + res['status'] = 'BSY' + else: + res['status'] = 'OPG' + else: + # Check if there is an active session. + res['status'] = 'LNX' + elif platform.system() == 'Windows': # Windows + # Check if there is an active session. + res['status'] = 'WIN' + elif platform.system() == 'Darwin': # Mac OS X ?? + res['status'] = 'OSX' + return res + + def process_reboot(self, path, getParams, postParams, server): + ''' + Launches a system reboot operation. + ''' + logger.debug('Received reboot operation') + self.checkSecret(server) + # Rebooting thread. + def rebt(): + operations.reboot() + threading.Thread(target=rebt).start() + return {'op': 'launched'} + + def process_poweroff(self, path, getParams, postParams, server): + ''' + Launches a system power off operation. + ''' + logger.debug('Received poweroff operation') + self.checkSecret(server) + # Powering off thread. + def pwoff(): + time.sleep(2) + operations.poweroff() + threading.Thread(target=pwoff).start() + return {'op': 'launched'} + + def process_script(self, path, getParams, postParams, server): + ''' + Processes an script execution (script should be encoded in base64) + ''' + logger.debug('Processing script request') + self.checkSecret(server) + # Decoding script. + script = urllib.unquote(postParams.get('script').decode('base64')).decode('utf8') + script = 'import subprocess; subprocess.check_output("""{}""",shell=True)'.format(script) + # Executing script. + if postParams.get('client', 'false') == 'false': + thr = ScriptExecutorThread(script) + thr.start() + else: + self.sendClientMessage('script', {'code': script}) + return {'op': 'launched'} + + def process_logoff(self, path, getParams, postParams, server): + ''' + Closes user session. + ''' + logger.debug('Received logoff operation') + self.checkSecret(server) + # Sending log off message to OGAgent client. + self.sendClientMessage('logoff', {}) + return {'op': 'sended to client'} + + def process_popup(self, path, getParams, postParams, server): + ''' + Shows a message popup on the user's session. + ''' + logger.debug('Received message operation') + self.checkSecret(server) + # Sending popup message to OGAgent client. + self.sendClientMessage('popup', postParams) + return {'op': 'launched'} + + def process_client_popup(self, params): + self.REST.sendMessage('popup_done', params) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/modules/server/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/operations.py b/admin/Sources/Clients/ogagent/src/opengnsys/operations.py new file mode 100644 index 00000000..dcfa40cb --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/operations.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +# pylint: disable=unused-wildcard-import,wildcard-import + +from __future__ import unicode_literals + +import sys +# Importing platform operations and getting operating system data. +if sys.platform == 'win32': + from .windows.operations import * # @UnusedWildImport + osType = 'Windows' + osVersion = getWindowsVersion() +else: + if sys.platform == 'darwin': + from .macos.operations import * # @UnusedWildImport + osType = 'MacOS' + osVersion = getMacosVersion().replace(',','') + else: + from .linux.operations import * # @UnusedWildImport + osType = 'Linux' + osVersion = getLinuxVersion().replace(',','') diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/scriptThread.py b/admin/Sources/Clients/ogagent/src/opengnsys/scriptThread.py new file mode 100644 index 00000000..2a6779b4 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/scriptThread.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 201 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' + +# pylint: disable-msg=E1101,W0703 + +from opengnsys.log import logger + +import threading +import six + + +class ScriptExecutorThread(threading.Thread): + def __init__(self, script): + super(ScriptExecutorThread, self).__init__() + self.script = script + + def run(self): + try: + logger.debug('Executing script: {}'.format(self.script)) + six.exec_(self.script, globals(), None) + except Exception as e: + logger.error('Error executing script: {}'.format(e)) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/service.py b/admin/Sources/Clients/ogagent/src/opengnsys/service.py new file mode 100644 index 00000000..4a44028e --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/service.py @@ -0,0 +1,249 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from .log import logger +from .config import readConfig +from .utils import exceptionToMessage + +from . import ipc +from . import httpserver +from .loader import loadModules + +import socket +import time +import json +import six + +IPC_PORT = 10398 + + +class CommonService(object): + isAlive = True + ipc = None + httpServer = None + modules = None + + def __init__(self): + logger.info('----------------------------------------') + logger.info('Initializing OpenGnsys Agent') + + # Read configuration file before proceding & ensures minimal config is there + + self.config = readConfig() + + # Get opengnsys section as dict + cfg = dict(self.config.items('opengnsys')) + + # Set up log level + logger.setLevel(cfg.get('log', 'INFO')) + + + logger.debug('Loaded configuration from opengnsys.cfg:') + for section in self.config.sections(): + logger.debug('Section {} = {}'.format(section, self.config.items(section))) + + + if logger.logger.isWindows(): + # Logs will also go to windows event log for services + logger.logger.serviceLogger = True + + self.address = (cfg.get('address', '0.0.0.0'), int(cfg.get('port', '10997'))) + self.ipcport = int(cfg.get('ipc_port', IPC_PORT)) + + self.timeout = int(cfg.get('timeout', '20')) + + logger.debug('Socket timeout: {}'.format(self.timeout)) + socket.setdefaulttimeout(self.timeout) + + # Now load modules + self.modules = loadModules(self) + logger.debug('Modules: {}'.format(list(v.name for v in self.modules))) + + def stop(self): + ''' + Requests service termination + ''' + self.isAlive = False + + # ******************************** + # * Internal messages processors * + # ******************************** + def notifyLogin(self, username): + for v in self.modules: + try: + logger.debug('Notifying login of user {} to module {}'.format(username, v.name)) + v.onLogin(username) + except Exception as e: + logger.error('Got exception {} processing login message on {}'.format(e, v.name)) + + def notifyLogout(self, username): + for v in self.modules: + try: + logger.debug('Notifying logout of user {} to module {}'.format(username, v.name)) + v.onLogout(username) + except Exception as e: + logger.error('Got exception {} processing logout message on {}'.format(e, v.name)) + + def notifyMessage(self, data): + module, message, data = data.split('\0') + for v in self.modules: + if v.name == module: # Case Sensitive!!!! + try: + logger.debug('Notifying message {} to module {} with json data {}'.format(message, v.name, data)) + v.processClientMessage(message, json.loads(data)) + return + except Exception as e: + logger.error('Got exception {} processing generic message on {}'.format(e, v.name)) + + logger.error('Module {} not found, messsage {} not sent'.format(module, message)) + + + def clientMessageProcessor(self, msg, data): + ''' + Callback, invoked from IPC, on its own thread (not the main thread). + This thread will "block" communication with agent untill finished, but this should be no problem + ''' + logger.debug('Got message {}'.format(msg)) + + if msg == ipc.REQ_LOGIN: + self.notifyLogin(data) + elif msg == ipc.REQ_LOGOUT: + self.notifyLogout(data) + elif msg == ipc.REQ_MESSAGE: + self.notifyMessage(data) + + def initialize(self): + # ****************************************** + # * Initialize listeners, modules, etc... + # ****************************************** + + if six.PY3 is False: + import threading + threading._DummyThread._Thread__stop = lambda x: 42 + + logger.debug('Starting IPC listener at {}'.format(IPC_PORT)) + self.ipc = ipc.ServerIPC(self.ipcport, clientMessageProcessor=self.clientMessageProcessor) + self.ipc.start() + + # And http threaded server + self.httpServer = httpserver.HTTPServerThread(self.address, self) + self.httpServer.start() + + # And lastly invoke modules activation + validMods = [] + for mod in self.modules: + try: + logger.debug('Activating module {}'.format(mod.name)) + mod.activate() + validMods.append(mod) + except Exception as e: + logger.exception() + logger.error("Activation of {} failed: {}".format(mod.name, exceptionToMessage(e))) + + self.modules[:] = validMods # copy instead of assignment + + logger.debug('Modules after activation: {}'.format(list(v.name for v in self.modules))) + + def terminate(self): + # First invoke deactivate on modules + for mod in reversed(self.modules): + try: + logger.debug('Deactivating module {}'.format(mod.name)) + mod.deactivate() + except Exception as e: + logger.exception() + logger.error("Deactivation of {} failed: {}".format(mod.name, exceptionToMessage(e))) + + # Remove IPC threads + if self.ipc is not None: + try: + self.ipc.stop() + except Exception: + logger.error('Couln\'t stop ipc server') + + if self.httpServer is not None: + try: + self.httpServer.stop() + except Exception: + logger.error('Couln\'t stop RESTApi server') + + self.notifyStop() + + # **************************************** + # Methods that CAN BE overridden by agents + # **************************************** + def doWait(self, miliseconds): + ''' + Invoked to wait a bit + CAN be OVERRIDDEN + ''' + time.sleep(float(miliseconds) / 1000) + + def notifyStop(self): + ''' + Overridden to log stop + ''' + logger.info('Service is being stopped') + + # *************************************************** + # * Helpers, convenient methods to facilitate comms * + # *************************************************** + def sendClientMessage(self, toModule, message, data): + ''' + Sends a message to the clients using IPC + The data is converted to json, so ensure that it is serializable. + All IPC is asynchronous, so if you expect a response, this will be sent by client using another message + + @param toModule: Module that will receive this message + @param message: Message to send + @param data: data to send + ''' + self.ipc.sendMessageMessage('\0'.join((toModule, message, json.dumps(data)))) + + def sendScriptMessage(self, script): + ''' + Sends an script to be executed by client + ''' + self.ipc.sendScriptMessage(script) + + def sendLogoffMessage(self): + ''' + Sends a logoff message to client + ''' + self.ipc.sendLoggofMessage() + + def sendPopupMessage(self, title, message): + ''' + Sends a poup box to be displayed by client + ''' + self.ipc.sendPopupMessage(title, message) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/utils.py b/admin/Sources/Clients/ogagent/src/opengnsys/utils.py new file mode 100644 index 00000000..9480a6ab --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/utils.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import sys +import six + +if sys.platform == 'win32': + _fromEncoding = 'windows-1250' +else: + _fromEncoding = 'utf-8' + + +def toUnicode(msg): + try: + if not isinstance(msg, six.text_type): + if isinstance(msg, six.binary_type): + return msg.decode(_fromEncoding, 'ignore') + return six.text_type(msg) + else: + return msg + except Exception: + try: + return six.text_type(msg) + except Exception: + return '' + + +def exceptionToMessage(e): + msg = '' + for arg in e.args: + if isinstance(arg, Exception): + msg = msg + exceptionToMessage(arg) + else: + msg = msg + toUnicode(arg) + '. ' + return msg + + +class Bunch(dict): + def __init__(self, **kw): + dict.__init__(self, kw) + self.__dict__ = self + diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/windows/OGAgentService.py b/admin/Sources/Clients/ogagent/src/opengnsys/windows/OGAgentService.py new file mode 100644 index 00000000..71716d78 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/windows/OGAgentService.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals +# pylint: disable=unused-wildcard-import, wildcard-import + +import win32serviceutil # @UnresolvedImport, pylint: disable=import-error +import win32service # @UnresolvedImport, pylint: disable=import-error +import win32security # @UnresolvedImport, pylint: disable=import-error +import win32net # @UnresolvedImport, pylint: disable=import-error +import win32event # @UnresolvedImport, pylint: disable=import-error +import win32com.client # @UnresolvedImport, @UnusedImport, pylint: disable=import-error +import pythoncom # @UnresolvedImport, pylint: disable=import-error +import servicemanager # @UnresolvedImport, pylint: disable=import-error +import os + +from opengnsys import operations +from opengnsys.service import CommonService + +from opengnsys.log import logger + +class OGAgentSvc(win32serviceutil.ServiceFramework, CommonService): + ''' + This class represents a Windows Service for managing Agent interactions + with OpenGnsys Server + ''' + _svc_name_ = "OGAgent" + _svc_display_name_ = "OpenGnsys Agent Service" + _svc_description_ = "OpenGnsys Agent for Operating Systems" + # 'System Event Notification' is the SENS service + _svc_deps_ = ['EventLog'] + + def __init__(self, args): + win32serviceutil.ServiceFramework.__init__(self, args) + CommonService.__init__(self) + self.hWaitStop = win32event.CreateEvent(None, 1, 0, None) + self._user = None + + def SvcStop(self): + self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) + self.isAlive = False + win32event.SetEvent(self.hWaitStop) + + SvcShutdown = SvcStop + + def notifyStop(self): + servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, + servicemanager.PYS_SERVICE_STOPPED, + (self._svc_name_, '')) + + def doWait(self, miliseconds): + win32event.WaitForSingleObject(self.hWaitStop, miliseconds) + + def SvcDoRun(self): + ''' + Main service loop + ''' + try: + logger.debug('running SvcDoRun') + servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, + servicemanager.PYS_SERVICE_STARTED, + (self._svc_name_, '')) + + # call the CoInitialize to allow the registration to run in an other + # thread + logger.debug('Initializing com...') + pythoncom.CoInitialize() + + # Initialize remaining service data + self.initialize() + except Exception: # Any init exception wil be caught, service must be then restarted + logger.exception() + logger.debug('Exiting service with failure status') + os._exit(-1) # pylint: disable=protected-access + + # ********************* + # * Main Service loop * + # ********************* + try: + while self.isAlive: + # Pumps & processes any waiting messages + pythoncom.PumpWaitingMessages() + win32event.WaitForSingleObject(self.hWaitStop, 1000) + except Exception as e: + logger.error('Caught exception on main loop: {}'.format(e)) + + logger.debug('Exited main loop, deregistering SENS') + + self.terminate() # Ends IPC servers + + self.notifyStop() + + +if __name__ == '__main__': + + win32serviceutil.HandleCommandLine(OGAgentSvc) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/windows/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/windows/__init__.py new file mode 100644 index 00000000..e662942e --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/windows/__init__.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import os +import sys + +# Change to application directory. +os.chdir(os.path.dirname(sys.argv[0])) + diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/windows/log.py b/admin/Sources/Clients/ogagent/src/opengnsys/windows/log.py new file mode 100644 index 00000000..745fd03f --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/windows/log.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import servicemanager # @UnresolvedImport, pylint: disable=import-error +import logging +import os +import tempfile + +# Valid logging levels, from UDS Broker (uds.core.utils.log) +OTHER, DEBUG, INFO, WARN, ERROR, FATAL = (10000 * (x + 1) for x in range(6)) + + +class LocalLogger(object): + def __init__(self): + # tempdir is different for "user application" and "service" + # service wil get c:\windows\temp, while user will get c:\users\XXX\temp + logging.basicConfig( + filename=os.path.join(tempfile.gettempdir(), 'opengnsys.log'), + filemode='a', + format='%(levelname)s %(asctime)s %(message)s', + level=logging.DEBUG + ) + self.logger = logging.getLogger('opengnsys') + self.serviceLogger = False + + def log(self, level, message): + # Debug messages are logged to a file + # our loglevels are 10000 (other), 20000 (debug), .... + # logging levels are 10 (debug), 20 (info) + # OTHER = logging.NOTSET + self.logger.log(level / 1000 - 10, message) + + if level < INFO or self.serviceLogger is False: # Only information and above will be on event log + return + + if level < WARN: # Info + servicemanager.LogInfoMsg(message) + elif level < ERROR: # WARN + servicemanager.LogWarningMsg(message) + else: # Error & Fatal + servicemanager.LogErrorMsg(message) + + def isWindows(self): + return True + + def isLinux(self): + return False diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/windows/operations.py b/admin/Sources/Clients/ogagent/src/opengnsys/windows/operations.py new file mode 100644 index 00000000..aa83c943 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/windows/operations.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +import os +import locale +import subprocess +import ctypes +from ctypes.wintypes import DWORD, LPCWSTR +import win32com.client # @UnresolvedImport, pylint: disable=import-error +import win32net # @UnresolvedImport, pylint: disable=import-error +import win32security # @UnresolvedImport, pylint: disable=import-error +import win32api # @UnresolvedImport, pylint: disable=import-error +import win32con # @UnresolvedImport, pylint: disable=import-error + +from opengnsys import utils +from opengnsys.log import logger + + +def getErrorMessage(res=0): + msg = win32api.FormatMessage(res) + return msg.decode('windows-1250', 'ignore') + + +def getComputerName(): + return win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) + + +def getNetworkInfo(): + ''' + Obtains a list of network interfaces + @return: A "generator" of elements, that are dict-as-object, with this elements: + name: Name of the interface + mac: mac of the interface + ip: ip of the interface + ''' + obj = win32com.client.Dispatch("WbemScripting.SWbemLocator") + wmobj = obj.ConnectServer("localhost", "root\cimv2") + adapters = wmobj.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IpEnabled=True") + try: + for obj in adapters: + if obj.DefaultIPGateway is None: # Skip adapters without default router + continue + for ip in obj.IPAddress: + if ':' in ip: # Is IPV6, skip this + continue + if ip is None or ip == '' or ip.startswith('169.254') or ip.startswith('0.'): # If single link ip, or no ip + continue + logger.debug('Net config found: {}=({}, {})'.format(obj.Caption, obj.MACAddress, ip)) + yield utils.Bunch(name=obj.Caption, mac=obj.MACAddress, ip=ip) + except Exception: + return + + +def getDomainName(): + ''' + Will return the domain name if we belong a domain, else None + (if part of a network group, will also return None) + ''' + # Status: + # 0 = Unknown + # 1 = Unjoined + # 2 = Workgroup + # 3 = Domain + domain, status = win32net.NetGetJoinInformation() + if status != 3: + domain = None + + return domain + + +def getWindowsVersion(): + ''' + Returns Windows version. + ''' + import _winreg + reg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion') + try: + data = '{} {}'.format(_winreg.QueryValueEx(reg, 'ProductName')[0], _winreg.QueryValueEx(reg, 'ReleaseId')[0]) + except Exception: + data = '{} {}'.format(_winreg.QueryValueEx(reg, 'ProductName')[0], _winreg.QueryValueEx(reg, 'CurrentBuildNumber')[0]) + reg.Close() + return data + + +EWX_LOGOFF = 0x00000000 +EWX_SHUTDOWN = 0x00000001 +EWX_REBOOT = 0x00000002 +EWX_FORCE = 0x00000004 +EWX_POWEROFF = 0x00000008 +EWX_FORCEIFHUNG = 0x00000010 + + +def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT): + hproc = win32api.GetCurrentProcess() + htok = win32security.OpenProcessToken(hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) + privs = ((win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED),) + win32security.AdjustTokenPrivileges(htok, 0, privs) + win32api.ExitWindowsEx(flags, 0) + +def poweroff(flags=0): + ''' + Simple poweroff command. + ''' + reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN) + +def logoff(): + win32api.ExitWindowsEx(EWX_LOGOFF) + + +def renameComputer(newName): + # Needs admin privileges to work + if ctypes.windll.kernel32.SetComputerNameExW(DWORD(win32con.ComputerNamePhysicalDnsHostname), LPCWSTR(newName)) == 0: # @UndefinedVariable + # win32api.FormatMessage -> returns error string + # win32api.GetLastError -> returns error code + # (just put this comment here to remember to log this when logger is available) + error = getErrorMessage() + computerName = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) + raise Exception('Error renaming computer from {} to {}: {}'.format(computerName, newName, error)) + + +NETSETUP_JOIN_DOMAIN = 0x00000001 +NETSETUP_ACCT_CREATE = 0x00000002 +NETSETUP_ACCT_DELETE = 0x00000004 +NETSETUP_WIN9X_UPGRADE = 0x00000010 +NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020 +NETSETUP_JOIN_UNSECURE = 0x00000040 +NETSETUP_MACHINE_PWD_PASSED = 0x00000080 +NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400 +NETSETUP_DEFER_SPN_SET = 0x1000000 + + +def joinDomain(domain, ou, account, password, executeInOneStep=False): + ''' + Joins machine to a windows domain + :param domain: Domain to join to + :param ou: Ou that will hold machine + :param account: Account used to join domain + :param password: Password of account used to join domain + :param executeInOneStep: If true, means that this machine has been renamed and wants to add NETSETUP_JOIN_WITH_NEW_NAME to request so we can do rename/join in one step. + ''' + # If account do not have domain, include it + if '@' not in account and '\\' not in account: + if '.' in domain: + account = account + '@' + domain + else: + account = domain + '\\' + account + + # Do log + flags = NETSETUP_ACCT_CREATE | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN + + if executeInOneStep: + flags |= NETSETUP_JOIN_WITH_NEW_NAME + + flags = DWORD(flags) + + domain = LPCWSTR(domain) + + # Must be in format "ou=.., ..., dc=...," + ou = LPCWSTR(ou) if ou is not None and ou != '' else None + account = LPCWSTR(account) + password = LPCWSTR(password) + + res = ctypes.windll.netapi32.NetJoinDomain(None, domain, ou, account, password, flags) + # Machine found in another ou, use it and warn this on log + if res == 2224: + flags = DWORD(NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN) + res = ctypes.windll.netapi32.NetJoinDomain(None, domain, None, account, password, flags) + if res != 0: + # Log the error + error = getErrorMessage(res) + if res == 1355: + error = "DC Is not reachable" + print('{} {}'.format(res, error)) + raise Exception('Error joining domain {}, with credentials {}/*****{}: {}, {}'.format(domain.value, account.value, ', under OU {}'.format(ou.value) if ou.value is not None else '', res, error)) + + +def changeUserPassword(user, oldPassword, newPassword): + computerName = LPCWSTR(getComputerName()) + user = LPCWSTR(user) + oldPassword = LPCWSTR(oldPassword) + newPassword = LPCWSTR(newPassword) + + res = ctypes.windll.netapi32.NetUserChangePassword(computerName, user, oldPassword, newPassword) + + if res != 0: + # Log the error, and raise exception to parent + error = getErrorMessage() + raise Exception('Error changing password for user {}: {}'.format(user.value, error)) + + +class LASTINPUTINFO(ctypes.Structure): + _fields_ = [ + ('cbSize', ctypes.c_uint), + ('dwTime', ctypes.c_uint), + ] + + +def initIdleDuration(atLeastSeconds): + ''' + In windows, there is no need to set screensaver + ''' + pass + + +def getIdleDuration(): + lastInputInfo = LASTINPUTINFO() + lastInputInfo.cbSize = ctypes.sizeof(lastInputInfo) + ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lastInputInfo)) + millis = ctypes.windll.kernel32.GetTickCount() - lastInputInfo.dwTime # @UndefinedVariable + return millis / 1000.0 + + +def getCurrentUser(): + ''' + Returns current logged in username + ''' + return os.environ['USERNAME'] + + +def getSessionLanguage(): + ''' + Returns the user's session language + ''' + return locale.getdefaultlocale()[0] + + +def showPopup(title, message): + ''' + Displays a message box on user's session (during 1 min). + ''' + return subprocess.call('mshta "javascript:var sh=new ActiveXObject(\'WScript.Shell\'); sh.Popup( \'{}\', 60, \'{}\', 64); close()"'.format(message.encode('unicode_escape'), title.encode('unicode_escape')), shell=True) diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/workers/__init__.py b/admin/Sources/Clients/ogagent/src/opengnsys/workers/__init__.py new file mode 100644 index 00000000..f2bcd7d2 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/workers/__init__.py @@ -0,0 +1,2 @@ +from .server_worker import ServerWorker +from .client_worker import ClientWorker diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/workers/client_worker.py b/admin/Sources/Clients/ogagent/src/opengnsys/workers/client_worker.py new file mode 100644 index 00000000..6a083804 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/workers/client_worker.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +# pylint: disable=unused-wildcard-import,wildcard-import +from __future__ import unicode_literals + +class ClientWorker(object): + ''' + A ServerWorker is a server module that "works" for service + Most method are invoked inside their own thread, except onActivation & onDeactivation. + This two methods are invoked inside main service thread, take that into account when creating them + + * You must provide a module name (override name on your class), so we can identify the module by a "valid" name. + A valid name is like a valid python variable (do not use spaces, etc...) + * The name of the module is used as REST message destination id: + https://sampleserver:8888/[name]/.... + Remember that module names and REST path are case sensitive!!! + + ''' + name = None + service = None + + def __init__(self, service): + self.service = service + + def activate(self): + ''' + Convenient method to wrap onActivation, so we can include easyly custom common logic for activation in a future + ''' + self.onActivation() + + def deactivate(self): + ''' + Convenient method to wrap onActivation, so we can include easyly custom common logic for deactivation in a future + ''' + self.onDeactivation() + + def processMessage(self, message, params): + ''' + This method can be overriden to provide your own message proccessor, or better you can + implement a method that is called "process_" + message and this default processMessage will invoke it + * Example: + We got a message from OGAgent "Mazinger", with json params + module.processMessage("mazinger", jsonParams) + + This method will process "mazinguer", and look for a "self" method that is called "process_mazinger", and invoke it this way: + return self.process_mazinger(jsonParams) + + The methods must return data that can be serialized to json (i.e. Ojects are not serializable to json, basic type are) + ''' + try: + operation = getattr(self, 'process_' + message) + except Exception: + raise Exception('Message processor for "{}" not found'.format(message)) + + return operation(params) + + def onActivation(self): + ''' + Invoked by Service for activation. + This MUST be overridden by modules! + This method is invoked inside main thread, so if it "hangs", complete service will hang + This should be no problem, but be advised about this + ''' + pass + + def onDeactivation(self): + ''' + Invoked by Service before unloading service + This MUST be overridden by modules! + This method is invoked inside main thread, so if it "hangs", complete service will hang + This should be no problem, but be advised about this + ''' + pass + + # ************************************* + # * Helper, convenient helper methods * + # ************************************* + def sendServerMessage(self, message, data): + ''' + Sends a message to connected ipc clients + By convenience, it uses the "current" moduel name as destination module name also. + If you need to send a message to a different module, you can use self.service.sendClientMessage(module, message, data) instead + og this helmer + ''' + self.service.ipc.sendMessage(self.name, message, data) + \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/workers/server_worker.py b/admin/Sources/Clients/ogagent/src/opengnsys/workers/server_worker.py new file mode 100644 index 00000000..141d657c --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/opengnsys/workers/server_worker.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +# pylint: disable=unused-wildcard-import,wildcard-import +from __future__ import unicode_literals + +class ServerWorker(object): + ''' + A ServerWorker is a server module that "works" for service + Most method are invoked inside their own thread, except onActivation & onDeactivation. + This two methods are invoked inside main service thread, take that into account when creating them + + * You must provide a module name (override name on your class), so we can identify the module by a "valid" name. + A valid name is like a valid python variable (do not use spaces, etc...) + * The name of the module is used as REST message destination id: + https://sampleserver:8888/[name]/.... + Remember that module names and REST path are case sensitive!!! + + ''' + name = None + service = None + locked = False + + def __init__(self, service): + self.service = service + + def activate(self): + ''' + Convenient method to wrap onActivation, so we can include easyly custom common logic for activation in a future + ''' + self.onActivation() + + def deactivate(self): + ''' + Convenient method to wrap onActivation, so we can include easyly custom common logic for deactivation in a future + ''' + self.onDeactivation() + + def process(self, getParams, postParams, server): + ''' + This method is invoked on a message received with an empty path (that means a message with only the module name, like in "http://example.com/Sample" + Override it if you expect messages with that pattern + + Overriden method must return data that can be serialized to json (i.e. Ojects are not serializable to json, basic type are) + ''' + raise NotImplementedError('Generic message processor is not supported') + + def processServerMessage(self, path, getParams, postParams, server): + ''' + This method can be overriden to provide your own message proccessor, or better you can + implement a method that is called exactly as "process_" + path[0] (module name has been removed from path array) and this default processMessage will invoke it + * Example: + Imagine this invocation url (no matter if GET or POST): http://example.com:9999/Sample/mazinger/Z + The HTTP Server will remove "Sample" from path, parse arguments and invoke this method as this: + module.processMessage(["mazinger","Z"], getParams, postParams) + + This method will process "mazinguer", and look for a "self" method that is called "process_mazinger", and invoke it this way: + return self.process_mazinger(["Z"], getParams, postParams) + + In the case path is empty (that is, the path is composed only by the module name, like in "http://example.com/Sample", the "process" method + will be invoked directly + + The methods must return data that can be serialized to json (i.e. Ojects are not serializable to json, basic type are) + ''' + if self.locked is True: + raise Exception('system is busy') + + if len(path) == 0: + return self.process(getParams, postParams, server) + try: + operation = getattr(self, 'process_' + path[0]) + except Exception: + raise Exception('Message processor for "{}" not found'.format(path[0])) + + return operation(path[1:], getParams, postParams, server) + + + def processClientMessage(self, message, data): + ''' + Invoked by Service when a client message is received (A message from user space Agent) + + This method can be overriden to provide your own message proccessor, or better you can + implement a method that is called exactly "process_client_" + message (module name has been removed from path) and this default processMessage will invoke it + * Example: + We got a message from OGAgent "Mazinger", with json params + module.processClientMessage("mazinger", jsonParams) + + This method will process "mazinguer", and look for a "self" method that is called "process_client_mazinger", and invoke it this way: + self.process_client_mazinger(jsonParams) + + The methods returns nothing (client communications are done asynchronously) + ''' + try: + operation = getattr(self, 'process_client_' + message) + except Exception: + raise Exception('Message processor for "{}" not found'.format(message)) + + operation(data) + + # raise NotImplementedError('Got a client message but no proccessor is implemented') + + + def onActivation(self): + ''' + Invoked by Service for activation. + This MUST be overridden by modules! + This method is invoked inside main thread, so if it "hangs", complete service will hang + This should be no problem, but be advised about this + ''' + pass + + def onDeactivation(self): + ''' + Invoked by Service before unloading service + This MUST be overridden by modules! + This method is invoked inside main thread, so if it "hangs", complete service will hang + This should be no problem, but be advised about this + ''' + pass + + + def onLogin(self, user): + ''' + Invoked by Service when an user login is detected + This CAN be overridden by modules + This method is invoked whenever the client (user space agent) notifies the server (Service) that a user has logged in. + This method is run on its own thread + ''' + pass + + def onLogout(self, user): + ''' + Invoked by Service when an user login is detected + This CAN be overridden by modules + This method is invoked whenever the client (user space agent) notifies the server (Service) that a user has logged in. + This method is run on its own thread + ''' + pass + + # ************************************* + # * Helper, convenient helper methods * + # ************************************* + def sendClientMessage(self, message, data): + ''' + Sends a message to connected ipc clients + By convenience, it uses the "current" moduel name as destination module name also. + If you need to send a message to a different module, you can use self.service.sendClientMessage(module, message, data) instead + og this helmer + ''' + self.service.sendClientMessage(self.name, message, data) + + def sendScriptMessage(self, script): + self.service.sendScriptMessage(script) + + def sendLogoffMessage(self): + self.service.sendLogoffMessage() + + def sendPopupMessage(self): + self.service.sendPopupMessage() diff --git a/admin/Sources/Clients/ogagent/src/prototypes/threaded_server.py b/admin/Sources/Clients/ogagent/src/prototypes/threaded_server.py new file mode 100644 index 00000000..ed5583bf --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/prototypes/threaded_server.py @@ -0,0 +1,170 @@ +''' +Created on Jul 9, 2015 + +@author: dkmaster +''' +from __future__ import unicode_literals, print_function + +# Pydev can't parse "six.moves.xxxx" because it is loaded lazy +from six.moves.socketserver import ThreadingMixIn # @UnresolvedImport +from six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler # @UnresolvedImport +from six.moves.BaseHTTPServer import HTTPServer # @UnresolvedImport +from six.moves.urllib.parse import unquote # @UnresolvedImport + +import json +import threading +import ssl + +import os.path +import tempfile + +# For testing +# -------------------- +CERTFILE = 'UDSActor.pem' + + +def createSelfSignedCert(force=False): + + certFile = os.path.join(tempfile.gettempdir(), CERTFILE) + + if os.path.exists(certFile) and not force: + return certFile + + certData = '''-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCb50K3mIznNklz +yVAD7xSQOSJQ6+NPXj7U9/4zLZ+TvmbQ7RqUUsxbfxHbeRnoYTWV2nKk4+tHqmvz +ujLSS/loFhTSMqtrLn7rowSYJoQhKOUkAiQlWkqCfItWgL5pJopDpNHFul9Rn3ds +PMWQTiGeUNR4Y3RnBhr1Q1BsqAzf4m6zFUmgLPPmVLdF4uJ3Tuz8TSy2gWLs5aSr +5do4WamwUfYjRSVMJECmwjUM4rQ8SQgg0sHBeBuDUGNBvBQFac1G7qUcMReeu8Zr +DUtMsXma/l4rA8NB5CRmTrQbTBF4l+jb2BDFebDqDUK1Oqs9X35yOQfDOAFYHiix +PX0IsXOZAgMBAAECggEBAJi3000RrIUZUp6Ph0gzPMuCjDEEwWiQA7CPNX1gpb8O +dp0WhkDhUroWIaICYPSXtOwUTtVjRqivMoxPy1Thg3EIoGC/rdeSdlXRHMEGicwJ +yVyalFnatr5Xzg5wkxVh4XMd0zeDt7e3JD7s0QLo5lm1CEzd77qz6lhzFic5/1KX +bzdULtTlq60dazg2hEbcS4OmM1UMCtRVDAsOIUIZPL0M9j1C1d1iEdYnh2xshKeG +/GOfo95xsgdMlGjtv3hUT5ryKVoEsu+36rGb4VfhPfUvvoVbRx5QZpW+QvxaYh5E +Fi0JEROozFwG31Y++8El7J3yQko8cFBa1lYYUwwpNAECgYEAykT+GiM2YxJ4uVF1 +OoKiE9BD53i0IG5j87lGPnWqzEwYBwnqjEKDTou+uzMGz3MDV56UEFNho7wUWh28 +LpEkjJB9QgbsugjxIBr4JoL/rYk036e/6+U8I95lvYWrzb+rBMIkRDYI7kbQD/mQ +piYUpuCkTymNAu2RisK6bBzJslkCgYEAxVE23OQvkCeOV8hJNPZGpJ1mDS+TiOow +oOScMZmZpail181eYbAfMsCr7ri812lSj98NvA2GNVLpddil6LtS1cQ5p36lFBtV +xQUMZiFz4qVbEak+izL+vPaev/mXXsOcibAIQ+qI/0txFpNhJjpaaSy6vRCBYFmc +8pgSoBnBI0ECgYAUKCn2atnpp5aWSTLYgNosBU4vDA1PShD14dnJMaqyr0aZtPhF +v/8b3btFJoGgPMLxgWEZ+2U4ju6sSFhPf7FXvLJu2QfQRkHZRDbEh7t5DLpTK4Fp +va9vl6Ml7uM/HsGpOLuqfIQJUs87OFCc7iCSvMJDDU37I7ekT2GKkpfbCQKBgBrE +0NeY0WcSJrp7/oqD2sOcYurpCG/rrZs2SIZmGzUhMxaa0vIXzbO59dlWELB8pmnE +Tf20K//x9qA5OxDe0PcVPukdQlH+/1zSOYNliG44FqnHtyd1TJ/gKVtMBiAiE4uO +aSClod5Yosf4SJbCFd/s5Iyfv52NqsAyp1w3Aj/BAoGAVCnEiGUfyHlIR+UH4zZW +GXJMeqdZLfcEIszMxLePkml4gUQhoq9oIs/Kw+L1DDxUwzkXN4BNTlFbOSu9gzK1 +dhuIUGfS6RPL88U+ivC3A0y2jT43oUMqe3hiRt360UQ1GXzp2dMnR9odSRB1wHoO +IOjEBZ8341/c9ZHc5PCGAG8= +-----END PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIJAIrEIthCfxUCMA0GCSqGSIb3DQEBCwUAMIGNMQswCQYD +VQQGEwJFUzEPMA0GA1UECAwGTWFkcmlkMREwDwYDVQQHDAhBbGNvcmNvbjEMMAoG +A1UECgwDVURTMQ4wDAYDVQQLDAVBY3RvcjESMBAGA1UEAwwJVURTIEFjdG9yMSgw +JgYJKoZIhvcNAQkBFhlzdXBwb3J0QHVkc2VudGVycHJpc2UuY29tMB4XDTE0MTAy +NjIzNDEyNFoXDTI0MTAyMzIzNDEyNFowgY0xCzAJBgNVBAYTAkVTMQ8wDQYDVQQI +DAZNYWRyaWQxETAPBgNVBAcMCEFsY29yY29uMQwwCgYDVQQKDANVRFMxDjAMBgNV +BAsMBUFjdG9yMRIwEAYDVQQDDAlVRFMgQWN0b3IxKDAmBgkqhkiG9w0BCQEWGXN1 +cHBvcnRAdWRzZW50ZXJwcmlzZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCb50K3mIznNklzyVAD7xSQOSJQ6+NPXj7U9/4zLZ+TvmbQ7RqUUsxb +fxHbeRnoYTWV2nKk4+tHqmvzujLSS/loFhTSMqtrLn7rowSYJoQhKOUkAiQlWkqC +fItWgL5pJopDpNHFul9Rn3dsPMWQTiGeUNR4Y3RnBhr1Q1BsqAzf4m6zFUmgLPPm +VLdF4uJ3Tuz8TSy2gWLs5aSr5do4WamwUfYjRSVMJECmwjUM4rQ8SQgg0sHBeBuD +UGNBvBQFac1G7qUcMReeu8ZrDUtMsXma/l4rA8NB5CRmTrQbTBF4l+jb2BDFebDq +DUK1Oqs9X35yOQfDOAFYHiixPX0IsXOZAgMBAAGjUDBOMB0GA1UdDgQWBBRShS90 +5lJTNvYPIEqP3GxWwG5iiDAfBgNVHSMEGDAWgBRShS905lJTNvYPIEqP3GxWwG5i +iDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAU0Sp4gXhQmRVzq+7+ +vRFUkQuPj4Ga/d9r5Wrbg3hck3+5pwe9/7APoq0P/M0DBhQpiJKjrD6ydUevC+Y/ +43ZOJPhMlNw0o6TdQxOkX6FDwQanLLs7sfvJvqtVzYn3nuRFKT3dvl7Zg44QMw2M +ay42q59fAcpB4LaDx/i7gOYSS5eca3lYW7j7YSr/+ozXK2KlgUkuCUHN95lOq+dF +trmV9mjzM4CNPZqKSE7kpHRywgrXGPCO000NvEGSYf82AtgRSFKiU8NWLQSEPdcB +k//2dsQZw2cRZ8DrC2B6Tb3M+3+CA6wVyqfqZh1SZva3LfGvq/C+u+ItguzPqNpI +xtvM +-----END CERTIFICATE-----''' + with open(certFile, "wt") as f: + f.write(certData) + + return certFile +# -------------- + + +class HTTPServerHandler(SimpleHTTPRequestHandler): + service = None + protocol_version = 'HTTP/1.1' + server_version = 'OpenGnsys Agent Server' + sys_version = '' + + def sendJsonError(self, code, message): + self.send_response(code) + self.send_header('Content-type', 'application/json') + self.end_headers() + self.wfile.write(json.dumps({'error': message})) + return + + def sendJsonResponse(self, data): + self.send_response(200) + data = json.dumps(data) + self.send_header('Content-type', 'application/json') + self.send_header('Content-Length', len(data)) + self.end_headers() + # Send the html message + self.wfile.write(data) + + + # parseURL + def parseUrl(self): + # Very simple path & params splitter + path = self.path.split('?')[0][1:].split('/') + + try: + params = dict((v[0], unquote(v[1])) for v in (v.split('=') for v in self.path.split('?')[1].split('&'))) + except Exception: + params = {} + + return (path, params) + + + def do_GET(self): + path, params = self.parseUrl() + + self.sendJsonResponse({'path': path, 'params': params}) + + def do_POST(self): + path, getParams = self.parseUrl() + + # Now post parameters, that are in JSON format + + + + + +class HTTPThreadingServer(ThreadingMixIn, HTTPServer): + pass + +class HTTPServerThread(threading.Thread): + def __init__(self, address, service): + super(self.__class__, self).__init__() + + HTTPServerHandler.service = service + + self.certFile = createSelfSignedCert() + self.server = HTTPThreadingServer(address, HTTPServerHandler) + self.server.socket = ssl.wrap_socket(self.server.socket, certfile=self.certFile, server_side=True) + + def getServerUrl(self): + return 'https://{}:{}/{}'.format(self.server.server_address[0], self.server.server_address[1], HTTPServerHandler.uuid) + + def stop(self): + self.server.shutdown() + + def run(self): + self.server.serve_forever() + + +if __name__ == '__main__': + thr = HTTPServerThread(('0.0.0.0', 8000), None) + print('Server started: {}'.format(thr)) + thr.start() + + \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/src/setup.py b/admin/Sources/Clients/ogagent/src/setup.py new file mode 100644 index 00000000..f80bf33b --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/setup.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +@author: Ramón M. Gómez, ramongomez at us dot es +''' + +VERSION = '1.1.0' + +# ModuleFinder can't handle runtime changes to __path__, but win32com uses them +try: + # py2exe 0.6.4 introduced a replacement modulefinder. + # This means we have to add package paths there, not to the built-in + # one. If this new modulefinder gets integrated into Python, then + # we might be able to revert this some day. + # if this doesn't work, try import modulefinder + try: + import py2exe.mf as modulefinder + except ImportError: + import modulefinder + import win32com, sys + for p in win32com.__path__[1:]: + modulefinder.AddPackagePath("win32com", p) + for extra in ["win32com.shell"]: # ,"win32com.mapi" + __import__(extra) + m = sys.modules[extra] + for p in m.__path__[1:]: + modulefinder.AddPackagePath(extra, p) +except ImportError: + # no build path setup, no worries. + pass + +from distutils.core import setup +import py2exe +import sys +import os + +sys.argv.append('py2exe') + +def get_requests_cert_file(): + """Add Python requests or certifi .pem file for installers.""" + import requests + f = os.path.join(os.path.dirname(requests.__file__), 'cacert.pem') + if not os.path.exists(f): + import certifi + f = os.path.join(os.path.dirname(certifi.__file__), 'cacert.pem') + return f + + +class Target: + + def __init__(self, **kw): + self.__dict__.update(kw) + # for the versioninfo resources + self.version = VERSION + self.name = 'OGAgentService' + self.description = 'OpenGnsys Agent Service' + self.author = 'Adolfo Gomez' + self.url = 'https://opengnsys.es/' + self.company_name = "OpenGnsys Project" + self.copyright = "(c) 2014 VirtualCable S.L.U." + self.name = "OpenGnsys Agent" + +# Now you need to pass arguments to setup +# windows is a list of scripts that have their own UI and +# thus don't need to run in a console. + + +udsservice = Target( + description='OpenGnsys Agent Service', + modules=['opengnsys.windows.OGAgentService'], + icon_resources=[(0, 'img\\oga.ico'), (1, 'img\\oga.ico')], + cmdline_style='pywin32' +) + +# Some test_modules are hidden to py2exe by six, we ensure that they appear on "includes" +HIDDEN_BY_SIX = ['SocketServer', 'SimpleHTTPServer', 'urllib'] + +setup( + windows=[ + { + 'script': 'OGAgentUser.py', + 'icon_resources': [(0, 'img\\oga.ico'), (1, 'img\\oga.ico')] + }, + ], + console=[ + { + 'script': 'OGAServiceHelper.py' + } + ], + service=[udsservice], + data_files=[('', [get_requests_cert_file()]),('cfg', ['cfg/ogagent.cfg', 'cfg/ogclient.cfg'])], + options={ + 'py2exe': { + 'bundle_files': 3, + 'compressed': True, + 'optimize': 2, + 'includes': ['sip', 'PyQt4', 'win32com.shell', 'requests', 'encodings', 'encodings.utf_8'] + HIDDEN_BY_SIX, + 'excludes': ['doctest', 'unittest'], + 'dll_excludes': ['msvcp90.dll'], + 'dist_dir': '..\\bin', + } + }, + name='OpenGnsys Agent', + version=VERSION, + description='OpenGnsys Agent', + author='Adolfo Gomez', + author_email='agomez@virtualcable.es', + zipfile='OGAgent.zip', +) diff --git a/admin/Sources/Clients/ogagent/src/test_modules/__init__.py b/admin/Sources/Clients/ogagent/src/test_modules/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/admin/Sources/Clients/ogagent/src/test_modules/client/Sample1/__init__.py b/admin/Sources/Clients/ogagent/src/test_modules/client/Sample1/__init__.py new file mode 100644 index 00000000..db174f0e --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/test_modules/client/Sample1/__init__.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from opengnsys.workers import ClientWorker + +class Sample1(ClientWorker): + name = 'Sample1' + diff --git a/admin/Sources/Clients/ogagent/src/test_modules/client/__init__.py b/admin/Sources/Clients/ogagent/src/test_modules/client/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/__init__.py b/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/__init__.py new file mode 100644 index 00000000..189957e6 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/__init__.py @@ -0,0 +1,2 @@ +# Module must be imported on package, so we can initialize and load it +from sample1 import Sample1 \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample1.py b/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample1.py new file mode 100644 index 00000000..61e405ec --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample1.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + +from opengnsys.workers import ServerWorker + +from .sample_pkg import test + +class Sample1(ServerWorker): + name='Sample1' + diff --git a/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample_pkg/__init__.py b/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample_pkg/__init__.py new file mode 100644 index 00000000..19365721 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/test_modules/server/Sample1/sample_pkg/__init__.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +from __future__ import unicode_literals + + +def test(): + return 'Test' \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/src/test_modules/server/__init__.py b/admin/Sources/Clients/ogagent/src/test_modules/server/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/admin/Sources/Clients/ogagent/src/test_rest_server.py b/admin/Sources/Clients/ogagent/src/test_rest_server.py new file mode 100644 index 00000000..ad1aede6 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/test_rest_server.py @@ -0,0 +1,210 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +''' +@author: Adolfo Gómez, dkmaster at dkmon dot com +''' +# pylint: disable=unused-wildcard-import,wildcard-import +from __future__ import unicode_literals, print_function + +# Pydev can't parse "six.moves.xxxx" because it is loaded lazy +from six.moves.socketserver import ThreadingMixIn # @UnresolvedImport +from six.moves.BaseHTTPServer import BaseHTTPRequestHandler # @UnresolvedImport +from six.moves.BaseHTTPServer import HTTPServer # @UnresolvedImport +from six.moves.urllib.parse import unquote # @UnresolvedImport + +import json +import threading +import ssl + +import logging +from tempfile import gettempdir +from os.path import exists, join + +logger = logging.getLogger(__name__) + + +CERTFILE = 'OGTestServer.pem' + + +def createSelfSignedCert(force=False): + + certFile = join(gettempdir(), CERTFILE) + + if exists(certFile) and not force: + return certFile + + certData = '''-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCb50K3mIznNklz +yVAD7xSQOSJQ6+NPXj7U9/4zLZ+TvmbQ7RqUUsxbfxHbeRnoYTWV2nKk4+tHqmvz +ujLSS/loFhTSMqtrLn7rowSYJoQhKOUkAiQlWkqCfItWgL5pJopDpNHFul9Rn3ds +PMWQTiGeUNR4Y3RnBhr1Q1BsqAzf4m6zFUmgLPPmVLdF4uJ3Tuz8TSy2gWLs5aSr +5do4WamwUfYjRSVMJECmwjUM4rQ8SQgg0sHBeBuDUGNBvBQFac1G7qUcMReeu8Zr +DUtMsXma/l4rA8NB5CRmTrQbTBF4l+jb2BDFebDqDUK1Oqs9X35yOQfDOAFYHiix +PX0IsXOZAgMBAAECggEBAJi3000RrIUZUp6Ph0gzPMuCjDEEwWiQA7CPNX1gpb8O +dp0WhkDhUroWIaICYPSXtOwUTtVjRqivMoxPy1Thg3EIoGC/rdeSdlXRHMEGicwJ +yVyalFnatr5Xzg5wkxVh4XMd0zeDt7e3JD7s0QLo5lm1CEzd77qz6lhzFic5/1KX +bzdULtTlq60dazg2hEbcS4OmM1UMCtRVDAsOIUIZPL0M9j1C1d1iEdYnh2xshKeG +/GOfo95xsgdMlGjtv3hUT5ryKVoEsu+36rGb4VfhPfUvvoVbRx5QZpW+QvxaYh5E +Fi0JEROozFwG31Y++8El7J3yQko8cFBa1lYYUwwpNAECgYEAykT+GiM2YxJ4uVF1 +OoKiE9BD53i0IG5j87lGPnWqzEwYBwnqjEKDTou+uzMGz3MDV56UEFNho7wUWh28 +LpEkjJB9QgbsugjxIBr4JoL/rYk036e/6+U8I95lvYWrzb+rBMIkRDYI7kbQD/mQ +piYUpuCkTymNAu2RisK6bBzJslkCgYEAxVE23OQvkCeOV8hJNPZGpJ1mDS+TiOow +oOScMZmZpail181eYbAfMsCr7ri812lSj98NvA2GNVLpddil6LtS1cQ5p36lFBtV +xQUMZiFz4qVbEak+izL+vPaev/mXXsOcibAIQ+qI/0txFpNhJjpaaSy6vRCBYFmc +8pgSoBnBI0ECgYAUKCn2atnpp5aWSTLYgNosBU4vDA1PShD14dnJMaqyr0aZtPhF +v/8b3btFJoGgPMLxgWEZ+2U4ju6sSFhPf7FXvLJu2QfQRkHZRDbEh7t5DLpTK4Fp +va9vl6Ml7uM/HsGpOLuqfIQJUs87OFCc7iCSvMJDDU37I7ekT2GKkpfbCQKBgBrE +0NeY0WcSJrp7/oqD2sOcYurpCG/rrZs2SIZmGzUhMxaa0vIXzbO59dlWELB8pmnE +Tf20K//x9qA5OxDe0PcVPukdQlH+/1zSOYNliG44FqnHtyd1TJ/gKVtMBiAiE4uO +aSClod5Yosf4SJbCFd/s5Iyfv52NqsAyp1w3Aj/BAoGAVCnEiGUfyHlIR+UH4zZW +GXJMeqdZLfcEIszMxLePkml4gUQhoq9oIs/Kw+L1DDxUwzkXN4BNTlFbOSu9gzK1 +dhuIUGfS6RPL88U+ivC3A0y2jT43oUMqe3hiRt360UQ1GXzp2dMnR9odSRB1wHoO +IOjEBZ8341/c9ZHc5PCGAG8= +-----END PRIVATE KEY----- +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIJAIrEIthCfxUCMA0GCSqGSIb3DQEBCwUAMIGNMQswCQYD +VQQGEwJFUzEPMA0GA1UECAwGTWFkcmlkMREwDwYDVQQHDAhBbGNvcmNvbjEMMAoG +A1UECgwDVURTMQ4wDAYDVQQLDAVBY3RvcjESMBAGA1UEAwwJVURTIEFjdG9yMSgw +JgYJKoZIhvcNAQkBFhlzdXBwb3J0QHVkc2VudGVycHJpc2UuY29tMB4XDTE0MTAy +NjIzNDEyNFoXDTI0MTAyMzIzNDEyNFowgY0xCzAJBgNVBAYTAkVTMQ8wDQYDVQQI +DAZNYWRyaWQxETAPBgNVBAcMCEFsY29yY29uMQwwCgYDVQQKDANVRFMxDjAMBgNV +BAsMBUFjdG9yMRIwEAYDVQQDDAlVRFMgQWN0b3IxKDAmBgkqhkiG9w0BCQEWGXN1 +cHBvcnRAdWRzZW50ZXJwcmlzZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCb50K3mIznNklzyVAD7xSQOSJQ6+NPXj7U9/4zLZ+TvmbQ7RqUUsxb +fxHbeRnoYTWV2nKk4+tHqmvzujLSS/loFhTSMqtrLn7rowSYJoQhKOUkAiQlWkqC +fItWgL5pJopDpNHFul9Rn3dsPMWQTiGeUNR4Y3RnBhr1Q1BsqAzf4m6zFUmgLPPm +VLdF4uJ3Tuz8TSy2gWLs5aSr5do4WamwUfYjRSVMJECmwjUM4rQ8SQgg0sHBeBuD +UGNBvBQFac1G7qUcMReeu8ZrDUtMsXma/l4rA8NB5CRmTrQbTBF4l+jb2BDFebDq +DUK1Oqs9X35yOQfDOAFYHiixPX0IsXOZAgMBAAGjUDBOMB0GA1UdDgQWBBRShS90 +5lJTNvYPIEqP3GxWwG5iiDAfBgNVHSMEGDAWgBRShS905lJTNvYPIEqP3GxWwG5i +iDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAU0Sp4gXhQmRVzq+7+ +vRFUkQuPj4Ga/d9r5Wrbg3hck3+5pwe9/7APoq0P/M0DBhQpiJKjrD6ydUevC+Y/ +43ZOJPhMlNw0o6TdQxOkX6FDwQanLLs7sfvJvqtVzYn3nuRFKT3dvl7Zg44QMw2M +ay42q59fAcpB4LaDx/i7gOYSS5eca3lYW7j7YSr/+ozXK2KlgUkuCUHN95lOq+dF +trmV9mjzM4CNPZqKSE7kpHRywgrXGPCO000NvEGSYf82AtgRSFKiU8NWLQSEPdcB +k//2dsQZw2cRZ8DrC2B6Tb3M+3+CA6wVyqfqZh1SZva3LfGvq/C+u+ItguzPqNpI +xtvM +-----END CERTIFICATE-----''' + with open(certFile, "wt") as f: + f.write(certData) + + return certFile + +class HTTPServerHandler(BaseHTTPRequestHandler): + service = None + protocol_version = 'HTTP/1.0' + server_version = 'OpenGnsys Test REST Server' + sys_version = '' + + def sendJsonError(self, code, message): + self.send_response(code) + self.send_header('Content-type', 'application/json') + self.end_headers() + self.wfile.write(json.dumps({'error': message})) + return + + def sendJsonResponse(self, data): + self.send_response(200) + data = json.dumps(data) + self.send_header('Content-type', 'application/json') + self.send_header('Content-Length', len(data)) + self.end_headers() + # Send the html message + self.wfile.write(data) + + + # parseURL + def parseUrl(self): + # Very simple path & params splitter + path = self.path.split('?')[0][1:].split('/') + + try: + params = dict((v[0], unquote(v[1])) for v in (v.split('=') for v in self.path.split('?')[1].split('&'))) + except Exception: + params = {} + + return (path, params) + + + def do_GET(self): + path, params = self.parseUrl() + + self.sendJsonResponse({'path': path, 'params': params}) + + def do_POST(self): + path, getParams = self.parseUrl() + + # Now post parameters, that are in JSON format + self.sendJsonResponse({'path': path, 'params': getParams}) + + def log_error(self, fmt, *args): + logger.error('HTTP ' + fmt % args) + + def log_message(self, fmt, *args): + logger.info('HTTP ' + fmt % args) + + +class HTTPThreadingServer(ThreadingMixIn, HTTPServer): + pass + +class HTTPServerThread(threading.Thread): + def __init__(self, address, service): + super(self.__class__, self).__init__() + + HTTPServerHandler.service = service + + self.certFile = createSelfSignedCert() + self.server = HTTPThreadingServer(address, HTTPServerHandler) + self.server.socket = ssl.wrap_socket(self.server.socket, certfile=self.certFile, server_side=True) + + logger.info('Initialized HTTPS Server thread on {}'.format(address)) + + def getServerUrl(self): + return 'https://{}:{}/{}'.format(self.server.server_address[0], self.server.server_address[1], HTTPServerHandler.uuid) + + def stop(self): + self.server.shutdown() + + def run(self): + self.server.serve_forever() + + + +if __name__ == '__main__': + logging.basicConfig( + filename='/tmp/restserver.log', + filemode='w', + format='%(levelname)s %(asctime)s %(message)s', + level=logging.DEBUG + ) + + thr = HTTPServerThread(('0.0.0.0', 9999), None) + print('Server started: {}'.format(thr)) + thr.run() + \ No newline at end of file diff --git a/admin/Sources/Clients/ogagent/src/update.sh b/admin/Sources/Clients/ogagent/src/update.sh new file mode 100755 index 00000000..1019ea85 --- /dev/null +++ b/admin/Sources/Clients/ogagent/src/update.sh @@ -0,0 +1,41 @@ +#!/bin/bash +# +# Copyright (c) 2014 Virtual Cable S.L. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +function process { + pyuic4 about-dialog.ui -o about_dialog_ui.py -x + pyuic4 message-dialog.ui -o message_dialog_ui.py -x +} + +cd $(dirname "$0") +pyrcc4 -py3 OGAgent.qrc -o OGAgent_rc.py + + +# process current directory ui's +process + diff --git a/admin/Sources/Clients/ogagent/windows/build-windows.sh b/admin/Sources/Clients/ogagent/windows/build-windows.sh new file mode 100755 index 00000000..d7248ab7 --- /dev/null +++ b/admin/Sources/Clients/ogagent/windows/build-windows.sh @@ -0,0 +1,5 @@ +#!/bin/bash +export WINEARCH=win32 +export WINEPREFIX=$(realpath $(dirname $0)/wine) +wine cmd /c c:\\ogagent\\build.bat +chmod -x $(dirname $0)/../OGAgentSetup*.exe diff --git a/admin/Sources/Clients/ogagent/windows/build.bat b/admin/Sources/Clients/ogagent/windows/build.bat new file mode 100644 index 00000000..2c444741 --- /dev/null +++ b/admin/Sources/Clients/ogagent/windows/build.bat @@ -0,0 +1,6 @@ +C: +CD \ogagent\src +python setup.py +CD .. +"C:\Program Files\NSIS\makensis.exe" ogagent.nsi + diff --git a/admin/Sources/Clients/ogagent/windows/ogagent.nsi b/admin/Sources/Clients/ogagent/windows/ogagent.nsi new file mode 100644 index 00000000..88c9ab2f --- /dev/null +++ b/admin/Sources/Clients/ogagent/windows/ogagent.nsi @@ -0,0 +1,192 @@ +# We need http://nsis.sourceforge.net/NSIS_Simple_Firewall_Plugin +# Copy inside the two x86_xxxxx folders inside nsis plugins folder +Name "OpenGnsys Agent" + +# OpenGnsys Actor version +!define /file OGA_VERSION "src\VERSION" + +# General Symbol Definitions +!define REGKEY "SOFTWARE\OGAgent" +!define VERSION ${OGA_VERSION}.0 +!define COMPANY "OpenGnsys Project" +!define URL https://opengnsys.es + +# MultiUser Symbol Definitions +!define MULTIUSER_EXECUTIONLEVEL Admin +#!define MULTIUSER_INSTALLMODE_DEFAULT_CURRENTUSER +!define MULTIUSER_INSTALLMODE_COMMANDLINE +!define MULTIUSER_INSTALLMODE_INSTDIR OGAgent +!define MULTIUSER_INSTALLMODE_INSTDIR_REGISTRY_KEY "${REGKEY}" +!define MULTIUSER_INSTALLMODE_INSTDIR_REGISTRY_VALUE "Path" + +# MUI Symbol Definitions +!define MUI_ICON "src\img\oga.ico" +!define MUI_FINISHPAGE_NOAUTOCLOSE +!define MUI_UNICON "src\img\oga.ico" +!define MUI_UNFINISHPAGE_NOAUTOCLOSE +!define MUI_LANGDLL_REGISTRY_ROOT HKLM +!define MUI_LANGDLL_REGISTRY_KEY ${REGKEY} +!define MUI_LANGDLL_REGISTRY_VALUENAME InstallerLanguage + +# Included files +!include MultiUser.nsh +!include Sections.nsh +!include MUI2.nsh + +# Reserved Files +!insertmacro MUI_RESERVEFILE_LANGDLL + +# Variables +Var StartMenuGroup + +# Installer pages +!insertmacro MUI_PAGE_WELCOME +!insertmacro MUI_PAGE_LICENSE src\license.txt +!insertmacro MUI_PAGE_DIRECTORY +!insertmacro MUI_PAGE_INSTFILES +!insertmacro MUI_PAGE_FINISH +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES + +# Installer languages +!insertmacro MUI_LANGUAGE English +!insertmacro MUI_LANGUAGE Spanish +!insertmacro MUI_LANGUAGE French +!insertmacro MUI_LANGUAGE German + +# Installer attributes +BrandingText "OpenGnsys" +OutFile OGAgentSetup-${OGA_VERSION}.exe +InstallDir OGAgent +CRCCheck on +XPStyle on +ShowInstDetails hide +VIProductVersion "${VERSION}.0.0" +VIAddVersionKey /LANG=${LANG_ENGLISH} ProductName "OGAgent" +VIAddVersionKey /LANG=${LANG_ENGLISH} ProductVersion "${VERSION}" +VIAddVersionKey /LANG=${LANG_ENGLISH} CompanyName "${COMPANY}" +VIAddVersionKey /LANG=${LANG_ENGLISH} CompanyWebsite "${URL}" +VIAddVersionKey /LANG=${LANG_ENGLISH} FileVersion "${VERSION}" +VIAddVersionKey /LANG=${LANG_ENGLISH} FileDescription "OpenGnsys Agent installer" +VIAddVersionKey /LANG=${LANG_ENGLISH} LegalCopyright "(c) 2015 Virtual Cable S.L.U." +InstallDirRegKey HKLM "${REGKEY}" Path +ShowUninstDetails show + +# Installer sections +Section -Main SEC0000 + SetShellVarContext all + SetOutPath $INSTDIR + SetOverwrite on + File /r bin\*.* + File vcredist_x86.exe + WriteRegStr HKLM "${REGKEY}\Components" Main 1 +SectionEnd + +Section -post SEC0001 + SetShellVarContext current + WriteRegStr HKLM "${REGKEY}" Path $INSTDIR + SetOutPath $INSTDIR + WriteUninstaller $INSTDIR\OGAgentUninstaller.exe + SetOutPath $SMPROGRAMS\$StartMenuGroup + CreateShortcut "$SMPROGRAMS\$StartMenuGroup\$(^UninstallLink).lnk" $INSTDIR\OGAgentUninstaller.exe + WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayName "$(^Name)" + WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayVersion "${VERSION}" + WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" Publisher "${COMPANY}" + WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" URLInfoAbout "${URL}" + WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" DisplayIcon $INSTDIR\OGAgentUninstaller.exe + WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" UninstallString $INSTDIR\OGAgentUninstaller.exe + WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Run" OGAgentTool $INSTDIR\OGAgentUser.exe + WriteRegDWORD HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoModify 1 + WriteRegDWORD HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" NoRepair 1 + ExecWait '"$INSTDIR\vcredist_x86.exe" /passive /norestart' + # Add the application to the firewall exception list - All Networks - All IP Version - Enabled + # SimpleFC::AddApplication "OpenGnsys Agent Service" "$INSTDIR\OGAgentService.exe" 0 2 "" 1 + # SimpleFC::AdvAddRule [name] [description] [protocol] [direction] + # [status] [profile] [action] [application] [service_name] [icmp_types_and_codes] + # [group] [local_ports] [remote_ports] [local_address] [remote_address] + # + SimpleFC::AdvAddRule "OpenGnsys Agent Firewall rules" "Firewall rules for OpenGnsys Agent interaction with broker." "6" "1" \ + "1" "7" "1" "$INSTDIR\OGAgentService.exe" "" "" \ + "" "" "" "" "" + Pop $0 ; return error(1)/success(0) + # Disable fast boot on Windows 10, if registry key exists. + ReadRegDWORD $0 HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Power" HiberbootEnabled + IfErrors 0 +2 + WriteRegDWORD HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Power" HiberbootEnabled 0 + # Install service + nsExec::Exec /OEM "$INSTDIR\OGAgentService.exe --startup auto install" # Add service after installation + # Update recovery options + nsExec::Exec /OEM "$INSTDIR\OGAServiceHelper.exe" +SectionEnd + +# Macro for selecting uninstaller sections +!macro SELECT_UNSECTION SECTION_NAME UNSECTION_ID + Push $R0 + ReadRegStr $R0 HKLM "${REGKEY}\Components" "${SECTION_NAME}" + StrCmp $R0 1 0 next${UNSECTION_ID} + !insertmacro SelectSection "${UNSECTION_ID}" + GoTo done${UNSECTION_ID} +next${UNSECTION_ID}: + !insertmacro UnselectSection "${UNSECTION_ID}" +done${UNSECTION_ID}: + Pop $R0 +!macroend + +# Uninstaller sections +Section /o -un.Main UNSEC0000 + nsExec::Exec /OEM "$INSTDIR\OGAgentService.exe stop" # Stops the service prior uninstall + nsExec::Exec /OEM "$INSTDIR\OGAgentService.exe remove" # Removes the service prior uninstall + Delete /REBOOTOK "$INSTDIR\*.*" + DeleteRegValue HKLM "${REGKEY}\Components" Main + DeleteRegValue HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Run" OGAgentTool +SectionEnd + +Section -un.post UNSEC0001 + # Remove application from the firewall exception list + # SimpleFC::RemoveApplication "$INSTDIR\OGAgentService.exe" + SimpleFC::AdvRemoveRule "OpenGnsys Agent Firewall rules" + Pop $0 ; return error(1)/success(0) + + SetShellVarContext current + StrCpy $StartMenuGroup "OpenGnsys Agent" + DeleteRegKey HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$(^Name)" + Delete /REBOOTOK "$SMPROGRAMS\$StartMenuGroup\$(^UninstallLink).lnk" + Delete /REBOOTOK $INSTDIR\OGAgentUninstaller.exe + DeleteRegValue HKLM "${REGKEY}" Path + DeleteRegKey /IfEmpty HKLM "${REGKEY}\Components" + DeleteRegKey /IfEmpty HKLM "${REGKEY}" + RmDir /REBOOTOK $SMPROGRAMS\$StartMenuGroup + SetShellVarContext all + RmDir /REBOOTOK $INSTDIR + SetRebootFlag true + MessageBox MB_YESNO "$(^RebootMessage)" IDNO donotreboot + Reboot # Reboot is needed after uninstalling, so new installs works fine + donotreboot: +SectionEnd + +# Installer functions +Function .onInit + InitPluginsDir + StrCpy $StartMenuGroup "OpenGnsys Agent" + + !insertmacro MUI_LANGDLL_DISPLAY + !insertmacro MULTIUSER_INIT +FunctionEnd + +# Uninstaller functions +Function un.onInit + StrCpy $StartMenuGroup "OpenGnsys Agent" + !insertmacro MUI_UNGETLANGUAGE + !insertmacro MULTIUSER_UNINIT + !insertmacro SELECT_UNSECTION Main ${UNSEC0000} +FunctionEnd + +# Installer Language Strings +LangString ^UninstallLink ${LANG_ENGLISH} "Uninstall $(^Name)" +LangString ^UninstallLink ${LANG_SPANISH} "Desinstalar $(^Name)" +LangString ^UninstallLink ${LANG_FRENCH} "D�sinstaller $(^Name)" +LangString ^UninstallLink ${LANG_GERMAN} "deinstallieren $(^Name)" +LangString ^RebootMessage ${LANG_ENGLISH} "Reboot the system to complete uninstall process?$\nNote: for a new $(^Name) installation, you will need to reboot." +LangString ^RebootMessage ${LANG_SPANISH} "¿Reiniciar el sistema para completar el proceso?$\nNota: es necesario reiniciar para instalar un nuevo $(^Name)." +LangString ^RebootMessage ${LANG_FRENCH} "Reboot the system to complete uninstall process?$\nNote: for a new $(^Name) installation, you will ned to reboot." +LangString ^RebootMessage ${LANG_GERMAN} "Reboot the system to complete uninstall process?$\nNote: for a new $(^Name) installation, you will ned to reboot." diff --git a/admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh b/admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh new file mode 100755 index 00000000..17fbbbc7 --- /dev/null +++ b/admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh @@ -0,0 +1,71 @@ +#!/bin/sh + +# We need: +# * Wine (32 bit) +# * winetricks (in some distributions) + +export WINEARCH=win32 WINEPREFIX=$PWD/wine WINEDEBUG=fixme-all +WINE=wine + +download() { + mkdir downloads + # Get needed software + cd downloads + wget -nd https://www.python.org/ftp/python/2.7.14/python-2.7.14.msi -O python-2.7.msi + wget -nd http://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi + wget -nd https://bootstrap.pypa.io/get-pip.py + wget -nd http://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/pywin32-221.win32-py2.7.exe/download -O pywin32-install.exe + wget -nd http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/py2exe-0.6.9.win32-py2.7.exe/download -O py2exe-install.exe + wget -nd http://prdownloads.sourceforge.net/nsis/nsis-3.0rc1-setup.exe?download -O nsis-install.exe + wget -nd http://sourceforge.net/projects/pyqt/files/PyQt4/PyQt-4.11.4/PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x32.exe/download -O pyqt-install.exe + wget -nd http://nsis.sourceforge.net/mediawiki/images/d/d7/NSIS_Simple_Firewall_Plugin_1.20.zip + cd .. +} + +install_python() { + if which winetricks &>/dev/null; then + echo "Setting up wine prefix (using winetricks)" + winetricks + fi + + cd downloads + echo "Installing python" + $WINE msiexec /qn /i python-2.7.msi + echo "Installing vc for python" + $WINE msiexec /qn /i VCForPython27.msi + + echo "Installing pywin32 (needs X)" + $WINE pywin32-install.exe + echo "Installing py2exe (needs X)" + $WINE py2exe-install.exe + echo "Installing pyqt" + $WINE pyqt-install.exe + echo "Installing nsis (needs X?)" + $WINE nsis-install.exe + + cd .. +} + +setup_pip() { + echo "Seting up pip..." + $WINE C:\\Python27\\python -m pip install --upgrade pip +} + +install_packages() { + echo "Installing required packages" + $WINE C:\\Python27\\python -m pip install requests + $WINE C:\\Python27\\python -m pip install six + # Using easy_install instead of pip to install pycrypto + $WINE C:\\Python27\\Scripts\\easy_install http://www.voidspace.org.uk/python/pycrypto-2.6.1/pycrypto-2.6.1.win32-py2.7.exe + # Copy nsis required NSIS_Simple_Firewall_Plugin_1 + echo "Copying simple firewall plugin for nsis installer" + unzip -o downloads/NSIS_Simple_Firewall_Plugin_1.20.zip SimpleFC.dll -d $WINEPREFIX/drive_c/Program\ Files/NSIS/Plugins/x86-ansi/ + unzip -o downloads/NSIS_Simple_Firewall_Plugin_1.20.zip SimpleFC.dll -d $WINEPREFIX/drive_c/Program\ Files/NSIS/Plugins/x86-unicode/ +} + +download +install_python +setup_pip +install_packages + + diff --git a/admin/Sources/Includes/Database.cpp b/admin/Sources/Includes/Database.cpp index 0d1ddcc5..84add9ce 100644 --- a/admin/Sources/Includes/Database.cpp +++ b/admin/Sources/Includes/Database.cpp @@ -106,6 +106,11 @@ bool Database::Execute(char* CmdStr, Table& Tbl) return (true); } // __________________________________________________________________________ +void Database::liberaResult (Table& Tbl) { + //Free resources after mysql_store_result + mysql_free_result(Tbl.m_Rec); +} +// __________________________________________________________________________ Table::Table() { m_Rec=NULL; diff --git a/admin/Sources/Includes/Database.h b/admin/Sources/Includes/Database.h index 0af1561b..ae318bdb 100644 --- a/admin/Sources/Includes/Database.h +++ b/admin/Sources/Includes/Database.h @@ -25,6 +25,7 @@ public: bool Close(void); bool Execute(char* CmdStr); bool Execute(char* CmdStr, Table& Tbl); + void liberaResult(Table& Tbl); void GetErrorErrStr(char* ErrStr); }; // __________________________________________________________________________ diff --git a/admin/Sources/Services/ogAdmAgent/sources/ogAdmAgent.h b/admin/Sources/Services/ogAdmAgent/sources/ogAdmAgent.h index a2f7deef..b1c429bb 100644 --- a/admin/Sources/Services/ogAdmAgent/sources/ogAdmAgent.h +++ b/admin/Sources/Services/ogAdmAgent/sources/ogAdmAgent.h @@ -27,7 +27,7 @@ // Valores hexadecimales para consultas // ________________________________________________________________________________________________________ -BYTE HEX_annos[]={0,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; +WORD HEX_annos[]={0,0x0001,0x0002,0x0004,0x0008,0x0010,0x0020,0x0040,0x0080,0x0100,0x0200,0x0400,0x0800,0x1000,0x2000,0x4000,0x8000}; WORD HEX_meses[]={0,0x0001,0x0002,0x0004,0x0008,0x0010,0x0020,0x0040,0x0080,0x0100,0x0200,0x0400,0x0800}; int HEX_dias[]={0,0x00000001,0x00000002,0x00000004,0x00000008,0x00000010,0x00000020,0x00000040,0x00000080,0x00000100,0x00000200, 0x00000400,0x00000800,0x00001000,0x00002000,0x00004000,0x00008000,0x00010000,0x00020000,0x00040000,0x00080000, diff --git a/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg b/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg index b916411d..1a8f289d 100644 --- a/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg +++ b/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg @@ -1,2 +1,3 @@ IPlocal=SERVERIP Puerto=2002 +ApiToken=REPOKEY diff --git a/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp b/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp index 19503065..6b6b7d72 100644 --- a/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp +++ b/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp @@ -147,11 +147,14 @@ BOOLEAN gestionaTrama(SOCKET *socket_c) if (res == 0) { // Encontrada la función que procesa el mensaje liberaMemoria(nfn); res=tbfuncionesServer[i].fptr(socket_c, ptrTrama); // Invoca la función - liberaMemoria((char*)ptrTrama); + liberaMemoria(ptrTrama->parametros); + liberaMemoria(ptrTrama); return(res); } } - + liberaMemoria(nfn); + liberaMemoria(ptrTrama->parametros); + liberaMemoria(ptrTrama); /* Sólo puede ser un comando personalizado o su notificación if (ptrTrama->tipo == MSG_COMANDO) @@ -215,6 +218,7 @@ BOOLEAN respuestaSondeo(SOCKET *socket_c, TRAMA* ptrTrama) { lSize = strlen(iph); // Calcula longitud de la cadena de direccion/es IPE/S Ipes = (char*) reservaMemoria(lSize + 1); if (Ipes == NULL) { + liberaMemoria(iph); errorLog(modulo, 3, FALSE); return (FALSE); } @@ -348,6 +352,7 @@ BOOLEAN EcoConsola(SOCKET *socket_c, TRAMA* ptrTrama) // Lee archivo de eco de consola iph = copiaParametro("iph",ptrTrama); // Toma dirección ip del cliente sprintf(fileco,"/tmp/_Seconsola_%s",iph); // Nombre del archivo en el Servidor + liberaMemoria(iph); lSize=lonArchivo(fileco); if(lSize>0){ // Si el fichero tiene contenido... initParametros(ptrTrama,lSize+LONGITUD_PARAMETROS); @@ -504,6 +509,7 @@ BOOLEAN procesoInclusionClienteWinLnx(SOCKET *socket_c, TRAMA *ptrTrama,int *ido iph = copiaParametro("iph",ptrTrama); // Toma ip if (!db.Open(usuario, pasguor, datasource, catalog)) { // Error de conexión con la BD + liberaMemoria(iph); errorLog(modulo, 20, FALSE); db.GetErrorErrStr(msglog); errorInfo(modulo, msglog); @@ -516,14 +522,19 @@ BOOLEAN procesoInclusionClienteWinLnx(SOCKET *socket_c, TRAMA *ptrTrama,int *ido " WHERE ordenadores.ip = '%s'", iph); if (!db.Execute(sqlstr, tbl)) { // Error al recuperar los datos + liberaMemoria(iph); errorLog(modulo, 21, FALSE); db.GetErrorErrStr(msglog); errorInfo(modulo, msglog); + db.Close(); return (21); } if (tbl.ISEOF()) { // Si no existe el cliente + liberaMemoria(iph); errorLog(modulo, 22, FALSE); + db.liberaResult(tbl); + db.Close(); return (22); } @@ -532,15 +543,22 @@ BOOLEAN procesoInclusionClienteWinLnx(SOCKET *socket_c, TRAMA *ptrTrama,int *ido infoDebug(msglog); } if (!tbl.Get("idordenador", *idordenador)) { + liberaMemoria(iph); + db.liberaResult(tbl); tbl.GetErrorErrStr(msglog); errorInfo(modulo, msglog); + db.Close(); return (FALSE); } if (!tbl.Get("nombreordenador", nombreordenador)) { + liberaMemoria(iph); + db.liberaResult(tbl); tbl.GetErrorErrStr(msglog); errorInfo(modulo, msglog); + db.Close(); return (FALSE); } + db.liberaResult(tbl); db.Close(); if (!registraCliente(iph)) { // Incluyendo al cliente en la tabla de sokets @@ -604,6 +622,8 @@ BOOLEAN procesoInclusionCliente(SOCKET *socket_c, TRAMA *ptrTrama) { cfg = copiaParametro("cfg",ptrTrama); // Toma configuracion if (!db.Open(usuario, pasguor, datasource, catalog)) { // Error de conexión con la BD + liberaMemoria(iph); + liberaMemoria(cfg); errorLog(modulo, 20, FALSE); db.GetErrorErrStr(msglog); errorInfo(modulo, msglog); @@ -732,14 +752,35 @@ BOOLEAN actualizaConfiguracion(Database db, Table tbl, char* cfg, int ido) char msglog[LONSTD], sqlstr[LONSQL]; int lon, p, c,i, dato, swu, idsoi, idsfi,k; char *ptrPar[MAXPAR], *ptrCfg[6], *ptrDual[2], tbPar[LONSTD]; - char *disk, *par, *cpt, *sfi, *soi, *tam; // Parametros que definen una partición + char *ser, *disk, *par, *cpt, *sfi, *soi, *tam, *uso; // Parametros de configuración. char modulo[] = "actualizaConfiguracion()"; lon = 0; p = splitCadena(ptrPar, cfg, '\n'); for (i = 0; i < p; i++) { c = splitCadena(ptrCfg, ptrPar[i], '\t'); - disk = par = cpt = sfi = soi = tam = NULL; + + // Si la 1ª línea solo incluye el número de serie del equipo; actualizar BD. + if (i == 0 && c == 1) { + splitCadena(ptrDual, ptrCfg[0], '='); + ser = ptrDual[1]; + if (strlen(ser) > 0) { + // Solo actualizar si número de serie no existía. + sprintf(sqlstr, "UPDATE ordenadores SET numserie='%s'" + " WHERE idordenador=%d AND numserie IS NULL", + ser, ido); + if (!db.Execute(sqlstr, tbl)) { // Error al insertar + db.GetErrorErrStr(msglog); + errorInfo(modulo, msglog); + return (FALSE); + } + } + continue; + } + + // Distribución de particionado. + disk = par = cpt = sfi = soi = tam = uso = NULL; + splitCadena(ptrDual, ptrCfg[0], '='); disk = ptrDual[1]; // Número de disco @@ -750,7 +791,7 @@ BOOLEAN actualizaConfiguracion(Database db, Table tbl, char* cfg, int ido) if(k==2){ cpt = ptrDual[1]; // Código de partición }else{ - cpt = "0"; + cpt = (char*)"0"; } k=splitCadena(ptrDual, ptrCfg[3], '='); @@ -774,10 +815,14 @@ BOOLEAN actualizaConfiguracion(Database db, Table tbl, char* cfg, int ido) splitCadena(ptrDual, ptrCfg[5], '='); tam = ptrDual[1]; // Tamaño de la partición + splitCadena(ptrDual, ptrCfg[6], '='); + uso = ptrDual[1]; // Porcentaje de uso del S.F. + lon += sprintf(tbPar + lon, "(%s, %s),", disk, par); - sprintf(sqlstr, "SELECT numdisk,numpar,codpar,tamano,idsistemafichero,idnombreso" - " FROM ordenadores_particiones WHERE idordenador=%d AND numdisk=%s AND numpar=%s", + sprintf(sqlstr, "SELECT numdisk, numpar, codpar, tamano, uso, idsistemafichero, idnombreso" + " FROM ordenadores_particiones" + " WHERE idordenador=%d AND numdisk=%s AND numpar=%s", ido, disk, par); @@ -788,9 +833,9 @@ BOOLEAN actualizaConfiguracion(Database db, Table tbl, char* cfg, int ido) return (FALSE); } if (tbl.ISEOF()) { // Si no existe el registro - sprintf(sqlstr, "INSERT INTO ordenadores_particiones(idordenador,numdisk,numpar,codpar,tamano,idsistemafichero,idnombreso,idimagen)" - " VALUES(%d,%s,%s,0x%s,%s,%d,%d,0)", - ido, disk, par, cpt, tam, idsfi, idsoi); + sprintf(sqlstr, "INSERT INTO ordenadores_particiones(idordenador,numdisk,numpar,codpar,tamano,uso,idsistemafichero,idnombreso,idimagen)" + " VALUES(%d,%s,%s,0x%s,%s,%s,%d,%d,0)", + ido, disk, par, cpt, tam, uso, idsfi, idsoi); if (!db.Execute(sqlstr, tbl)) { // Error al insertar @@ -833,19 +878,25 @@ BOOLEAN actualizaConfiguracion(Database db, Table tbl, char* cfg, int ido) sprintf(sqlstr, "UPDATE ordenadores_particiones SET " " codpar=0x%s," " tamano=%s," + " uso=%s," " idsistemafichero=%d," " idnombreso=%d," " idimagen=0," " idperfilsoft=0," " fechadespliegue=NULL" " WHERE idordenador=%d AND numdisk=%s AND numpar=%s", - cpt, tam, idsfi, idsoi, ido, disk, par); - if (!db.Execute(sqlstr, tbl)) { // Error al recuperar los datos - errorLog(modulo, 21, FALSE); - db.GetErrorErrStr(msglog); - errorInfo(modulo, msglog); - return (FALSE); - } + cpt, tam, uso, idsfi, idsoi, ido, disk, par); + } else { // Actualizar porcentaje de uso. + sprintf(sqlstr, "UPDATE ordenadores_particiones SET " + " uso=%s" + " WHERE idordenador=%d AND numdisk=%s AND numpar=%s", + uso, ido, disk, par); + } + if (!db.Execute(sqlstr, tbl)) { // Error al recuperar los datos + errorLog(modulo, 21, FALSE); + db.GetErrorErrStr(msglog); + errorInfo(modulo, msglog); + return (FALSE); } } } @@ -2033,9 +2084,11 @@ BOOLEAN actualizaCreacionImagen(Database db, Table tbl, char* idi, char* dsk, /* Actualizar los datos de la imagen */ snprintf(sqlstr, LONSQL, - "UPDATE imagenes" - " SET idordenador=%s, numdisk=%s, numpar=%s, codpar=%s, idperfilsoft=%d, idrepositorio=%d, fechacreacion=NOW()" - " WHERE idimagen=%s", ido, dsk, par, cpt, ifs, idr, idi); + "UPDATE imagenes" + " SET idordenador=%s, numdisk=%s, numpar=%s, codpar=%s," + " idperfilsoft=%d, idrepositorio=%d," + " fechacreacion=NOW(), revision=revision+1" + " WHERE idimagen=%s", ido, dsk, par, cpt, ifs, idr, idi); if (!db.Execute(sqlstr, tbl)) { // Error al recuperar los datos errorLog(modulo, 21, FALSE); @@ -2043,6 +2096,19 @@ BOOLEAN actualizaCreacionImagen(Database db, Table tbl, char* idi, char* dsk, errorInfo(modulo, msglog); return (FALSE); } + /* Actualizar los datos en el cliente */ + snprintf(sqlstr, LONSQL, + "UPDATE ordenadores_particiones" + " SET idimagen=%s, revision=(SELECT revision FROM imagenes WHERE idimagen=%s)," + " fechadespliegue=NOW()" + " WHERE idordenador=%s AND numdisk=%s AND numpar=%s", + idi, idi, ido, dsk, par); + if (!db.Execute(sqlstr, tbl)) { // Error al recuperar los datos + errorLog(modulo, 21, FALSE); + db.GetErrorErrStr(msglog); + errorInfo(modulo, msglog); + return (FALSE); + } return (TRUE); } // ________________________________________________________________________________________________________ @@ -2321,7 +2387,7 @@ BOOLEAN RESPUESTA_RestaurarImagen(SOCKET *socket_c, TRAMA* ptrTrama) Database db; Table tbl; BOOLEAN res; - char *iph, *ido, *idi, *dsk, *par, *ifs; + char *iph, *ido, *idi, *dsk, *par, *ifs, *cfg; char modulo[] = "RESPUESTA_RestaurarImagen()"; if (!db.Open(usuario, pasguor, datasource, catalog)) { // Error de conexion @@ -2346,11 +2412,15 @@ BOOLEAN RESPUESTA_RestaurarImagen(SOCKET *socket_c, TRAMA* ptrTrama) dsk = copiaParametro("dsk",ptrTrama); // Número de disco par = copiaParametro("par",ptrTrama); // Número de partición ifs = copiaParametro("ifs",ptrTrama); // Identificador del perfil software contenido - + cfg = copiaParametro("cfg",ptrTrama); // Configuración de discos + if(cfg){ + actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador + liberaMemoria(cfg); + } res=actualizaRestauracionImagen(db, tbl, idi, dsk, par, ido, ifs); liberaMemoria(iph); - liberaMemoria(ido); + liberaMemoria(ido); liberaMemoria(idi); liberaMemoria(par); liberaMemoria(ifs); @@ -2421,8 +2491,10 @@ BOOLEAN actualizaRestauracionImagen(Database db, Table tbl, char* idi, /* Actualizar los datos de la imagen */ snprintf(sqlstr, LONSQL, "UPDATE ordenadores_particiones" - " SET idimagen=%s, idperfilsoft=%s, fechadespliegue=NOW()" - " WHERE idordenador=%s AND numdisk=%s AND numpar=%s", idi, ifs, ido, dsk, par); + " SET idimagen=%s, idperfilsoft=%s, fechadespliegue=NOW()," + " revision=(SELECT revision FROM imagenes WHERE idimagen=%s)," + " idnombreso=(SELECT idnombreso FROM perfilessoft WHERE idperfilsoft=%s)" + " WHERE idordenador=%s AND numdisk=%s AND numpar=%s", idi, ifs, idi, ifs, ido, dsk, par); if (!db.Execute(sqlstr, tbl)) { // Error al recuperar los datos errorLog(modulo, 21, FALSE); @@ -2554,7 +2626,6 @@ BOOLEAN RESPUESTA_EjecutarScript(SOCKET *socket_c, TRAMA* ptrTrama) Database db; Table tbl; char *iph, *ido,*cfg; - int res; char modulo[] = "RESPUESTA_EjecutarScript()"; @@ -2576,9 +2647,8 @@ BOOLEAN RESPUESTA_EjecutarScript(SOCKET *socket_c, TRAMA* ptrTrama) } cfg = copiaParametro("cfg",ptrTrama); // Toma configuración de particiones - if(cfg){ - res=actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador + actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador liberaMemoria(cfg); } @@ -3070,10 +3140,12 @@ BOOLEAN RESPUESTA_InventarioSoftware(SOCKET *socket_c, TRAMA* ptrTrama) { // Devuelve: // TRUE: Si el proceso es correcto // FALSE: En caso de ocurrir algún error +// +// Versión 1.1.0: Se incluye el sistema operativo. Autora: Irina Gómez - ETSII Universidad Sevilla // ________________________________________________________________________________________________________ BOOLEAN actualizaSoftware(Database db, Table tbl, char* sft, char* par,char* ido, char* npc, char* idc) { - int i, j, lon, aux, idperfilsoft; + int i, j, lon, aux, idperfilsoft, idnombreso; bool retval; char *wsft; int tbidsoftware[MAXSOFTWARE]; @@ -3121,6 +3193,12 @@ BOOLEAN actualizaSoftware(Database db, Table tbl, char* sft, char* par,char* ido lon = MAXSOFTWARE; // Limita el número de componentes software for (i = 0; i < lon; i++) { + // Primera línea es el sistema operativo: se obtiene identificador + if (i == 0) { + idnombreso = checkDato(db, tbl, rTrim(tbSoftware[i]), "nombresos", "nombreso", "idnombreso"); + continue; + } + sprintf(sqlstr, "SELECT idsoftware FROM softwares WHERE descripcion ='%s'", rTrim(tbSoftware[i])); @@ -3189,7 +3267,7 @@ BOOLEAN actualizaSoftware(Database db, Table tbl, char* sft, char* par,char* ido aux += sprintf(idsoftwares + aux, ",%d", tbidsoftware[i]); // Comprueba existencia de perfil software y actualización de éste para el ordenador - if (!cuestionPerfilSoftware(db, tbl, idc, ido, idperfilsoft, idsoftwares, + if (!cuestionPerfilSoftware(db, tbl, idc, ido, idperfilsoft, idnombreso, idsoftwares, npc, par, tbidsoftware, lon)) { errorLog(modulo, 83, FALSE); errorInfo(modulo, msglog); @@ -3210,6 +3288,7 @@ BOOLEAN actualizaSoftware(Database db, Table tbl, char* sft, char* par,char* ido // - tbl: Objeto tabla // - idcentro: Identificador del centro en la tabla // - ido: Identificador del ordenador del cliente en la tabla +// - idnombreso: Identificador del sistema operativo // - idsoftwares: Cadena con los identificadores de componentes software separados por comas // - npc: Nombre del ordenador del cliente // - particion: Número de la partición @@ -3218,9 +3297,11 @@ BOOLEAN actualizaSoftware(Database db, Table tbl, char* sft, char* par,char* ido // Devuelve: // TRUE: Si el proceso es correcto // FALSE: En caso de ocurrir algún error -//________________________________________________________________________________________________________/ +// +// Versión 1.1.0: Se incluye el sistema operativo. Autora: Irina Gómez - ETSII Universidad Sevilla +//_________________________________________________________________________________________________________ BOOLEAN cuestionPerfilSoftware(Database db, Table tbl, char* idc, char* ido, - int idperfilsoftware, char *idsoftwares, char *npc, char *par, + int idperfilsoftware, int idnombreso, char *idsoftwares, char *npc, char *par, int *tbidsoftware, int lon) { char *sqlstr, msglog[LONSTD]; int i, nwidperfilsoft; @@ -3248,8 +3329,8 @@ BOOLEAN cuestionPerfilSoftware(Database db, Table tbl, char* idc, char* ido, return (false); } if (tbl.ISEOF()) { // No existe un perfil software con esos componentes de componentes software, lo crea - sprintf(sqlstr, "INSERT perfilessoft (descripcion,idcentro,grupoid)" - " VALUES('Perfil Software (%s, Part:%s) ',%s,0)", npc, par, idc); + sprintf(sqlstr, "INSERT perfilessoft (descripcion, idcentro, grupoid, idnombreso)" + " VALUES('Perfil Software (%s, Part:%s) ',%s,0,%i)", npc, par, idc,idnombreso); if (!db.Execute(sqlstr, tbl)) { // Error al insertar db.GetErrorErrStr(msglog); errorInfo(modulo, msglog); @@ -3409,7 +3490,7 @@ BOOLEAN recibeArchivo(SOCKET *socket_c, TRAMA *ptrTrama) { BOOLEAN envioProgramacion(SOCKET *socket_c, TRAMA *ptrTrama) { char sqlstr[LONSQL], msglog[LONSTD]; - char *idp,*mar,iph[LONIP],mac[LONMAC]; + char *idp,iph[LONIP],mac[LONMAC]; Database db; Table tbl; int idx,idcomando; @@ -3464,24 +3545,19 @@ BOOLEAN envioProgramacion(SOCKET *socket_c, TRAMA *ptrTrama) return (FALSE); } - //mar = copiaParametro("mar",ptrTrama); // Toma modo de arranque si el comando es Arrancar - // Se manda por broadcast y por unicast - if (!Levanta(iph,mac,"1")) { + if (!Levanta(iph, mac, (char*)"1")) { sprintf(msglog, "%s:%s", tbErrores[32], modulo); errorInfo(modulo, msglog); - liberaMemoria(mar); return (FALSE); } - if (!Levanta(iph,mac,"2")) { + if (!Levanta(iph, mac, (char*)"2")) { sprintf(msglog, "%s:%s", tbErrores[32], modulo); errorInfo(modulo, msglog); - liberaMemoria(mar); return (FALSE); } - liberaMemoria(mar); } if (clienteDisponible(iph, &idx)) { // Si el cliente puede recibir comandos strcpy(tbsockets[idx].estado, CLIENTE_OCUPADO); // Actualiza el estado del cliente @@ -3505,6 +3581,7 @@ int main(int argc, char *argv[]) { socklen_t iAddrSize; struct sockaddr_in local, cliente; char modulo[] = "main()"; + int activo=1; /*-------------------------------------------------------------------------------------------------------- Validación de parámetros de ejecución y lectura del fichero de configuración del servicio @@ -3642,6 +3719,7 @@ int main(int argc, char *argv[]) { Creación y configuración del socket del servicio ---------------------------------------------------------------------------------------------------------*/ socket_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // Crea socket del servicio + setsockopt(socket_s, SOL_SOCKET, SO_REUSEPORT, &activo, sizeof(int)); if (socket_s == SOCKET_ERROR) { // Error al crear el socket del servicio errorLog(modulo, 13, TRUE); exit(EXIT_FAILURE); diff --git a/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.h b/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.h index cf2930a8..48f0be3a 100644 --- a/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.h +++ b/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.h @@ -117,7 +117,7 @@ BOOLEAN RESPUESTA_InventarioHardware(SOCKET *,TRAMA *); BOOLEAN actualizaHardware(Database, Table,char* ,char*,char*,char*); BOOLEAN cuestionPerfilHardware(Database,Table,char*,char*,int,char*,char*,int *,int); BOOLEAN actualizaSoftware(Database , Table , char* , char* , char*,char*,char*); -BOOLEAN cuestionPerfilSoftware(Database, Table, char*, char*,int,char*,char*,char*,int *,int); +BOOLEAN cuestionPerfilSoftware(Database, Table, char*, char*,int,int,char*,char*,char*,int *,int); BOOLEAN enviaArchivo(SOCKET *, TRAMA *); BOOLEAN recibeArchivo(SOCKET *, TRAMA *); diff --git a/admin/Sources/Services/ogAdmServerAux b/admin/Sources/Services/ogAdmServerAux index fdc98bf2..65bea5cb 100755 --- a/admin/Sources/Services/ogAdmServerAux +++ b/admin/Sources/Services/ogAdmServerAux @@ -28,10 +28,15 @@ case "$PARM1" in #1 SET_CLIENTMODE #2 template #3 pc_name o group_pc +#4 modo temporal o permanente + TEMPLATE="$PARM2" PC="$PARM3" +#incluyo parametro de MODO + MODO="$PARM4" echolog "Ejecutar $(which setclientmode) $FILE $MCASTOPT" - setclientmode $TEMPLATE $PC &>> $SERVERLOG +#incluyo parametro de MODO + setclientmode $TEMPLATE $PC $MODO &>> $SERVERLOG exit $? ;; default) diff --git a/admin/Sources/Services/opengnsys.default b/admin/Sources/Services/opengnsys.default index f998ccfb..644f516a 100644 --- a/admin/Sources/Services/opengnsys.default +++ b/admin/Sources/Services/opengnsys.default @@ -1,5 +1,5 @@ -# RUN_OGADMSERVER run OpenGnSys Admin service. -# RUN_OGADMREPO run OpenGnSys Repository Manager service. +# RUN_OGADMSERVER run OpenGnsys Admin service. +# RUN_OGADMREPO run OpenGnsys Repository Manager service. # RUN_BTTRACKER run Bittorrent Tracker # RUN_BTSEEDER starts seeding of selected torrent files # RUN_CRON run Cron script to check started processes diff --git a/admin/Sources/Services/opengnsys.init b/admin/Sources/Services/opengnsys.init index 2912811e..548843fa 100755 --- a/admin/Sources/Services/opengnsys.init +++ b/admin/Sources/Services/opengnsys.init @@ -6,8 +6,8 @@ # Required-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 1 -# Short-Description: Servicios del sistema OpenGnSys -# Description: Servicios del sistema OpenGnSys +# Short-Description: Servicios del sistema OpenGnsys +# Description: Servicios del sistema OpenGnsys ### END INIT INFO # @@ -19,7 +19,7 @@ IMAGEDIR=$BASEDIR/images CLIENTLOGDIR=$BASEDIR/log/clients # -# Servidor de OpenGnSys +# Servidor de OpenGnsys # SERVERNAME=ogAdmServer SERVERDAEMON=$BASEDIR/sbin/$SERVERNAME @@ -126,7 +126,7 @@ config() { } arranca_demonios() { - # Comprobar que está instalado OpenGnSys. + # Comprobar que está instalado OpenGnsys. if [ ! -d $BASEDIR ]; then $ACTIONMSG "ERROR: No existe el directorio $BASEDIR" $FAILMSG diff --git a/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php b/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php index 5bef96ea..f0481d5b 100644 --- a/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php +++ b/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php @@ -40,8 +40,8 @@ if (!$cmd) - '?> - '?> + '?> + '?> printJavascript('../xajax/'); @@ -50,7 +50,7 @@ $xajax->printJavascript('../xajax/'); - - @@ -93,13 +93,13 @@ switch($ambito){ - " onClick="codeCloneRemotePartition(this.form)"> + " onClick="codeCloneRemotePartition(this.form)"> - - " onClick="codeDeployImage(this.form)"> - " onClick="modificarCodigo()"> + " onClick="codeDeployImage(this.form)"> + " onClick="modificarCodigo()"> - - + + diff --git a/admin/WebConsole/asistentes/AsistenteParticionado.php b/admin/WebConsole/asistentes/AsistenteParticionado.php index 917b832e..f1ecc803 100644 --- a/admin/WebConsole/asistentes/AsistenteParticionado.php +++ b/admin/WebConsole/asistentes/AsistenteParticionado.php @@ -4,6 +4,9 @@ // Autor: Antonio J. Doblas Viso // Baso en Codigo Comando.php de : Jose Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla // Xajax +// version 1.1: Se incluye aviso para particiones GTP. +// autor: Irina Gomez, ETSII Universidad de Sevilla +// fecha: 2016-06-21 // ************************************************************************************************************************************************* @@ -52,6 +55,7 @@ if (!$cmd) '?> '?> + '?> printJavascript('../xajax/'); @@ -97,7 +102,7 @@ function doOnload(){ echo '  '.$TbMsg[1].' : '.$textambito.'  

'; - $sws=0x11111; // Mostrar todas las configuraciones diferentes. + $sws=bindec('0x11111'); // Mostrar todas las configuraciones diferentes. $configuraciones = pintaConfiguraciones($cmd,$idambito,$ambito,7,$sws,false); global $tbKeys; // Tabla contenedora de claves de configuración global $conKeys; // Contador de claves de configuración @@ -154,6 +159,9 @@ function doOnload(){ + + + diff --git a/admin/WebConsole/asistentes/AsistenteUpdateCache.php b/admin/WebConsole/asistentes/AsistenteUpdateCache.php index 86a867b1..4d6d0f61 100644 --- a/admin/WebConsole/asistentes/AsistenteUpdateCache.php +++ b/admin/WebConsole/asistentes/AsistenteUpdateCache.php @@ -50,8 +50,8 @@ if (!$cmd) - '?> - '?> + '?> + '?> printJavascript('../xajax/'); -aulas 16->ordenadores # idambito: id de los elementos en su correspondiente tabla-ambito (aulas, ordenadores...) # nombreambito: nombre del elemento. @@ -108,7 +108,7 @@ switch($ambito){ - @@ -119,7 +119,7 @@ switch($ambito){
- '?> -texto='SELECT aulas.pormul,aulas.ipmul,aulas.modomul,aulas.velmul,aulas.modp2p,aulas.timep2p FROM aulas where aulas.idaula=' . $idambito ; -} - -if ($ambito == 8) -{ -$cmd->texto='SELECT aulas.pormul,aulas.ipmul,aulas.modomul,aulas.velmul,aulas.modp2p,aulas.timep2p FROM aulas JOIN gruposordenadores ON aulas.idaula=gruposordenadores.idaula where gruposordenadores.idgrupo=' . $idambito ; -} - -if ($ambito == 16) -{ -$cmd->texto='SELECT aulas.pormul,aulas.ipmul,aulas.modomul,aulas.velmul,aulas.modp2p,aulas.timep2p FROM aulas JOIN ordenadores ON ordenadores.idaula=aulas.idaula where ordenadores.idordenador=' . $idambito ; -} - - $rs=new Recordset; - $rs->Comando=&$cmd; -if ($rs->Abrir()){ - $rs->Primero(); - $SelectHtml = $TbMsg["WDI24"] . ':
'; - $rs->Siguiente(); - $SelectHtml.= $TbMsg["WDI25"] . ':
'; - $rs->Siguiente(); - switch ($rs->campos["modomul"]) - { - case 1: - $modomulticast="half-duplex"; - break; - default: - $modomulticast="full-duplex"; - break; - } - $SelectHtml.= $TbMsg["WDI26"] . ':
'; - $rs->Siguiente(); - $SelectHtml.= $TbMsg["WDI27"] . ':
'; - - $rs->Cerrar(); - } - $SelectHtml.= $TbMsg["WDI28"] . ':
'; - $SelectHtml.= $TbMsg["WDI29"] . ' :
'; - - return($SelectHtml); -} - - -#devuelve los elementos [texto] p2p para un formulario. -#$ambito (aula=4 y ordenadores=16) -function htmlForm_p2p($cmd,$ambito,$idambito) -{ -global $TbMsg; -//if (isset($_GET["idambito"])) $idambito=$_GET["idambito"]; -if ($ambito == 4) -{ -$cmd->texto='SELECT aulas.modp2p,aulas.timep2p FROM aulas where aulas.idaula=' . $idambito ; -} -if ($ambito == 8) -{ -$cmd->texto='SELECT aulas.modp2p,aulas.timep2p FROM aulas JOIN gruposordenadores ON aulas.idaula=gruposordenadores.idaula where gruposordenadores.idgrupo=' . $idambito ; -} - - -if ($ambito == 16) -{ -$cmd->texto='SELECT aulas.modp2p,aulas.timep2p FROM aulas JOIN ordenadores ON ordenadores.idaula=aulas.idaula where ordenadores.idordenador=' . $idambito ; -} - - $SelectHtml=""; - $rs=new Recordset; - $rs->Comando=&$cmd; - if ($rs->Abrir()){ - $rs->Primero(); - $SelectHtml.= $TbMsg["WDI26"] . ' :
'; - $rs->Siguiente(); - $SelectHtml.= $TbMsg["WDI30"] . ' :
'; - $rs->Siguiente(); - $rs->Cerrar(); - } - -return($SelectHtml); -} - - -function htmlForm_unicast($cmd,$ambito,$idambito) -{ -global $TbMsg; -//if (isset($_GET["idambito"])) $idambito=$_GET["idambito"]; -if ($ambito == 4) -{ -$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; -} - -if ($ambito == 8) -{ -$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where grupoid=' . $idambito ; -} -if ($ambito == 16) -{ -$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; -} - - $SelectHtml=""; - $rs=new Recordset; - $rs->Comando=&$cmd; - - if ($rs->Abrir()){ - $rs->Primero(); - $ucastclient=""; - while (!$rs->EOF){ - $ucastclient.= $rs->campos["ip"] . ":" ; - $rs->Siguiente(); - } - $rs->Cerrar(); - } - $SelectHtml.= $TbMsg["WDI24"] . ' :
'; - $SelectHtml.= $TbMsg["WDI28"] . ' :
'; - - return($SelectHtml); -} - - - -function htmlOPTION_equipos($cmd,$ambito,$idambito) -{ - -//if (isset($_GET["idambito"])) $idambito=$_GET["idambito"]; -if ($ambito == 4) -{ -$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; -} - -if ($ambito == 8) -{ -$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where grupoid=' . $idambito ; -} -if ($ambito == 16) -{ -$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; -} - - $SelectHtml=""; - $rs=new Recordset; - $rs->Comando=&$cmd; - - if ($rs->Abrir()){ - $rs->Primero(); - while (!$rs->EOF){ - $SelectHtml.=''; - $rs->Siguiente(); - } - $rs->Cerrar(); - } - //$SelectHtml.= ''; - return($SelectHtml); -} - - - - - - -function htmlOPTION_images($cmd,$ambito,$idambito) -{ -if ($ambito == 4) -{ -$subconsultarepo='SELECT DISTINCT idrepositorio from ordenadores where idaula=' . $idambito ; -} -if ($ambito == 8) -{ -$subconsultarepo='SELECT DISTINCT idrepositorio FROM ordenadores where grupoid=' . $idambito ; -} -if ($ambito == 16) -{ -$subconsultarepo='SELECT idrepositorio FROM ordenadores where idordenador=' . $idambito ; -} - - - $SelectHtml=""; - // 1.0.5 imagenes.tipo =1 para que solo muestre las monoloticas. - $cmd->texto="SELECT *,repositorios.ip as iprepositorio FROM imagenes - INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio AND repositorios.idrepositorio=(" . $subconsultarepo . ") WHERE imagenes.tipo=1"; - $rs=new Recordset; - $rs->Comando=&$cmd; - - if ($rs->Abrir()){ - $rs->Primero(); - while (!$rs->EOF){ - $SelectHtml.=''; - $rs->Siguiente(); - } - $rs->Cerrar(); - } - else - { - $SelectHtml.=''; - - } - return($SelectHtml); -} - - - -function HTMLSELECT_imagenes($cmd,$idimagen,$numpar,$codpar,$icp,$sw) -{ - $SelectHtml=""; - $cmd->texto="SELECT *,repositorios.ip as iprepositorio FROM imagenes - INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio"; - if($sw) // Imágenes con el mismo tipo de partición - $cmd->texto.= " WHERE imagenes.codpar=".$codpar; - else - $cmd->texto.= " WHERE imagenes.codpar<>".$codpar; - - $cmd->texto.=" AND imagenes.numpar>0 AND imagenes.codpar>0 AND imagenes.idrepositorio>0"; // La imagene debe existir y estar creada - $rs=new Recordset; - $rs->Comando=&$cmd; - if($sw) $des=1; else $des=0; - $SelectHtml.= ''; - return($SelectHtml); -} - - - -function htmlOPTION_typepartnotcache($cmd) -{ - $SelectHtml=""; - $cmd->texto='SELECT tipopar FROM tipospar WHERE NOT tipopar = "CACHE"'; - $rs=new Recordset; - $rs->Comando=&$cmd; - //$SelectHtml.= ''; - return($SelectHtml); -} - - -function htmlForm_typepart($cmd,$numpar) -{ - $SelectHtml=""; - $cmd->texto='SELECT DISTINCT tipopar FROM tipospar - JOIN ordenadores_particiones ON ordenadores_particiones.codpar = tipospar.codpar - WHERE numpar = ' .$numpar; - $rs=new Recordset; - $rs->Comando=&$cmd; - - if ($rs->Abrir()){ - $rs->Primero(); - while (!$rs->EOF){ - $valor=$rs->campos["tipopar"]; - $SelectHtml.=''; - $rs->Siguiente(); - } - $rs->Cerrar(); - } - return($SelectHtml); -} - - -function htmlForm_typepartnotcacheEngine10($npart) -{ -$SelectHtml=""; -if ($npart == 4) { - $SelectHtml.=''; -} -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -if ($npart <= 4) { - $SelectHtml.=''; -} -return($SelectHtml); -} - -function htmlForm_typepartnotcacheGPT($npart) -{ -$SelectHtml=""; -if ($npart == 4) { - $SelectHtml.=''; -} -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -$SelectHtml.=''; -return($SelectHtml); -} - -function htmlForm_sizepart($cmd,$numpar) -{ - $SelectHtml=""; - $cmd->texto='SELECT DISTINCT tamano FROM ordenadores_particiones WHERE numpar = ' .$numpar . ' AND NOT tamano = 0'; - $rs=new Recordset; - $rs->Comando=&$cmd; - - if ($rs->Abrir()){ - $rs->Primero(); - while (!$rs->EOF){ - $SelectHtml.=''; - $rs->Siguiente(); - } - $rs->Cerrar(); - } - return($SelectHtml); -} - - -function pintaParticionesAsistenteDeployImage($cmd,$configuraciones,$idordenadores,$cc) -{ - global $tbKeys; // Tabla contenedora de claves de configuración - global $conKeys; // Contador de claves de configuración - global $TbMsg; - - $colums=7; - echo ''; - echo ' '.$TbMsg[20].' '; // Número de partición - echo ' '.$TbMsg[24].' '; // Tipo de partición - echo ' '.$TbMsg[27].' '; // Sistema de ficheros - echo ' '.$TbMsg[21].' '; // Sistema Operativo Instalado - echo ' '.$TbMsg[22].' '; // Tamaño - echo ' '.$TbMsg[25].' '; // Imagen instalada - echo ' '.$TbMsg[26].' '; // Perfil software - echo ''; - - $auxCfg=split("@",$configuraciones); // Crea lista de particiones - for($i=0;$i0) - echo''.chr(13); - echo' '.$tbKeys[$k]["numpar"].' '.chr(13); - echo' '.$tbKeys[$k]["tipopar"].' '.chr(13); - - //echo' '.$tbKeys[$k]["sistemafichero"].' '.chr(13); - echo' '.tomaSistemasFicheros($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); - - //echo ' '.$tbKeys[$k]["nombreso"].' '.chr(13); - echo ' '.tomaNombresSO($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); - - //echo' '.formatomiles($tbKeys[$k]["tamano"]).' '.chr(13); - echo' '.tomaTamano($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); - - //echo' '.$tbKeys[$k]["imagen"].' '.chr(13); - echo' '.tomaImagenes($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); - - //echo' '.$tbKeys[$k]["perfilsoft"].' '.chr(13); - echo' '.tomaPerfiles($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); - - echo''.chr(13); - break; - } - } - } - } - // Mostrar información del disco, si se ha obtenido. - if (!empty ($disksize)) { - echo''.chr(13); - echo' '.$TbMsg[35].' '.chr(13); - echo''.chr(13); - echo''.chr(13); - echo''.chr(13); - echo' '.$disksize.' '.chr(13); - echo''.chr(13); - echo''.chr(13); - echo''.chr(13); - } - echo ' '; -} - -?> +texto='SELECT aulas.pormul,aulas.ipmul,aulas.modomul,aulas.velmul,aulas.modp2p,aulas.timep2p FROM aulas where aulas.idaula=' . $idambito ; +} + +if ($ambito == 8) +{ +$cmd->texto='SELECT aulas.pormul,aulas.ipmul,aulas.modomul,aulas.velmul,aulas.modp2p,aulas.timep2p FROM aulas JOIN gruposordenadores ON aulas.idaula=gruposordenadores.idaula where gruposordenadores.idgrupo=' . $idambito ; +} + +if ($ambito == 16) +{ +$cmd->texto='SELECT aulas.pormul,aulas.ipmul,aulas.modomul,aulas.velmul,aulas.modp2p,aulas.timep2p FROM aulas JOIN ordenadores ON ordenadores.idaula=aulas.idaula where ordenadores.idordenador=' . $idambito ; +} + + $rs=new Recordset; + $rs->Comando=&$cmd; +if ($rs->Abrir()){ + $rs->Primero(); + $SelectHtml = $TbMsg["WDI24"] . ':
'; + $rs->Siguiente(); + $SelectHtml.= $TbMsg["WDI25"] . ':
'; + $rs->Siguiente(); + switch ($rs->campos["modomul"]) + { + case 1: + $modomulticast="half-duplex"; + break; + default: + $modomulticast="full-duplex"; + break; + } + $SelectHtml.= $TbMsg["WDI26"] . ':
'; + $rs->Siguiente(); + $SelectHtml.= $TbMsg["WDI27"] . ':
'; + + $rs->Cerrar(); + } + $SelectHtml.= $TbMsg["WDI28"] . ':
'; + $SelectHtml.= $TbMsg["WDI29"] . ' :
'; + + return($SelectHtml); +} + + +#devuelve los elementos [texto] p2p para un formulario. +#$ambito (aula=4 y ordenadores=16) +function htmlForm_p2p($cmd,$ambito,$idambito) +{ +global $TbMsg; +//if (isset($_GET["idambito"])) $idambito=$_GET["idambito"]; +if ($ambito == 4) +{ +$cmd->texto='SELECT aulas.modp2p,aulas.timep2p FROM aulas where aulas.idaula=' . $idambito ; +} +if ($ambito == 8) +{ +$cmd->texto='SELECT aulas.modp2p,aulas.timep2p FROM aulas JOIN gruposordenadores ON aulas.idaula=gruposordenadores.idaula where gruposordenadores.idgrupo=' . $idambito ; +} + + +if ($ambito == 16) +{ +$cmd->texto='SELECT aulas.modp2p,aulas.timep2p FROM aulas JOIN ordenadores ON ordenadores.idaula=aulas.idaula where ordenadores.idordenador=' . $idambito ; +} + + $SelectHtml=""; + $rs=new Recordset; + $rs->Comando=&$cmd; + if ($rs->Abrir()){ + $rs->Primero(); + $SelectHtml.= $TbMsg["WDI26"] . ' :
'; + $rs->Siguiente(); + $SelectHtml.= $TbMsg["WDI30"] . ' :
'; + $rs->Siguiente(); + $rs->Cerrar(); + } + +return($SelectHtml); +} + + +function htmlForm_unicast($cmd,$ambito,$idambito) +{ +global $TbMsg; +//if (isset($_GET["idambito"])) $idambito=$_GET["idambito"]; +if ($ambito == 4) +{ +$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; +} + +if ($ambito == 8) +{ +$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where grupoid=' . $idambito ; +} +if ($ambito == 16) +{ +$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; +} + + $SelectHtml=""; + $rs=new Recordset; + $rs->Comando=&$cmd; + + if ($rs->Abrir()){ + $rs->Primero(); + $ucastclient=""; + while (!$rs->EOF){ + $ucastclient.= $rs->campos["ip"] . ":" ; + $rs->Siguiente(); + } + $rs->Cerrar(); + } + $SelectHtml.= $TbMsg["WDI24"] . ' :
'; + $SelectHtml.= $TbMsg["WDI28"] . ' :
'; + + return($SelectHtml); +} + + + +function htmlOPTION_equipos($cmd,$ambito,$idambito) +{ + +//if (isset($_GET["idambito"])) $idambito=$_GET["idambito"]; +if ($ambito == 4) +{ +$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; +} + +if ($ambito == 8) +{ +$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where grupoid=' . $idambito ; +} +if ($ambito == 16) +{ +$cmd->texto='SELECT nombreordenador,idordenador,ip FROM ordenadores where idaula=' . $idambito ; +} + + $SelectHtml=""; + $rs=new Recordset; + $rs->Comando=&$cmd; + + if ($rs->Abrir()){ + $rs->Primero(); + while (!$rs->EOF){ + $SelectHtml.=''; + $rs->Siguiente(); + } + $rs->Cerrar(); + } + //$SelectHtml.= ''; + return($SelectHtml); +} + + + + + + +function htmlOPTION_images($cmd,$ambito,$idambito) +{ +// 1.1 Imagenes de todos los repositorios de la UO. +if ($ambito == 4) +{ +// ambito aulas +$subconsultarepo='select idrepositorio from repositorios INNER JOIN aulas where repositorios.idcentro=aulas.idcentro AND idaula='.$idambito; +} +if ($ambito == 8) +{ +$subconsultarepo='select idrepositorio from repositorios INNER JOIN aulas INNER JOIN gruposordenadores where repositorios.idcentro=aulas.idcentro AND aulas.idaula=gruposordenadores.idaula AND idgrupo='.$idambito; +} +if ($ambito == 16) +{ +$subconsultarepo='select repositorios.idrepositorio from repositorios INNER JOIN aulas INNER JOIN ordenadores where repositorios.idcentro=aulas.idcentro AND aulas.idaula=ordenadores.idaula AND idordenador='.$idambito; +} + + + $SelectHtml=""; + // 1.0.5 imagenes.tipo =1 para que solo muestre las monoloticas. + $cmd->texto="SELECT *,repositorios.ip as iprepositorio, repositorios.nombrerepositorio as nombrerepo FROM imagenes + INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio + AND repositorios.idrepositorio IN (" . $subconsultarepo . ") WHERE imagenes.tipo=1 ORDER BY imagenes.descripcion"; + $rs=new Recordset; + $rs->Comando=&$cmd; + + if ($rs->Abrir()){ + $rs->Primero(); + while (!$rs->EOF){ + $SelectHtml.=''; + $rs->Siguiente(); + } + $rs->Cerrar(); + } + else + { + $SelectHtml.=''; + + } + return($SelectHtml); +} + + + +function HTMLSELECT_imagenes($cmd,$idimagen,$numpar,$codpar,$icp,$sw) +{ + $SelectHtml=""; + $cmd->texto="SELECT *,repositorios.ip as iprepositorio FROM imagenes + INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio"; + if($sw) // Imágenes con el mismo tipo de partición + $cmd->texto.= " WHERE imagenes.codpar=".$codpar; + else + $cmd->texto.= " WHERE imagenes.codpar<>".$codpar; + + $cmd->texto.=" AND imagenes.numpar>0 AND imagenes.codpar>0 AND imagenes.idrepositorio>0"; // La imagene debe existir y estar creada + $rs=new Recordset; + $rs->Comando=&$cmd; + if($sw) $des=1; else $des=0; + $SelectHtml.= ''; + return($SelectHtml); +} + + + +function htmlOPTION_typepartnotcache($cmd) +{ + $SelectHtml=""; + $cmd->texto='SELECT tipopar FROM tipospar WHERE NOT tipopar = "CACHE"'; + $rs=new Recordset; + $rs->Comando=&$cmd; + //$SelectHtml.= ''; + return($SelectHtml); +} + + +function htmlForm_typepart($cmd,$numpar) +{ + $SelectHtml=""; + $cmd->texto='SELECT DISTINCT tipopar FROM tipospar + JOIN ordenadores_particiones ON ordenadores_particiones.codpar = tipospar.codpar + WHERE numpar = ' .$numpar; + $rs=new Recordset; + $rs->Comando=&$cmd; + + if ($rs->Abrir()){ + $rs->Primero(); + while (!$rs->EOF){ + $valor=$rs->campos["tipopar"]; + $SelectHtml.=''; + $rs->Siguiente(); + } + $rs->Cerrar(); + } + return($SelectHtml); +} + + +function htmlForm_typepartnotcacheEngine10($npart) +{ +$SelectHtml=""; +if ($npart == 4) { + $SelectHtml.=''; +} +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +if ($npart <= 4) { + $SelectHtml.=''; +} +return($SelectHtml); +} + +function htmlForm_typepartnotcacheGPT($npart) +{ +$SelectHtml=""; +if ($npart == 4) { + $SelectHtml.=''; +} +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +$SelectHtml.=''; +return($SelectHtml); +} + +function htmlForm_sizepart($cmd,$numpar) +{ + $SelectHtml=""; + $cmd->texto='SELECT DISTINCT tamano FROM ordenadores_particiones WHERE numpar = ' .$numpar . ' AND NOT tamano = 0'; + $rs=new Recordset; + $rs->Comando=&$cmd; + + if ($rs->Abrir()){ + $rs->Primero(); + while (!$rs->EOF){ + $SelectHtml.=''; + $rs->Siguiente(); + } + $rs->Cerrar(); + } + return($SelectHtml); +} + + +function pintaParticionesAsistenteDeployImage($cmd,$configuraciones,$idordenadores,$cc) +{ + global $tbKeys; // Tabla contenedora de claves de configuración + global $conKeys; // Contador de claves de configuración + global $TbMsg; + + $colums=7; + echo ''; + echo ' '.$TbMsg[20].' '; // Número de partición + echo ' '.$TbMsg[24].' '; // Tipo de partición + echo ' '.$TbMsg[27].' '; // Sistema de ficheros + echo ' '.$TbMsg[21].' '; // Sistema Operativo Instalado + echo ' '.$TbMsg[22].' '; // Tamaño + echo ' '.$TbMsg[25].' '; // Imagen instalada + echo ' '.$TbMsg[26].' '; // Perfil software + echo ''; + + $auxCfg=split("@",$configuraciones); // Crea lista de particiones + for($i=0;$i0) + echo''.chr(13); + echo' '.$tbKeys[$k]["numpar"].' '.chr(13); + echo' '.$tbKeys[$k]["tipopar"].' '.chr(13); + + //echo' '.$tbKeys[$k]["sistemafichero"].' '.chr(13); + echo' '.tomaSistemasFicheros($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); + + //echo ' '.$tbKeys[$k]["nombreso"].' '.chr(13); + echo ' '.tomaNombresSO($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); + + //echo' '.formatomiles($tbKeys[$k]["tamano"]).' '.chr(13); + echo' '.tomaTamano($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); + + //echo' '.$tbKeys[$k]["imagen"].' '.chr(13); + echo' '.tomaImagenes($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); + + //echo' '.$tbKeys[$k]["perfilsoft"].' '.chr(13); + echo' '.tomaPerfiles($tbKeys[$k]["numpar"],$idordenadores).' '.chr(13); + + echo''.chr(13); + break; + } + } + } + } + // Mostrar información del disco, si se ha obtenido. + if (!empty ($disksize)) { + echo''.chr(13); + echo' '.$TbMsg[35].' '.chr(13); + echo''.chr(13); + echo''.chr(13); + echo''.chr(13); + echo' '.$disksize.' '.chr(13); + echo''.chr(13); + echo''.chr(13); + echo''.chr(13); + } + echo ' '; +} + +?> diff --git a/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php b/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php index 4cf3fead..d9b1cfa1 100644 --- a/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php +++ b/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php @@ -3,17 +3,17 @@ - +
- +

- +
- +
- +
- + -
-
-
+ +
+
+
- + - +
- +
- +
'.$TbMsg[20].' '.$p.' + '.$TbMsg[20].' '.$p.'
- + '; @@ -47,7 +47,7 @@ for ($p=1; $p<4; $p++) { - + + : diff --git a/admin/WebConsole/asistentes/includes/asistentes/formParticionado_msdos.php b/admin/WebConsole/asistentes/includes/asistentes/formParticionado_msdos.php index 01b17917..b1d6b079 100644 --- a/admin/WebConsole/asistentes/includes/asistentes/formParticionado_msdos.php +++ b/admin/WebConsole/asistentes/includes/asistentes/formParticionado_msdos.php @@ -59,7 +59,7 @@ for ($p=1; $p<4; $p++) {
--> - + + : diff --git a/admin/WebConsole/asistentes/includes/capturaacciones.php b/admin/WebConsole/asistentes/includes/capturaacciones.php index e26e38e6..a6fa089d 100644 --- a/admin/WebConsole/asistentes/includes/capturaacciones.php +++ b/admin/WebConsole/asistentes/includes/capturaacciones.php @@ -1,4 +1,4 @@ - -
- - - - - - - + + + + + + + + diff --git a/admin/WebConsole/asistentes/includes/opcionesacciones.php b/admin/WebConsole/asistentes/includes/opcionesacciones.php index 2eeaf1ab..a598b090 100644 --- a/admin/WebConsole/asistentes/includes/opcionesacciones.php +++ b/admin/WebConsole/asistentes/includes/opcionesacciones.php @@ -1,4 +1,4 @@ - -

+

- + - +

- + - + - + - + - + - + - + - - + + - + - + - + - - + + - +
   
    
    

  

 
 
     
   
 
      
 
 
 
    
   
 
      
diff --git a/admin/WebConsole/asistentes/jscripts/EjecutarScripts.js b/admin/WebConsole/asistentes/jscripts/EjecutarScripts.js index 616bc470..5452cf97 100644 --- a/admin/WebConsole/asistentes/jscripts/EjecutarScripts.js +++ b/admin/WebConsole/asistentes/jscripts/EjecutarScripts.js @@ -17,7 +17,7 @@ // Pedir confirmación si clonación masiva por Unicast. if (document.fdatosejecucion.ambito.value!=16 && document.fdatos.idmetodo !== undefined && - (document.fdatos.idmetodo.value=="UNICAST" || document.fdatos.idmetodo.value=="UNICAST-DIRECT")) { + (document.fdatos.idmetodo.value=="UNICAST" || document.fdatos.idmetodo.value=="UNICAST-DIRECT")) { if (confirm(TbMsg[4]) !== true) { cancelar(); return false; diff --git a/admin/WebConsole/asistentes/jscripts/asistentes.js b/admin/WebConsole/asistentes/jscripts/asistentes.js index 1e9e3d95..b47e888b 100644 --- a/admin/WebConsole/asistentes/jscripts/asistentes.js +++ b/admin/WebConsole/asistentes/jscripts/asistentes.js @@ -6,12 +6,15 @@ // Nombre del fichero: asistentes.js // Descripción : // Este fichero implementa las funciones javascript del fichero AsistentesEjecutarScripts.php (Comandos) -// version 1.0.6b y 1.1: codeDeployImage: Compone atributo para el comando restaurar imagen (ticket #757) +// version 1.1: cliente con varios repositorios - Imagenes de todos los repositorios de la UO. +// autor: Irina Gomez, Universidad de Sevilla +// fecha 2015-06-17 +// version 1.1: showPartitionForm: Se incluye aviso para particiones GTP. // autor: Irina Gomez, ETSII Universidad de Sevilla -// fecha: 2016-10-27 -// versión 1.0.6b: Si existe Cache al crear las particiones reservamos la cuarta libre (ticket #753) +// fecha: 2016-06-21 +// version 1.1: codeDeployImage: Compone atributo para el comando restaurar imagen (ticket #757) // autor: Irina Gomez, ETSII Universidad de Sevilla -// fecha: 2016-12-15 +// fecha: 2016-10-27 // *********************************************************************************************************** function codeCloneRemotePartition(form){ @@ -67,13 +70,16 @@ switch (form.idmetodo.value) protocol="UNICAST-DIRECT"; break; } + // Datos imagen var imagen = form.idimagen.value.split("_"); + //form.codigo.value="deployImage REPO /"; if (form.modo[0].checked) { // UHU - Distinguimos entre disco y particion, el valor de idparticion sera disco;particion. eje. 1;1 var diskPart = form.idparticion.value.split(";"); + var imagen = form.idimagen.value.split("_"); command="deployImage " + imagen[0] + " /" + imagen[1] + " "+diskPart[0]+" " + diskPart[1] + " " + protocol ; form.codigo.value="\ ogEcho log session \"[0] $MSG_SCRIPTS_TASK_START " + command + "\"\n \ " + @@ -82,11 +88,11 @@ command + " \n"; // Atributos para comando RestaurarImagen form.atrib_restore.value = "dsk=" + diskPart[0] + "@par="+ diskPart[1] +"@idi=" +imagen[2] + "@nci="+imagen[1] + "@ipr="+ imagen[0] +"@ifs=" +imagen[3] + - "@ptc="+protocol +"@"; + "@ptc="+protocol +"@"; } else { - command="updateCache REPO /" + imagen[1] + ".img" + " " + protocol ; + command="updateCache REPO /" + imagen[1] + ".img" + " " + protocol ; form.codigo.value="\ ogEcho log session \"[0] $MSG_SCRIPTS_TASK_START " + command +"\"\n \ " + command + " \n"; @@ -101,29 +107,36 @@ function modificarCodigo() { } function codeParticionado(form){ - var errorMsg = "¡El espacio libre en disco no puede ser menor que 0!"; var n_disk = form.n_disk.value; var tipo_part_table = form.tipo_part_table.value; // Comprobamos si la opcion elejida es GPT o MSDOS para llamar a una funcion u otra if(tipo_part_table == "GPT"){ + var freediskGPT = parseInt(document.getElementById("freediskGPT").value); // Comprobamos que el espacio libre en el disco no sea negativo, si lo es, dar aviso - if(parseInt(document.getElementById("freediskGPT").value) < 0){ - alert(errorMsg); + if(freediskGPT < 0){ + alert(TbMsg['NODISKSIZE']); + } + else if (!validaCache(freediskGPT)) { + alert(TbMsg['NOCACHESIZE']); } else{ codeParticionadoGPT(form); } } else{ + var freedisk = parseInt(document.getElementById("freedisk").value); // Comprobamos que el espacio libre en el disco no sea negativo, si lo es, dar aviso - if(parseInt(document.getElementById("freedisk").value) < 0){ - alert(errorMsg); + if(freedisk < 0){ + alert(TbMsg['NODISKSIZE']); + } + else if (!validaCache(freedisk)) { + alert(TbMsg['NOCACHESIZE']); } else{ codeParticionadoMSDOS(form); } } - + } @@ -131,26 +144,18 @@ function codeParticionadoMSDOS (form) { var partCode=""; var logicalCode=""; var sizecacheCode=""; - // cacheCode: codigo para preparar la particion cache - var cacheCode=""; - // cacheInit: codigo para crear la particion cache, al final de todo el proceso - var cacheInit=""; + var cacheCode; var cacheSize; var extended=false; var n_disk = form.n_disk.value; var tipo_part_table = form.tipo_part_table.value; var maxParts = 4; - var emptyCache = ""; + var swapPart = new Array(); + var swapCode = ""; // Comprobamos si esta seleccionada la cuarta particion y no es CACHE - if(form.check4.checked) { - if (form.part4.value == "CACHE") { - // Si existe Cache al crear las particiones reservamos la cuarta libre - emptyCache = " EMPTY:0"; - } else { - maxParts = 5; - } - } + if(form.check4.checked && form.part4.value != "CACHE") + maxParts = 5; for (var nPart=1; nPart/dev/null | tee -a $OGLOGCOMMAND \n "; +sizecache=`ogGetCacheSize` \n "; cacheCode="\ ogEcho session \"[30] $MSG_HELP_ogUpdatePartitionTable "+n_disk+"\"\n \ +ogCreatePartitionTable "+n_disk+" "+tipo_part_table +" \n \ ogDeletePartitionTable "+n_disk+" \n \ -ogExecAndLog command ogUpdatePartitionTable "+n_disk+" \n \ "; +ogExecAndLog command ogUpdatePartitionTable "+n_disk+" \n \ +ogEcho session \"[50] $MSG_HELP_ogCreateCache\"\n \ +initCache "+n_disk+" $sizecache NOMOUNT &>/dev/null \n "; } else { if (form.size4.value == "CUSTOM") { cacheSize = form.size4custom.value; } else { cacheSize = form.size4.value; } - cacheInit="initCache " + n_disk + " " + cacheSize + " &>/dev/null | tee -a $OGLOGCOMMAND \n "; cacheCode="\ ogEcho session \"[30] $MSG_HELP_ogUpdatePartitionTable "+n_disk+"\"\n \ +ogCreatePartitionTable "+n_disk+" "+tipo_part_table +" \n \ ogDeletePartitionTable "+n_disk+" \n \ -ogUpdatePartitionTable "+n_disk+" \n \ "; +ogUpdatePartitionTable "+n_disk+" \n \ +ogEcho session \"[50] $MSG_HELP_ogCreateCache\"\n \ +initCache " + n_disk + " " + cacheSize + " NOMOUNT &>/dev/null"; } } else { cacheCode="\ ogEcho session \"[30] $MSG_HELP_ogUpdatePartitionTable "+n_disk+"\"\n \ +ogCreatePartitionTable "+n_disk+" "+tipo_part_table +" \n \ ogDeletePartitionTable "+n_disk+" \n \ -ogUpdatePartitionTable "+n_disk+" \n \ "; +ogUpdatePartitionTable "+n_disk+" \n"; partCode += " EMPTY:0"; } } @@ -230,8 +250,14 @@ partCode += " EMPTY:0"; if (partType.value == "CUSTOM" ) { var partTypeCustom=eval("form.part"+nPart+"custom"); logicalCode += " " + partTypeCustom.value; + // Partición swap + if (partTypeCustom.value == "LINUX-SWAP") + swapPart.push(nPart); } else { logicalCode += " " + partType.value; + // Partición swap + if (partType.value == "LINUX-SWAP") + swapPart.push(nPart); } var partSize=eval("form.size"+nPart); if (partSize.value == "CUSTOM" ) { @@ -247,25 +273,36 @@ partCode += " EMPTY:0"; partCode += logicalCode; } + // Formateo de la partición swap + if (swapPart.length > 0) { + for (var i=0; i < swapPart.length; i++) { + swapCode += "ogEcho session log \"$MSG_HELP_ogFormat "+n_disk+" "+swapPart[i]+" LINUX-SWAP \" \n " ; + swapCode += "ogExecAndLog command session log ogFormat "+n_disk+" "+swapPart[i]+" LINUX-SWAP \n "; + } + + } + form.codigo.value="\ -" + sizecacheCode + " \ -ogCreatePartitionTable "+n_disk+" "+tipo_part_table +" \n \ -ogEcho log session \"[0] $MSG_HELP_ogCreatePartitions \"\n \ +" + sizecacheCode + " \n \ ogEcho session \"[10] $MSG_HELP_ogUnmountAll "+n_disk+"\"\n \ -ogUnmountAll "+n_disk+" 2>/dev/null\n \ +ogUnmountAll "+n_disk+" 2>/dev/null \n \ ogUnmountCache \n \ -" + cacheCode + " \ +" + cacheCode + " \n \ ogEcho session \"[60] $MSG_HELP_ogListPartitions "+n_disk+"\"\n \ ogExecAndLog command session ogListPartitions "+n_disk+" \n \ ogEcho session \"[70] $MSG_HELP_ogCreatePartitions " + partCode + "\"\n \ -ogExecAndLog command ogCreatePartitions "+n_disk+" " + partCode + " \n \ -ogEcho session \"[80] $MSG_HELP_ogSetPartitionActive "+n_disk+" 1\"\n \ -ogSetPartitionActive "+n_disk+" 1 \n \ -ogEcho log session \"[100] $MSG_HELP_ogListPartitions "+n_disk+"\"\n \ -ogUpdatePartitionTable "+n_disk+" \n \ -ms-sys /dev/sda | grep unknow && ms-sys /dev/sda \n \ -" + cacheInit + " \ -ogExecAndLog command session log ogListPartitions "+n_disk+" \n"; +if ogExecAndLog command session ogCreatePartitions "+n_disk+" " + partCode + "; then \n \ + ogEcho session \"[80] $MSG_HELP_ogSetPartitionActive "+n_disk+" 1\"\n \ + ogSetPartitionActive "+n_disk+" 1 \n \ + ogEcho log session \"[100] $MSG_HELP_ogListPartitions "+n_disk+"\"\n \ + ogUpdatePartitionTable "+n_disk+" \n \ + ms-sys /dev/sda | grep unknow && ms-sys /dev/sda \n \ + ogExecAndLog command session log ogListPartitions "+n_disk+" \n \ + "+ swapCode +"\ +else \n \ + ogEcho session log \"[100] ERROR: $MSG_HELP_ogCreatePartitions\" \n \ + sleep 5 \n \ +fi"; } @@ -278,6 +315,9 @@ function codeParticionadoGPT (form) { var extended=false; var n_disk = form.n_disk.value; var tipo_part_table = form.tipo_part_table.value; + var swapPart = new Array(); + var swapCode = ""; + numParts=document.getElementById("numGPTpartitions").value; for (var nPart=1; nPart <= numParts; nPart++) { @@ -287,15 +327,15 @@ function codeParticionadoGPT (form) { // Solo tratamos la particion 4 como cache, si se selecciono este tipo if(nPart == 4 && form.partGPT4.value == "CACHE") { if (form.sizeGPT4.value == "0") { - sizecacheCode="\ + sizecacheCode="\ ogEcho session \"[20] $MSG_HELP_ogGetCacheSize\"\n \ -sizecache=`ogGetCacheSize` \n"; +sizecache=`ogGetCacheSize` \n "; cacheCode="\ ogEcho session \"[30] $MSG_HELP_ogUpdatePartitionTable "+n_disk+"\"\n \ ogDeletePartitionTable "+n_disk+" \n \ ogExecAndLog command ogUpdatePartitionTable "+n_disk+" \n \ ogEcho session \"[50] $MSG_HELP_ogCreateCache\"\n \ -initCache "+ n_disk +" $sizecache &>/dev/null \n "; +initCache "+ n_disk +" $sizecache NOMOUNT &>/dev/null \n "; } else { if (form.sizeGPT4.value == "CUSTOM") { cacheSize = form.sizeGPT4custom.value; @@ -307,15 +347,21 @@ ogEcho session \"[30] $MSG_HELP_ogUpdatePartitionTable "+n_disk+"\"\n \ ogDeletePartitionTable "+n_disk+" \n \ ogUpdatePartitionTable "+n_disk+" \n \ ogEcho session \"[50] $MSG_HELP_ogCreateCache\"\n \ -initCache " + n_disk +" "+ cacheSize + " &>/dev/null"; +initCache " + n_disk +" "+ cacheSize + " NOMOUNT &>/dev/null"; } } else{ var partType=eval("form.partGPT"+nPart); if (partType.value == "CUSTOM" ) { var partTypeCustom=eval("form.partGPT"+nPart+"custom"); partCode += " " + partTypeCustom.value; + // Partición swap + if (partTypeCustom.value == "LINUX-SWAP") + swapPart.push(nPart); } else { partCode += " " + partType.value; + // Partición swap + if (partType.value == "LINUX-SWAP") + swapPart.push(nPart); } var partSize=eval("form.sizeGPT"+nPart); if (partSize.value == "CUSTOM" ) { @@ -337,6 +383,14 @@ partCode += " EMPTY:0"; } } } + // Formateo de la partición swap + if (swapPart.length > 0) { + for (var i=0; i < swapPart.length; i++) { + swapCode += " ogEcho session log \"$MSG_HELP_ogFormat "+n_disk+" "+swapPart[i]+" LINUX-SWAP \" \n" ; + swapCode += " ogExecAndLog command session log ogFormat "+n_disk+" "+swapPart[i]+" LINUX-SWAP \n"; + } + } + form.codigo.value="\ " + sizecacheCode + " \n \ ogCreatePartitionTable "+n_disk+" "+tipo_part_table +" \n \ @@ -354,7 +408,10 @@ ogSetPartitionActive "+n_disk+" 1 \n \ ogEcho log session \"[100] $MSG_HELP_ogListPartitions "+n_disk+"\"\n \ ogUpdatePartitionTable "+n_disk+" \n \ ms-sys /dev/sda | grep unknow && ms-sys /dev/sda \n \ -ogExecAndLog command session log ogListPartitions "+n_disk+" \n"; +ogExecAndLog command session log ogListPartitions "+n_disk+" \n"; + +// Formateo de la swap +form.codigo.value += swapCode; } @@ -363,8 +420,19 @@ function showPartitionForm (tipo_table_part) { if(tipo_table_part == "MSDOS"){ // De los dos tipos, se oculta el otro document.getElementById("formGPT").style.display="none"; + document.getElementById("warngpt").style.display="none"; } else{ document.getElementById("formMSDOS").style.display="none"; + // Para GPT obliga que primera partición sea EFI + document.getElementById("checkGPT1").checked=true; + document.getElementById("checkGPT1").disabled=true; + document.getElementById("partGPT1").value="CUSTOM"; + document.getElementById("partGPT1custom").value="EFI"; + document.getElementById("sizeGPT1").value="CUSTOM"; + document.getElementById("sizeGPT1").disabled=false; + document.getElementById("sizeGPT1custom").value="512000"; + document.getElementById("sizeGPT1custom").disabled=false; + document.getElementById("warngpt").style.display="table-row"; } } @@ -430,6 +498,30 @@ function getMinDiskSize(disk){ return (minSize > 1024 ? minSize - 1024 : minSize) } +// Calcula el tamaño de la mayor cache y lo guarda en un campo oculto +function getMaxCacheSize() { + var cacheSizeArray = document.getElementsByName("cachesize"); + var maxSize = cacheSizeArray[0].value; + for(var i= 1; i < cacheSizeArray.length; i++){ + if(maxSize < cacheSizeArray[i].value) + maxSize = cacheSizeArray[i].value; + } + document.getElementById("maxcachesize").value = maxSize; + return + +} + + +// Comprueba que la cache quepa en el espacio libre del disco +function validaCache (freedisk) { + var form = document.fdatos; + var maxcachesize = parseInt(document.getElementById("maxcachesize").value); + if(form.part4.value == "CACHE" && form.check4.checked && form.size4.value == 0 ){ + return (freedisk - maxcachesize > 0 ? true : false); + } + return true; +} + // Código para calcular el espacio libre del disco. function calculateFreeDisk(form) { // Si esta seleccionada la opcion GPT, se llama a la funcion correspondiente @@ -616,3 +708,4 @@ function checkExtendedPartition(form) { } } + diff --git a/admin/WebConsole/asistentes/xajax.server.php b/admin/WebConsole/asistentes/xajax.server.php index 6f93f685..b4f26585 100644 --- a/admin/WebConsole/asistentes/xajax.server.php +++ b/admin/WebConsole/asistentes/xajax.server.php @@ -87,7 +87,7 @@ function ListarOrigenMaster($ip){ //Tercera consulta: Imagenes del REPO, que el MASTER se encargara de enivarlas $cmd->texto='SELECT *,repositorios.ip as iprepositorio FROM imagenes INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio -where repositorios.idrepositorio=(select idrepositorio from ordenadores where ordenadores.ip="' .$ip .'")'; +where repositorios.idrepositorio=(select idrepositorio from ordenadores where ordenadores.ip="' .$ip .'") ORDER BY imagenes.descripcion'; $rs->Comando=&$cmd; @@ -98,7 +98,7 @@ where repositorios.idrepositorio=(select idrepositorio from ordenadores where or while (!$rs->EOF){ $SelectHtml.=''; + $SelectHtml.='IMG-REPO: ' . $rs->campos["descripcion"].''; $rs->Siguiente(); } } diff --git a/admin/WebConsole/barramenu.php b/admin/WebConsole/barramenu.php index f7a669e7..36bf2e1e 100644 --- a/admin/WebConsole/barramenu.php +++ b/admin/WebConsole/barramenu.php @@ -177,71 +177,71 @@ if (!$cmd) - + +     +     +     +     +     +     +     +     - +   +   +   - - + + +     +     +     diff --git a/admin/WebConsole/clases/AdoPhp.php b/admin/WebConsole/clases/AdoPhp.php index b48032d1..e7daad17 100644 --- a/admin/WebConsole/clases/AdoPhp.php +++ b/admin/WebConsole/clases/AdoPhp.php @@ -332,17 +332,19 @@ class Comando{ tipo = tipo de parametro: 0: El valor del par�etro debe ir encerrado entre comillas simples 1: El valor del par�etro no necesita ir entre comillas simples - + Versión 1.1: Al incluir los valores se escapan caracteres especiales (ticket #777) + Autor: Irina Gómez - ETSII, Universidad de Sevilla + Fecha: 2017-03-30 ---------------------------------------------------------------------------------------------*/ function CreaParametro($nombre,$valor,$tipo){ for($i=0;$iparametros);$i++){ if($this->parametros[$i]["nombre"]==$nombre){ - $this->parametros[$i]["valor"]=$valor; + $this->parametros[$i]["valor"]=mysql_real_escape_string($valor); return; } } - $p = new parametro($nombre,$valor,$tipo); + $p = new parametro($nombre,mysql_real_escape_string($valor),$tipo); $this->AddParametro($p); } @@ -351,11 +353,14 @@ class Comando{ Par�etros de entrada: nombre: El nombre del par�etro valor : El nuevo valor del par�etro + Versión 1.1: Al incluir los valores se escapan caracteres especiales (ticket #777) + Autor: Irina Gómez - ETSII, Universidad de Sevilla + Fecha: 2017-03-30 ---------------------------------------------------------------------------------------------*/ function ParamSetValor($nombre,$valor){ for($i=0;$iparametros);$i++){ if($this->parametros[$i]["nombre"]==$nombre) - $this->parametros[$i]["valor"]=$valor; + $this->parametros[$i]["valor"]=mysql_real_escape_string($valor); } } /* ------------------------------------------------------------------------------------------- diff --git a/admin/WebConsole/clases/ArbolVistaXML.php b/admin/WebConsole/clases/ArbolVistaXML.php index 6de54069..3da6bb83 100644 --- a/admin/WebConsole/clases/ArbolVistaXML.php +++ b/admin/WebConsole/clases/ArbolVistaXML.php @@ -1,4 +1,4 @@ - - '?> + '?> -'.$TbMsg[5].' 
'; //________________________________________________________________________________________________________ // diff --git a/admin/WebConsole/comandos/Arrancar.php b/admin/WebConsole/comandos/Arrancar.php index 09c0b673..a73e2d7f 100644 --- a/admin/WebConsole/comandos/Arrancar.php +++ b/admin/WebConsole/comandos/Arrancar.php @@ -34,7 +34,7 @@ if (!$cmd) - '?> + '?> -

+


diff --git a/admin/WebConsole/comandos/Comando.php b/admin/WebConsole/comandos/Comando.php index f9c53257..d4e7eff8 100644 --- a/admin/WebConsole/comandos/Comando.php +++ b/admin/WebConsole/comandos/Comando.php @@ -1,4 +1,4 @@ - - '?> + '?> - -'?> -'?> +'?> +'?> -'.$TbMsg[5].' 
'; //________________________________________________________________________________________________________ // @@ -82,24 +83,24 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"]; ?> - - - + + +
- + - - + + - - + + - - + + @@ -108,11 +109,11 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"]; +
>>  >>  >>  
-
- - de los número de particiones @@ -149,7 +150,7 @@ function HTMLSELECT_particiones($p) $SelectHtml=""; $opciones=""; - for($i=0;$i<8;$i++) + for($i=0;$i<9;$i++) $opciones.="$i=$i".chr(13); $opciones.="$i=$i"; $SelectHtml.=HTMLCTESELECT($opciones,"particiones","estilodesple","",$p,40,""); diff --git a/admin/WebConsole/comandos/CrearImagen.php b/admin/WebConsole/comandos/CrearImagen.php index 8e741bac..37a43128 100644 --- a/admin/WebConsole/comandos/CrearImagen.php +++ b/admin/WebConsole/comandos/CrearImagen.php @@ -1,4 +1,4 @@ - -Administración web de aulas +Administración web de aulas -'?> -'?> +'?> +'?> -   '.$TbMsg[14].': '.$textambito.','.$nombreambito.'  

'; ?> -

+

- +
- -texto="SELECT imagenes.idimagen,imagenes.descripcion,imagenes.nombreca, - imagenes.idperfilsoft, repositorios.nombrerepositorio - FROM imagenes INNER JOIN repositorios on imagenes.idrepositorio = repositorios.idrepositorio - WHERE imagenes.tipo=".$IMAGENES_MONOLITICAS." - AND imagenes.idrepositorio=".$idrepositorio ." OR repositorios.ip='" .$masterip ."'"; + $cmd->texto="SELECT DISTINCT imagenes.idimagen,imagenes.descripcion,imagenes.nombreca, + imagenes.idperfilsoft, repositorios.nombrerepositorio, repositorios.ip + FROM imagenes INNER JOIN repositorios USING (idrepositorio) + WHERE repositorios.idrepositorio = (SELECT idrepositorio FROM ordenadores WHERE ordenadores.ip='".$masterip."') + OR repositorios.ip='".$masterip."' ORDER BY imagenes.descripcion"; + $rs=new Recordset; $rs->Comando=&$cmd; $SelectHtml.= ''; return($SelectHtml); } - -/*________________________________________________________________________________________________________ - Crea la etiqueta html '; - $rs->Primero(); - while (!$rs->EOF){ - $SelectHtml.=''; - $rs->Siguiente(); - } - $SelectHtml.= ''; - $rs->Cerrar(); - return($SelectHtml); -} - ?> diff --git a/admin/WebConsole/comandos/CrearImagenBasica.php b/admin/WebConsole/comandos/CrearImagenBasica.php index f9937f66..875aeb40 100644 --- a/admin/WebConsole/comandos/CrearImagenBasica.php +++ b/admin/WebConsole/comandos/CrearImagenBasica.php @@ -49,30 +49,30 @@ if (!$resul){ -

+

- +
- - -
   - '.$nombreordenador.'';?> +    + '.$nombreordenador.'';?>
   - '.$ip.'';?> +    + '.$ip.'';?>
   - '.$mac.'';?> +    + '.$mac.'';?>

-

+

@@ -88,17 +88,17 @@ if (!$resul){ -
- +
-
- - -'?> -'?> +'?> +'?> -

+

- +
- - -
   - '.$nombreordenador.'';?> +    + '.$nombreordenador.'';?>
   - '.$ip.'';?> +    + '.$ip.'';?>
   - '.$mac.'';?> +    + '.$mac.'';?>

-

+

@@ -89,17 +89,17 @@ if (!$resul){ -
- +
-
- - - '?> - '?> + '?> + '?> -'.$TbMsg[5].' 
'; //________________________________________________________________________________________________________ // @@ -45,15 +45,22 @@ if (!$cmd) //________________________________________________________________________________________________________ ?>

- +

+ + + + - + +
+ +
    
- -'?> -'?> +'?> +'?> @@ -49,6 +49,10 @@ switch($ambito){ case $AMBITO_GRUPOSAULAS : $urlimg='../images/iconos/carpeta.gif'; $textambito=$TbMsg[1]; + $cmd->texto="SELECT DISTINCT ordenadores.idrepositorio + FROM aulas + LEFT JOIN ordenadores ON ordenadores.idaula=aulas.idaula + WHERE aulas.idaula=$idambito"; break; case $AMBITO_AULAS : $urlimg='../images/iconos/aula.gif'; @@ -136,7 +140,7 @@ switch($ambito){ } echo '

'.$TbMsg[5].' 
'; - echo '  '.$TbMsg[6].': '.$textambito.','.$nombreambito.'  

'; + echo '  '.$textambito.': '.$nombreambito.'  

'; ?>   - ".$nombreambito.$TbMsg[16]."
".$TbMsg[18]; }else{ echo $TbMsg[17]."
".$nombreambito.$TbMsg[15]."
".$TbMsg[18]; } @@ -156,7 +160,7 @@ switch($ambito){

- +

@@ -282,65 +286,51 @@ function tabla_configuraciones($cmd,$idambito){ switch($ambito){ case $AMBITO_CENTROS : $urlimg='../images/iconos/centros.gif'; - //echo "ambito - ".$ambito."
"; - //echo "idcentro - ".$idc; break; case $AMBITO_GRUPOSAULAS : - - $cmd->texto="SELECT * FROM grupos WHERE nombregrupo='$nombreambito' AND idcentro='$idc'"; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(true); // Error al abrir recordset - $rs->Primero(); - if (!$rs->EOF){ - $identificadorgrupo=$rs->campos["idgrupo"]; - } - $rs->Cerrar(); - - $cmd->texto="SELECT * FROM aulas,grupos - WHERE grupos.nombregrupo='$nombreambito' - AND aulas.idcentro='$idc' - AND aulas.grupoid='$identificadorgrupo' - AND aulas.grupoid=grupos.idgrupo"; - - + $cmd->texto="SELECT * FROM ordenadores,aulas,ordenadores_particiones + JOIN grupos USING(idgrupo) + JOIN sistemasficheros USING(idsistemafichero) + WHERE ordenadores_particiones.idordenador=ordenadores.idordenador + AND ordenadores.idaula=aulas.idaula + AND grupos.nombregrupo='$nombreambito' + AND grupos.idcentro='$idc' + AND sistemasficheros.nemonico='CACHE'"; break; case $AMBITO_AULAS : $cmd->texto="SELECT * FROM ordenadores,aulas,ordenadores_particiones + JOIN sistemasficheros USING(idsistemafichero) WHERE ordenadores_particiones.idordenador=ordenadores.idordenador AND ordenadores.idaula=aulas.idaula AND aulas.nombreaula='$nombreambito' - AND aulas.idcentro='$idc' - AND ordenadores_particiones.numpar=4 - GROUP BY ordenadores_particiones.cache"; - + AND aulas.idcentro='$idc' + AND sistemasficheros.nemonico='CACHE'"; break; case $AMBITO_GRUPOSORDENADORES : $cmd->texto="SELECT * FROM ordenadores,aulas,ordenadores_particiones,gruposordenadores + JOIN sistemasficheros USING(idsistemafichero) WHERE ordenadores_particiones.idordenador=ordenadores.idordenador AND ordenadores.idaula=aulas.idaula - AND gruposordenadores.idaula=aulas.idaula - AND aulas.idcentro='$idc' - AND ordenadores_particiones.numpar=4 - AND ordenadores.grupoid='$idambito' - GROUP BY ordenadores_particiones.cache"; - + AND gruposordenadores.idaula=aulas.idaula + AND aulas.idcentro='$idc' + AND sistemasficheros.nemonico='CACHE' + AND ordenadores.grupoid='$idambito'"; break; + case $AMBITO_ORDENADORES : $cmd->texto="SELECT * FROM ordenadores,ordenadores_particiones + JOIN sistemasficheros USING(idsistemafichero) WHERE ordenadores_particiones.idordenador=ordenadores.idordenador AND ordenadores.nombreordenador='$nombreambito' - AND ordenadores_particiones.numpar=4 - GROUP BY ordenadores_particiones.cache"; + AND sistemasficheros.nemonico='CACHE'"; break; } $tablaHtml=""; - $rs->Comando=&$cmd; $rs=new Recordset; $rs->Comando=&$cmd; diff --git a/admin/WebConsole/comandos/EliminarImagenRepositorio.php b/admin/WebConsole/comandos/EliminarImagenRepositorio.php index d33cb377..a95b4f78 100644 --- a/admin/WebConsole/comandos/EliminarImagenRepositorio.php +++ b/admin/WebConsole/comandos/EliminarImagenRepositorio.php @@ -20,7 +20,7 @@ if (isset($_POST["opcion"])) {$opcion=$_POST["opcion"];}else{$opcion;} // Recoge //$opcion=$_POST["opcion"]; // Recoge parametros if (isset($_POST["idrepositorio"])) {$idrepositorio=$_POST["idrepositorio"];}else{$idrepositorio;} //$idrepositorio=$_POST["idrepositorio"]; -if (isset($_POST["grupoid"])) {$grupoid=$_POST["grupoid"];}else{$grupoid;} +if (isset($_POST["grupoid"])) {$grupoid=$_POST["grupoid"];}else{$grupoid='';} //$grupoid=$_POST["grupoid"]; $idcentro=$_SESSION["widcentro"]; if (isset($_GET["opcion"])) $opcion=$_GET["opcion"]; // Recoge parametros @@ -86,19 +86,38 @@ if (!$rs->Abrir()) return(true); // Error al abrir recordset } $rs->Cerrar(); -if ($iprepositorio == $ipservidor) -{ - -$cmd->texto="SELECT * FROM repositorios WHERE ip='$iprepositorio'"; +// Compruebo si se separan directorio de unidades organizativas +$cmd->texto="SELECT ogunit FROM entidades INNER JOIN centros USING(identidad) where idcentro=$idcentro"; $rs=new Recordset; -$rs->Comando=&$cmd; +$rs->Comando=&$cmd; if (!$rs->Abrir()) return(true); // Error al abrir recordset - $rs->Primero(); - if (!$rs->EOF) +$rs->Primero(); +if (!$rs->EOF) +{ + $separarogunit=$rs->campos["ogunit"]; // 1 -> si, 0 -> no +} +$rs->Cerrar(); + +// Directorios de las imágenes, si separo por unidades organizativas leo la BD +$dircentros= array(); +$dircentros[0]='/'; // Incluimos /opt/opengnsys/images +if ($separarogunit == 1 ) { + $cmd->texto="SELECT idcentro, directorio FROM centros ORDER BY idcentro"; + $rs=new Recordset; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(true); // Error al abrir recordset + $rs->Primero(); + while (!$rs->EOF) { - $idrepodefault=$rs->campos["idrepositorio"]; + $dircentros[$rs->campos["idcentro"]]="/".$rs->campos["directorio"]; + $rs->Siguiente(); } - $rs->Cerrar(); +} + +if ($iprepositorio == $ipservidor) +{ + + //######################################################################### $repolocal="si"; @@ -106,19 +125,24 @@ $repolocal="si"; // LEYENDO EL DIRECTORIO local en el server // /opt/opengnsys/images/ //######################################################################### - $dirtemplates="/opt/opengnsys/images/"; - $directorio=dir($dirtemplates); $imarepo= array();//pila de nombres - //bucle para llenar las pilas :P - while ($archivo = $directorio->read()) - { + foreach ( array_unique($dircentros) as $subdir) { + $dirtemplates="/opt/opengnsys/images/$subdir"; + $directorio=dir($dirtemplates); + // quitamos la barra inicial + $subdir = ($subdir == "/") ? '' : substr($subdir,1).':'; + //bucle para llenar las pilas :P + while ($archivo = $directorio->read()) + { //no mostrar ni "." ni ".." ni "pxe" if(($archivo!=".")&&($archivo!="..")&&($archivo!="mount")&&($archivo!="lost+found")) { - array_push($imarepo, $archivo); + array_push($imarepo, $subdir.$archivo); } + } + $directorio->close(); } - $directorio->close(); + sort($imarepo); // Ordenamos el Array if (isset($_POST["contar"])) {$cuantos=$_POST["contar"];}else{$cuantos=0;$contar;} @@ -170,19 +194,15 @@ $repolocal="si"; if ($checkboxobjeto == "si") { //######################################################################### - $cmd->texto="SELECT * FROM imagenes WHERE nombreca='$nombre' AND idcentro='$idcentroimg'"; + // Si la imagen tiene directorio lo elimino + $cmd->texto="SELECT * FROM imagenes WHERE nombreca='".preg_replace('/^\w*:/','',$nombre)."' AND idcentro='$idcentroimg'"; $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return(0); // Error al abrir recordset $rs->Primero(); if (!$rs->EOF){ - $idimagen=$rs->campos["idimagen"]; - $nombrecanonico=$rs->campos["nombreca"]; - $centroimagen=$rs->campos["idcentro"]; - $idimagen=$rs->campos["idimagen"]; - //$cmd->texto="DELETE FROM imagenes WHERE idimagen='$idimagen'"; - //$resul=$cmd->Ejecutar(); - } + $idimagen=$rs->campos["idimagen"]; + } $rs->Cerrar(); EliminaImagenes($cmd,$idimagen,"idimagen");// Eliminación en cascada @@ -222,12 +242,12 @@ $repolocal="no"; ?> -Administración web de aulas +Administración web de aulas -'?> +'?> -";if(confirm(me -    -    -    -    +    +    +    +    -    -    -    -    +    +    +    +    -    +    @@ -270,13 +290,13 @@ function confirmeliminar() {var mensaje="";if(confirm(me

-

+
- - - + + + @@ -295,31 +315,33 @@ function confirmeliminar() {var mensaje="";if(confirm(me - - + + - + - +
     ".$TbMsg[31]; ?>     ".$TbMsg[31]; ?>       ".$TbMsg[32]; ?>   ".$TbMsg[32]; ?>       Backup" ?>   Backup" ?>   
- - - - - - - + + + + + + + + + - ";if(confirm(me } }else{ // Compruebo si es un directorio - $buscodir="/opt/opengnsys/images/".$imarepo[$x]; + $buscodir="/opt/opengnsys/images/".str_replace(":","/",$imarepo[$x]); $buscopengnsys=$buscodir."/.marcimg"; if(is_dir($buscodir) && file_exists($buscopengnsys)){ $imarepo[$x]=trim($imarepo[$x]); @@ -374,16 +396,24 @@ function confirmeliminar() {var mensaje="";if(confirm(me $contar=1; foreach($sin_duplicados as $value) //imprimimos $sin_duplicados { //Llave Forach + // Guardo los valores del directorio y el nombre imagen + // Si no se separan los directorios queda igual + $arrayname=explode(':', $value); + if (sizeof( $arrayname) == 1){ + $imgdir=""; + $imgname=$arrayname[0]; + } else { + $imgdir=$arrayname[0]; + $imgname=$arrayname[1]; + } //Buscamos tamano de fichero - //Buscamos .torrent y .sum con lock - $gensum=$value.".img.sum.lock"; - $gentor=$value.".img.lock"; + //Buscamos si existe fichero de bloqueo + $gentor=str_replace(":","/",$value).".img.lock"; if(ereg(".diff",$value))$gendif=$value.".img.diff"; // ########### Buscando si existe fichero imagen ##################### - $buscando="find /opt/opengnsys/images/ -maxdepth 1 -name ".$gentor." -print"; - $generando="Generando .torrent"; + $buscando="ls /opt/opengnsys/images/$gentor"; $bustor=exec($buscando); if(ereg(".diff",$value)) { @@ -401,204 +431,48 @@ function confirmeliminar() {var mensaje="";if(confirm(me $nombrefichero=$value.'.img';$marcadif=0; } - - if ($modov != 1){ - - // #################################################################################### - // ########## Si el nombre imagen existe en la Unidad Organizativa #################### - // #################################################################################### - //echo $value." - ".$idcentro."
"; - - $cmd->texto="SELECT * FROM imagenes WHERE nombreca='$value' ";//AND idcentro='$idcentro'"; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(0); // Error al abrir recordset - $rs->Primero(); - if (!$rs->EOF){ - $nombrecacentro=$rs->campos["nombreca"]; - $nombrecaidcentro=$rs->campos["idcentro"]; - } - if ($nombrecacentro != $value){$nombrecaidcentro=0;} - $rs->Cerrar(); - - if($nombrecaidcentro == $idcentro || $nombrecaidcentro==0) - { //Comienzo de Condicion si es nombrecaidcentro - //echo "Value - ".$value."/ - Id Centro - ".$idc." /Nombrecacentro - ".$nombrecacentro." /Base ID Centro ".$nombrecaidcentro."
"; - - // #################################################################################### // #################################################################################### // ########## Buscando si existe objeto imagen ######################################## - // ########## Si el Nombre contiene .diff lo quitamos para buscar objeto imagen - if(ereg(".diff",$value)){ $valuediff=$value; $value = str_replace(".diff", "", $value);} //quitar todos los .diff y continuamos // #################################################################################### + $encontradoobjetoimagen=''; + // Version anterior tomaba nombrecentro donde $nombrecaidcentro=$idrepodefault + $nombrecaidcentro=0; // No afecta a vista unidad organizativa + $nombrecentro=''; // No afecta a vista unidad organizativa + // ########## Si el Nombre contiene .diff lo quitamos para buscar objeto imagen + if(ereg(".diff",$imgname)){ $imgname = str_replace(".diff", "", $imgname);} - $encontradoobjetoimagen=""; - $cmd->texto="SELECT * FROM imagenes WHERE nombreca='$value' AND idcentro='$idcentro'"; + $cmd->texto="SELECT idcentro, nombrecentro, nombreca FROM imagenes LEFT JOIN centros USING(idcentro) WHERE nombreca='$imgname' "; $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return(0); // Error al abrir recordset $rs->Primero(); if (!$rs->EOF){ - $encontradoobjetoimagen=$rs->campos["nombreca"]; - } - if($encontradoobjetoimagen == $value){$encontradoobjetoimagen;}else{$encontradoobjetoimagen="";} - $idcentroimgpost=$rs->campos["idcentro"]; - $rs->Cerrar(); - // #################################################################################### - - // ########################## VARIABLES FICHERO DELETE ################################ - $nombredirectorio="/opt/opengnsys/images/".$value; - // #################################################################################### - if ($tipo[$contandotipo] == "D") - { - $nombrefichero=str_replace(".img", "", $nombrefichero); - $ficherodelete="../tmp/".$nombrefichero.".delete"; - }else{ - $ficherodelete="../tmp/".$nombrefichero.".delete"; - } - // ########################## VARIABLES FICHERO DELETE ################################ - // #################################################################################### - // ######## TAMAÑO DEL FICHERO Y DIRECTORIO ########################## - if (is_dir ($nombredirectorio) && $tipo[$contandotipo] == "D") - { - $tamanofich=exec("ls -lah ".$nombredirectorio." | awk 'NR==1 {print $2}'"); - } - elseif (ereg(".ant",$nombrefichero)) - { - $nombreficheroant=str_replace(".ant", "", $nombrefichero); //quitar todos los .ant y continuamos - - $nombreficheroant=$nombreficheroant.".ant"; - $tamanofich=exec("du -h --max-depth=1 /opt/opengnsys/images/$nombreficheroant"); - $tamanofich=split("/",$tamanofich);//////////////////////////////////////////echo $nombrefichero."
"; - }else{ - $tamanofich=exec("du -h --max-depth=1 /opt/opengnsys/images/$nombrefichero"); - $tamanofich=split("/",$tamanofich);//////////////////////////////////////////echo $nombrefichero."
"; - } - // ######## TAMAÑO DEL FICHERO Y DIRECTORIO ########################## - - $todo=".delete"; - $ruta='touch%20/opt/opengnsys/images/'.$value.$todo;//////////////////////////////////////echo $value;// - - echo ''.chr(13); - - // ########## Nº ###################################################################### - echo ''.chr(13); - - // ########## Marcar ################################################################## - - if ($bustor<>"") - { - echo ''.chr(13); - } - elseif (file_exists($ficherodelete)) - { - echo ''.chr(13);} - else - { - echo ''.chr(13); - } - - // ########## Tipo #################################################################### - if ($tipo[$contandotipo]=="D") - { - echo ''.chr(13); - } - elseif ($tipo[$contandotipo]=="B") - { - echo ''.chr(13); - }else{ - echo ''.chr(13); + $encontradoobjetoimagen=(is_null($rs->campos["nombreca"]))? '': $rs->campos["nombreca"]; + $nombrecaidcentro=(is_null($rs->campos["idcentro"]))? 0 :$rs->campos["idcentro"]; + $nombrecentro=(is_null($rs->campos["nombrecentro"]))? '' : $rs->campos["nombrecentro"]; } + $rs->Cerrar(); - echo ''.chr(13);; - echo ''.chr(13);; - echo ''.chr(13);; - echo ''.chr(13);; - - // ########## Nombre de Imagen ######################################################## - if ($tipo[$contandotipo]=="D") - { - echo ''.chr(13); - } - else - { - - echo ''.chr(13); + // Sobre: si devuelve una imagen tiene que coincidir + if($encontradoobjetoimagen == $imgname) { + $encontradoobjetoimagen=$value; } - // ########## Tamaño de Imagen ######################################################## - if (is_dir ($nombredirectorio) && $tipo[$contandotipo] == "D") - {echo ''.chr(13);} - else{echo ''.chr(13);} + if ($modov != 1){ //VISTA UNIDAD ORGANIZATIVA + // Si la imagen no es del centro no la muestro + if ($nombrecaidcentro != $idcentro && $nombrecaidcentro != 0) { + $contandotipo++; + continue; + } + // si ogunit con dir separados -> si la imagen no es del dir del centro no la muestro + if ($separarogunit == 1 and ! ereg($dircentros[$idcentro], "/".$value)) { + $contandotipo++; + continue; + }; - // ########## Objeto Imagen ########################################################### - if($encontradoobjetoimagen<>"") - { - echo ''.chr(13); - echo ''.chr(13); - } - elseif (ereg(".ant",$nombrefichero)) - { - echo ''.chr(13); - }else{ - echo ''.chr(13); } - // ##################################################################################### - echo ''.chr(13); - $contar++; - $contandotipo++; - }else{$contandotipo++;}//Fin de Condicion si es nombrecaidcentro - - } - - else{ - - - $nombrecaidcentro=$idrepodefault; - //echo $value." - ".$idcentro."
"; - $cmd->texto="SELECT * FROM imagenes WHERE nombreca='$value' "; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(0); // Error al abrir recordset - $rs->Primero(); - if (!$rs->EOF){ - $nombrecacentro=$rs->campos["nombreca"]; - $nombrecaidcentro=$rs->campos["idcentro"]; - } - $rs->Cerrar(); - - $cmd->texto="SELECT * FROM centros WHERE idcentro='$nombrecaidcentro' "; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(0); // Error al abrir recordset - $rs->Primero(); - if (!$rs->EOF){ - $nombrecentro=$rs->campos["nombrecentro"]; - } - $rs->Cerrar(); - - - // #################################################################################### - // #################################################################################### - // ########## Buscando si existe objeto imagen ######################################## - // ########## Si el Nombre contiene .diff lo quitamos para buscar objeto imagen - if(ereg(".diff",$value)){ $valuediff=$value; $value = str_replace(".diff", "", $value);} //quitar todos los .diff y continuamos - // #################################################################################### - - $encontradoobjetoimagen=""; - $cmd->texto="SELECT * FROM imagenes WHERE nombreca='$value'";// AND idcentro='$idcentro'"; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(0); // Error al abrir recordset - $rs->Primero(); - if (!$rs->EOF){ - $encontradoobjetoimagen=$rs->campos["nombreca"]; - } - if($encontradoobjetoimagen == $value){$encontradoobjetoimagen;}else{$encontradoobjetoimagen="";} - $rs->Cerrar(); // #################################################################################### - // ########################## VARIABLES FICHERO DELETE ################################ $nombredirectorio="/opt/opengnsys/images/".$value; // #################################################################################### @@ -610,6 +484,8 @@ function confirmeliminar() {var mensaje="";if(confirm(me $ficherodelete="../tmp/".$nombrefichero.".delete"; } // ########################## VARIABLES FICHERO DELETE ################################ + $nombredirectorio=str_replace(":","/",$nombredirectorio); + $nombrefichero=str_replace(":","/",$nombrefichero); // #################################################################################### // ######## TAMAÑO DEL FICHERO Y DIRECTORIO ########################## @@ -639,6 +515,7 @@ function confirmeliminar() {var mensaje="";if(confirm(me echo ''.chr(13); // ########## Marcar ################################################################## + if ($bustor<>"") { echo ''.chr(13); @@ -669,14 +546,26 @@ function confirmeliminar() {var mensaje="";if(confirm(me echo ''.chr(13);; echo ''.chr(13);; + // ########## Aviso si directorio distinto al del centro - en vista repositorio ########## + $aviso=''; + if ($separarogunit == 1) { + if ( $nombrecaidcentro != 0 and "/".$imgdir != $dircentros[$nombrecaidcentro]){ + $aviso=" * "; + $textoaviso="\n \n". + "\n"; + } + } + // ########## Nombre de Imagen ######################################################## if ($tipo[$contandotipo]=="D") { - echo ''.chr(13); + echo ''.chr(13); } else { - echo ''.chr(13); + + echo ''.chr(13); } // ########## Tamaño de Imagen ######################################################## @@ -695,30 +584,30 @@ function confirmeliminar() {var mensaje="";if(confirm(me }else{ echo ''.chr(13); } - // ##################################################################################### - // ########## Unidad Organizativa ###################################################### + // VISTA REPOSITORIO COMPLETO + if ($modov == 1){ + // ##################################################################################### + // ########## Unidad Organizativa ###################################################### + + echo ''.chr(13); - echo ''.chr(13); + // ##################################################################################### + } // ##################################################################################### echo ''.chr(13); $contar++; $contandotipo++; -// }else{$contandotipo++;}//Fin de Condicion si es nombrecaidcentro - - } - - - } //Fin Llave Forach + if (isset ($textoaviso)) echo $textoaviso; ?> - - - + + +
                            
 '.$contar.'  '.$TbMsg[14].' '.$TbMsg[15].''.$tipo[$contandotipo].' '.$tipo[$contandotipo].' '.$tipo[$contandotipo].' '.$value.'  '.$value.'  '.$tamanofich.' '.$tamanofich[0].' ------ '.$TbMsg[25].'
 '.$contar.'  '.$TbMsg[14].'
". + " * $TbMsg[33]  
 '.$value.'  '.str_replace(":"," / ",$value).' '.$aviso.'  '.$value.'  '.str_replace(":"," / ",$value).' '.$aviso.'  '.$TbMsg[25].''.$nombrecentro.''.$nombrecentro.'

@@ -729,7 +618,7 @@ function confirmeliminar() {var mensaje="";if(confirm(me - + @@ -738,6 +627,5 @@ function confirmeliminar() {var mensaje="";if(confirm(me - - ?> diff --git a/admin/WebConsole/comandos/EnviarMensaje.php b/admin/WebConsole/comandos/EnviarMensaje.php new file mode 100644 index 00000000..15e9237a --- /dev/null +++ b/admin/WebConsole/comandos/EnviarMensaje.php @@ -0,0 +1,97 @@ + + +Administración web de aulas + + + + + + + + '?> + '?> + + +'.$TbMsg[5].' 
'; + //________________________________________________________________________________________________________ + // + include_once("./includes/FiltradoAmbito.php"); + //________________________________________________________________________________________________________ +?> +

+ +

+ + + + + + + + + + +
  
  
+
+ +

Opciones de Ejecución

+ + + + +
+
+ + + + + + + + + + + + + +
Ejecutar inmediatamente  
  Incluirlo en Cola de Acciones 
  No incluirlo en Cola de Acciones 
+ + + + + diff --git a/admin/WebConsole/comandos/IniciarSesion.php b/admin/WebConsole/comandos/IniciarSesion.php index 3ef3b9c5..404a004d 100644 --- a/admin/WebConsole/comandos/IniciarSesion.php +++ b/admin/WebConsole/comandos/IniciarSesion.php @@ -59,12 +59,12 @@ if (!$cmd) ?>

- +

- - - + + +
- '?> + '?> - -'?> - '?> +'?> + '?>

- +


- - - '?> + '?> -'.$TbMsg[5].' 
'; //________________________________________________________________________________________________________ // diff --git a/admin/WebConsole/comandos/RestaurarImagen.php b/admin/WebConsole/comandos/RestaurarImagen.php index e75b2f82..047f6174 100644 --- a/admin/WebConsole/comandos/RestaurarImagen.php +++ b/admin/WebConsole/comandos/RestaurarImagen.php @@ -7,6 +7,10 @@ // Nombre del fichero: RestaurarImagenOrdenador.php // Descripción : // Implementación del comando "RestaurarImagen" (Ordenadores) +// version 1.1: cliente con varios repositorios +// HTMLSELECT_imagenes: Imagenes de todos los repositorios de la UO - Cambia parametro idordenadores por idambito +// autor: Irina Gomez, Universidad de Sevilla +// fecha 2015-06-17 // ************************************************************************************************************************************************* include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); @@ -63,7 +67,7 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"]; - + '?> '?> @@ -83,24 +87,24 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"]; RecopilaIpesMacs($cmd,$ambito,$idambito); ?>
- - - + + + - + - - + + - - + + - - + + @@ -109,12 +113,14 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"]; +
>>  >>  >>  
-
0. las imágenes recien creadas tienen numpar=0. // US ETSII - Irina Gomez - 2014-11-11 ________________________________________________________________________________________________________*/ -function HTMLSELECT_imagenes($cmd,$idimagen,$numpar,$codpar,$icp,$sw,$idordenadores,$ambito) +function HTMLSELECT_imagenes($cmd,$idimagen,$numpar,$codpar,$icp,$sw,$idambito,$ambito) { global $IMAGENES_MONOLITICAS; $SelectHtml=""; - $cmd->texto="SELECT *,repositorios.ip as iprepositorio FROM imagenes + $cmd->texto="SELECT *,repositorios.ip as iprepositorio, repositorios.nombrerepositorio as nombrerepo FROM imagenes INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio"; if($sw) // Imágenes con el mismo tipo de partición - $cmd->texto.= " WHERE imagenes.codpar=".$codpar; + $cmd->texto.= " WHERE imagenes.codpar=".$codpar; else - $cmd->texto.= " WHERE imagenes.codpar<>".$codpar; + $cmd->texto.= " WHERE imagenes.codpar<>".$codpar; - $cmd->texto.=" AND imagenes.codpar>0 AND imagenes.idrepositorio>0 "; // La imagene debe existir y + $cmd->texto.=" AND imagenes.idrepositorio>0"; // La imagene debe existir en el repositorio. $cmd->texto.=" AND imagenes.tipo=".$IMAGENES_MONOLITICAS; - $idordenador1 = explode(",",$idordenadores); - $idordenador=$idordenador1[0]; - if ($ambito == 16) - $cmd->texto.=" AND repositorios.idrepositorio=(select idrepositorio from ordenadores where ordenadores.idordenador=" .$idordenador .") OR repositorios.ip=(select ip from ordenadores where ordenadores.idordenador=". $idordenador .")"; - else - $cmd->texto.=" AND repositorios.idrepositorio=(select idrepositorio from ordenadores where ordenadores.idordenador=" .$idordenador .")"; + // 1.1 Imagenes de todos los repositorios de la UO. + switch ($ambito) { + case 16: + // ambito ordenador + $selectrepo='select repositorios.idrepositorio from repositorios INNER JOIN aulas INNER JOIN ordenadores where repositorios.idcentro=aulas.idcentro AND aulas.idaula=ordenadores.idaula AND idordenador='.$idambito; + break; + case 8: + // ambito grupo ordenadores + $selectrepo='select idrepositorio from repositorios INNER JOIN aulas INNER JOIN gruposordenadores where repositorios.idcentro=aulas.idcentro AND aulas.idaula=gruposordenadores.idaula AND idgrupo='.$idambito; + break; + case 4: + // ambito aulas + $selectrepo='select idrepositorio from repositorios INNER JOIN aulas where repositorios.idcentro=aulas.idcentro AND idaula='.$idambito; + break; + } + $cmd->texto.=" AND repositorios.idrepositorio IN (".$selectrepo.") ORDER BY imagenes.descripcion"; $rs=new Recordset; $rs->Comando=&$cmd; @@ -170,7 +186,8 @@ function HTMLSELECT_imagenes($cmd,$idimagen,$numpar,$codpar,$icp,$sw,$idordenado $SelectHtml.=''; + $SelectHtml.= $rs->campos["descripcion"].' ('.$rs->campos["nombrerepo"].') '; + $rs->Siguiente(); } $rs->Cerrar(); diff --git a/admin/WebConsole/comandos/RestaurarImagenBasica.php b/admin/WebConsole/comandos/RestaurarImagenBasica.php index 7b431c67..d7be1eec 100644 --- a/admin/WebConsole/comandos/RestaurarImagenBasica.php +++ b/admin/WebConsole/comandos/RestaurarImagenBasica.php @@ -1,4 +1,4 @@ - -'?> -'?> +'?> +'?> -
- - - + + + - + - - + + - - + + - - + + @@ -120,7 +120,7 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"];
>>  >>  >>  
- -texto="SELECT imagenes.*,repositorios.ip as iprepositorio,repositorios.nombrerepositorio FROM imagenes - INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio"; - - if($sw) // Im�genes con el mismo tipo de partici�n - $cmd->texto.= " WHERE imagenes.codpar=".$codpar; - else - $cmd->texto.= " WHERE imagenes.codpar<>".$codpar; - - $cmd->texto.=" AND imagenes.tipo=".$IMAGENES_BASICAS." - AND imagenes.codpar>0 + INNER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio + AND imagenes.tipo=".$IMAGENES_BASICAS." AND imagenes.idrepositorio>0"; //AND imagenes.idperfilsoft>0"; // La imagene debe existir y estar creada diff --git a/admin/WebConsole/comandos/RestaurarSoftIncremental.php b/admin/WebConsole/comandos/RestaurarSoftIncremental.php index b030ce2b..3075819d 100644 --- a/admin/WebConsole/comandos/RestaurarSoftIncremental.php +++ b/admin/WebConsole/comandos/RestaurarSoftIncremental.php @@ -1,4 +1,4 @@ - -'?> -'?> +'?> +'?> -
- - - + + + - + - - + + - - + + - - + + @@ -117,7 +117,7 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"];
>>  >>  >>  
- -texto.= " WHERE imagesbas.codpar=".$codpar; - else - $cmd->texto.= " WHERE imagesbas.codpar<>".$codpar; - - $cmd->texto.=" AND imagenes.tipo=".$IMAGENES_INCREMENTALES; + INNER JOIN repositorios ON repositorios.idrepositorio=imagesbas.idrepositorio + AND imagenes.tipo=".$IMAGENES_INCREMENTALES; // AND imagenes.idperfilsoft>=0"; // La imagene debe existir y estar creada $idordenador1 = explode(",",$idordenadores); diff --git a/admin/WebConsole/comandos/gestores/gestor_Comandos.php b/admin/WebConsole/comandos/gestores/gestor_Comandos.php index 7e22d431..dd06022d 100644 --- a/admin/WebConsole/comandos/gestores/gestor_Comandos.php +++ b/admin/WebConsole/comandos/gestores/gestor_Comandos.php @@ -9,6 +9,7 @@ // Gestor de todos los comandos // ************************************************************************************************************************************************* include_once("../../includes/ctrlacc.php"); +include_once("../../includes/restfunctions.php"); include_once("../../clases/AdoPhp.php"); include_once("../../clases/SockHidra.php"); include_once("../../includes/constantes.php"); @@ -19,8 +20,7 @@ include_once("../../includes/RecopilaIpesMacs.php"); //________________________________________________________________________________________________________ include_once("../includes/capturaacciones.php"); //________________________________________________________________________________________________________ - - // Recoge parametros de seguimiento +// Recoge parametros de seguimiento $sw_ejya=""; $sw_seguimiento=""; $sw_ejprg=""; @@ -28,6 +28,7 @@ $sw_mkprocedimiento=""; $nombreprocedimiento=""; $idprocedimiento=""; $ordprocedimiento=0; +$avisoRepo=false; $sw_mktarea=""; $nombretarea=""; @@ -74,18 +75,7 @@ $atributos=str_replace('$',chr(9),$atributos); - '?> - '?> - - - + '?> $cadenaid=""; $cadenaip=""; $cadenamac=""; +$cadenaoga=""; // Clave de acceso a la API REST de OGAgent. if(!empty($filtro)){ // Ambito restringido a un subconjuto de ordenadores if(substr($filtro,strlen($cadenaid)-1,1)==";") // Si el último caracter es una coma @@ -124,6 +115,11 @@ $cmd->CreaParametro("@restrambito","",0); $cmd->CreaParametro("@ordprocedimiento",0,1); $cmd->CreaParametro("@ordtarea",0,1); +/* PARCHE UHU heredado de la version 1.1.0: Si la accion a realizar es Arrancar incluimos una pagina para arrancar desde el repo */ +if($funcion == "nfn=Arrancar".chr(13)) + include("wakeonlan_repo.php"); +/**/ + if($ambito==0){ // Ambito restringido a un subconjuto de ordenadores con formato (idordenador1,idordenador2,etc) $cmd->ParamSetValor("@restrambito",$idambito); $idambito=0; @@ -166,7 +162,6 @@ if($sw_ejya=='on' || $sw_ejprg=="on" ){ VALUES (@idordenador,@tipoaccion,@idtipoaccion,@descriaccion,@ip, @sesion,@idcomando,@parametros,@fechahorareg,@estado,@resultado,@ambito,@idambito,@restrambito,@idcentro)"; $resul=$cmd->Ejecutar(); - //echo "
".$cmd->texto; } $acciones=chr(13)."ids=".$sesion.chr(13); // Para seguimiento } @@ -176,13 +171,16 @@ if($sw_ejya=='on' || $sw_ejprg=="on" ){ echo ''; } else{ + $ValorParametros=extrae_parametros($parametros,chr(13),'='); + $script=@urldecode($ValorParametros["scp"]); if($sw_ejya=='on'){ - // Envio al servidor - $shidra=new SockHidra($servidorhidra,$hidraport); - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra + // comando 16 sólo agente nuevo + if ($idcomando != 16){ + // Envio al servidor + $shidra=new SockHidra($servidorhidra,$hidraport); + if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra $parametros.=$aplicacion; $parametros.=$acciones; - //die($parametros); $resul=$shidra->envia_comando($parametros); if($resul) $trama=$shidra->recibe_respuesta(); @@ -193,15 +191,95 @@ if($sw_ejya=='on' || $sw_ejprg=="on" ){ $resul=$ValorParametros["res"]; } $shidra->desconectar(); + } + // Guardamos resultado de ogAgent original + $resulhidra = $resul; + } else { + // En agente nuevo devuelvo siempre correcto + $resulhidra = 1; + } + + // Comprobamos si el comando es soportado por el nuevo ogAgent + $numip=0; + $ogAgentNuevo = false; + switch ($idcomando) { + case 2: + // Apagar + $urlcomando = 'poweroff'; + $ogAgentNuevo = true; + break; + case 5: + // Reiniciar + $urlcomando = 'reboot'; + $ogAgentNuevo = true; + break; + case 8: + // Ejecutar script + $urlcomando = 'script'; + $ogAgentNuevo = true; + $client = (isset ($_POST['modoejecucion']) && $_POST['modoejecucion'] != '' ) ? $_POST['modoejecucion'] : 'true'; + $paramsPost = '{"script":"'.base64_encode($script).'","client":"'.$client.'"}'; + break; + case 16: + // Enviar mensaje + $urlcomando = 'popup'; + $ogAgentNuevo = true; + $paramsPost = '{"title":"'.$_POST['titulo'].'","message":"'.$_POST['mensaje'].'"}'; + break; + } + + // Se envía acción al nuevo ogAgent + if ( $ogAgentNuevo ) { + // Send REST requests to new OGAgent clients. + $urls = array(); + $ipsuccess = ''; + // Compose array of REST URLs. + $auxIp = explode(';', $cadenaip); + $auxKey = explode(";", $cadenaoga); + $i = 0; + foreach ($auxIp as $ip) { + $urls[$ip]['url'] = "https://$ip:8000/opengnsys/$urlcomando"; + if (isset($auxKey[$i])) $urls[$ip]['header'] = Array("Authorization: ".$auxKey[$i]); + if (isset($paramsPost)) $urls[$ip]['post'] = $paramsPost; + + $i++; + } + // Launch concurrent requests. + $responses = multiRequest($urls); + // Process responses array (IP as array index). + foreach ($responses as $ip => $resp) { + // Check if response code is OK (200). + if ($resp['code'] == 200) { + $ipsuccess .= "'".$ip."',"; + $numip++; + } + } + // quitamos último carácter ',' + $ipsuccess=substr($ipsuccess, 0, -1); + + // Actualizamos la cola de acciones con los que no dan error + if ( $numip >> 0 ) { + $fin= date ("Y-m-d H:i:s"); + $cmd->texto="UPDATE acciones SET resultado='1', estado='3', ". + " descrinotificacion='', fechahorafin='".$fin."' ". + " WHERE ip IN ($ipsuccess) AND idcomando='$idcomando' ". + " ORDER BY idaccion DESC LIMIT $numip"; + $resul=$cmd->Ejecutar(); + } } - if (!$resul){ + // Mostramos mensaje con resultado + if (!$resulhidra && $numip == 0){ echo ''; } else{ echo ''.chr(13); } } diff --git a/admin/WebConsole/comandos/gestores/wakeonlan_repo.php b/admin/WebConsole/comandos/gestores/wakeonlan_repo.php new file mode 100644 index 00000000..b2929d48 --- /dev/null +++ b/admin/WebConsole/comandos/gestores/wakeonlan_repo.php @@ -0,0 +1,85 @@ +texto="SELECT repo.ip, repo.apikey FROM ordenadores o,repositorios repo WHERE o.mac=\"".$mac."\" AND o.idrepositorio=repo.idrepositorio"; + $rs=new Recordset; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) + return; // Error al abrir recordset + while (!$rs->EOF){ + $repo = $rs->campos["ip"]; + if(!existREPO($repo, $repos)){ + $repos[count($repos)]=$repo; + } + // Una vez creado el repo se asigna la mac del pc a su lista + if(empty($reposAndMacs[$repo])){ + $reposAndMacs[$repo] = array(); + $reposAndMacs[$repo]["apikey"] = $rs->campos["apikey"]; + } + // Modificar la mac añadiendo ":" cada dos caracteres + $tmp = substr_replace($mac, ":", 2, 0); + $tmp = substr_replace($tmp, ":", 5, 0); + $tmp = substr_replace($tmp, ":", 8, 0); + $tmp = substr_replace($tmp, ":", 11, 0); + $tmp = substr_replace($tmp, ":", 14, 0); + + $reposAndMacs[$repo][count($reposAndMacs[$repo])] = $tmp; + $rs->Siguiente(); + } + $rs->Cerrar(); +} +// En este punto tenemos un array con todos los repos y cada uno de ellos con una lista de todas las macs que deben arrancar +// Recorremos cada uno de ellos +foreach($reposAndMacs as $repo => $macs){ + // En el array de $macs tenemos la clave "apikey" + if($macs["apikey"] !== ""){ + $apiKeyRepo = $macs["apikey"]; + unset($macs["apikey"]); + // Componer datos de conexión para el repositorio. + $urls[$repo]['url'] = "https://$repo/opengnsys/rest/repository/poweron"; + $urls[$repo]['header'] = array('Authorization: '. $apiKeyRepo); + $urls[$repo]['post'] = '{"macs": ["' . implode('","', $macs) . '"]}'; + } + else{ + $avisoRepo = true; + } +} +// Enviar petición múltiple a los repositorios afectados. +if (isset($urls)) { + $result = multiRequest($urls); + // Comprobar respuesta. + foreach ($result as $repo => $res) { + if ($res['code'] != 200) { + $avisoRepo = true; + } + } +} + + +function existREPO($repo, $repos){ + $found=false; + $index = 0; + while(!$found && $index < count($repos)){ + $r = $repos[$index]; + if($r == $repo) + $found=true; + } + return $found; +} + +?> diff --git a/admin/WebConsole/comandos/includes/FiltradoAmbito.php b/admin/WebConsole/comandos/includes/FiltradoAmbito.php index 62b12952..6bc524df 100644 --- a/admin/WebConsole/comandos/includes/FiltradoAmbito.php +++ b/admin/WebConsole/comandos/includes/FiltradoAmbito.php @@ -173,13 +173,24 @@ function RecorriendoOrdenadores($cmd) '.$TbMsg["STATUS_OPG"].' + -'.$TbMsg["STATUS_WXP"].' + +'.$TbMsg["STATUS_WIN"].' -'.$TbMsg["STATUS_LNX"].' +'.$TbMsg["STATUS_WINS"].' +'.$TbMsg["STATUS_LNX"].' + + +'.$TbMsg["STATUS_LNXS"].' + + +'.$TbMsg["STATUS_OSX"].' + + '; @@ -193,7 +204,7 @@ function RecorriendoOrdenadores($cmd) $ip=$rs->campos["ip"]; $cadenaip.=$ip.";"; $htmlCode.=''; - $htmlCode.=' '; + $htmlCode.=' '; $htmlCode.=' '; $htmlCode.=' '; $htmlCode.=' '; @@ -219,8 +230,8 @@ echo ''; ?> - -CreaParametro("@idcentro",$idcentro,1); $cmd->CreaParametro("@nombrecentro",$nombrecentro,0); $cmd->CreaParametro("@comentarios",$comentarios,0); + $cmd->CreaParametro("@directorio",$directorio,0); switch($opcion){ case $op_alta : - $cmd->texto="INSERT INTO centros(nombrecentro,comentarios,identidad) VALUES (@nombrecentro,@comentarios,@identidad)"; + $cmd->texto="INSERT INTO centros(nombrecentro,comentarios,directorio,identidad) VALUES (@nombrecentro,@comentarios,@directorio,@identidad)"; $resul=$cmd->Ejecutar(); if ($resul){ // Crea una tabla nodo para devolver a la página que llamó ésta $idcentro=$cmd->Autonumerico(); @@ -128,7 +131,7 @@ function Gestiona(){ } break; case $op_modificacion: - $cmd->texto="UPDATE centros SET nombrecentro=@nombrecentro,comentarios=@comentarios WHERE idcentro=@idcentro"; + $cmd->texto="UPDATE centros SET nombrecentro=@nombrecentro,comentarios=@comentarios,directorio=@directorio WHERE idcentro=@idcentro"; $resul=$cmd->Ejecutar(); break; case $op_eliminacion : diff --git a/admin/WebConsole/gestores/gestor_componentehardwares.php b/admin/WebConsole/gestores/gestor_componentehardwares.php index 5710f5f3..00fec28c 100644 --- a/admin/WebConsole/gestores/gestor_componentehardwares.php +++ b/admin/WebConsole/gestores/gestor_componentehardwares.php @@ -1,4 +1,4 @@ -'; echo ''; echo ' '; + echo ''; echo ''; echo '

'; echo ' '; @@ -102,6 +104,7 @@ function Gestiona(){ global $identidad; global $nombreentidad; global $comentarios; + global $ogunit; global $grupoid; global $iduniversidad; @@ -116,10 +119,11 @@ function Gestiona(){ $cmd->CreaParametro("@identidad",$identidad,1); $cmd->CreaParametro("@nombreentidad",$nombreentidad,0); $cmd->CreaParametro("@comentarios",$comentarios,0); + $cmd->CreaParametro("@ogunit",$ogunit,0); switch($opcion){ case $op_alta : - $cmd->texto="INSERT INTO entidades(nombreentidad,comentarios,iduniversidad,grupoid) VALUES (@nombreentidad,@comentarios,@iduniversidad,@grupoid)"; + $cmd->texto="INSERT INTO entidades(nombreentidad,comentarios,ogunit,iduniversidad,grupoid) VALUES (@nombreentidad,@comentarios,@ogunit,@iduniversidad,@grupoid)"; $resul=$cmd->Ejecutar(); if ($resul){ // Crea una tabla nodo para devolver a la página que llamó ésta $identidad=$cmd->Autonumerico(); @@ -131,7 +135,7 @@ function Gestiona(){ } break; case $op_modificacion: - $cmd->texto="UPDATE entidades SET nombreentidad=@nombreentidad,comentarios=@comentarios WHERE identidad=@identidad"; + $cmd->texto="UPDATE entidades SET nombreentidad=@nombreentidad,comentarios=@comentarios,ogunit=@ogunit WHERE identidad=@identidad"; $resul=$cmd->Ejecutar(); break; case $op_eliminacion : diff --git a/admin/WebConsole/gestores/gestor_entornos.php b/admin/WebConsole/gestores/gestor_entornos.php index 6836db45..9a8683b6 100644 --- a/admin/WebConsole/gestores/gestor_entornos.php +++ b/admin/WebConsole/gestores/gestor_entornos.php @@ -1,4 +1,4 @@ - - '?> + '?> - - - -CreaParametro("@grupoid",$grupoid,1); $cmd->CreaParametro("@idperfilsoft",$idperfilsoft,1); $cmd->CreaParametro("@comentarios",$comentarios,0); + $cmd->CreaParametro("@inremotepc",$inremotepc,1); $cmd->CreaParametro("@numpar",$numpar,1); $cmd->CreaParametro("@codpar",$codpar,1); $cmd->CreaParametro("@idrepositorio",$idrepositorio,1); @@ -148,8 +152,13 @@ function Gestiona(){ switch($opcion){ case $op_alta : - $cmd->texto="INSERT INTO imagenes (nombreca,ruta,descripcion,idperfilsoft,comentarios,numpar,codpar,idrepositorio,imagenid,idcentro,grupoid,tipo) - VALUES (@nombreca,@ruta,@descripcion,@idperfilsoft,@comentarios,@numpar,@codpar,@idrepositorio,@imagenid,@idcentro,@grupoid,@tipo)"; + $cmd->texto="INSERT INTO imagenes + (nombreca, ruta, descripcion, idperfilsoft, + comentarios, inremotepc, numpar, codpar, + idrepositorio, imagenid, idcentro, grupoid, tipo) + VALUES (@nombreca, @ruta, @descripcion, @idperfilsoft, + @comentarios, @inremotepc, @numpar, @codpar, + @idrepositorio, @imagenid, @idcentro, @grupoid, @tipo)"; $resul=$cmd->Ejecutar(); if ($resul){ // Crea una tabla nodo para devolver a la página que llamó ésta $idimagen=$cmd->Autonumerico(); @@ -161,10 +170,12 @@ function Gestiona(){ } break; case $op_modificacion: - $cmd->texto="UPDATE imagenes SET nombreca=@nombreca,ruta=@ruta,descripcion=@descripcion,idperfilsoft=@idperfilsoft, - comentarios=@comentarios,numpar=@numpar,codpar=@codpar,idrepositorio=@idrepositorio, - imagenid=@imagenid - WHERE idimagen=@idimagen"; + $cmd->texto="UPDATE imagenes SET + nombreca=@nombreca, ruta=@ruta, descripcion=@descripcion, + idperfilsoft=@idperfilsoft, comentarios=@comentarios, + inremotepc=@inremotepc, numpar=@numpar,codpar=@codpar, + idrepositorio=@idrepositorio, imagenid=@imagenid + WHERE idimagen=@idimagen"; $resul=$cmd->Ejecutar(); break; case $op_eliminacion : diff --git a/admin/WebConsole/gestores/gestor_inclusionacciones.php b/admin/WebConsole/gestores/gestor_inclusionacciones.php index 6d28f513..964158e8 100644 --- a/admin/WebConsole/gestores/gestor_inclusionacciones.php +++ b/admin/WebConsole/gestores/gestor_inclusionacciones.php @@ -1,4 +1,4 @@ -texto="SELECT * FROM ordenadores WHERE idordenador=".$idordenador; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error al abrir recordset + $rs->Primero(); + if (!$rs->EOF){ + $arranque=$rs->campos["arranque"]; + $rs->Cerrar(); + } + } +######## AGP + $tablanodo=""; // Arbol para nodos insertados //________________________________________________________________________________________________________ $cmd=CreaComando($cadenaconexion); // Crea objeto comando @@ -118,8 +147,13 @@ if($opcion!=$op_movida){ break; } if ($resul){ - if ($opcion==$op_alta ) + if ($opcion==$op_alta ) { + if ( $datosduplicados != '') { + echo $literal."(0,'".$TbMsg["DUPLICADO"].$datosduplicados." ',".$idordenador.",o.innerHTML);".chr(13); + } else { echo $literal."(1,'".$cmd->DescripUltimoError()." ',".$idordenador.",o.innerHTML);".chr(13); + } + } else echo $literal."(1,'".$cmd->DescripUltimoError()." ','".$nombreordenador."');".chr(13); } @@ -157,11 +191,13 @@ function Gestiona(){ global $grupoid; global $idordenador; global $nombreordenador; + global $numserie; global $ip; global $mac; global $idaula; global $idperfilhard; global $idrepositorio; + global $oglive; global $idmenu; global $idprocedimiento; global $netiface; @@ -180,15 +216,20 @@ function Gestiona(){ global $op_movida; global $tablanodo; +####################### Irina + global $datosduplicados; + $cmd->CreaParametro("@grupoid",$grupoid,1); $cmd->CreaParametro("@idaula",$idaula,1); $cmd->CreaParametro("@idordenador",$idordenador,1); $cmd->CreaParametro("@nombreordenador",$nombreordenador,0); + $cmd->CreaParametro("@numserie",$numserie,0); $cmd->CreaParametro("@ip",$ip,0); $cmd->CreaParametro("@mac",$mac,0); $cmd->CreaParametro("@idperfilhard",$idperfilhard,1); $cmd->CreaParametro("@idrepositorio",$idrepositorio,1); + $cmd->CreaParametro("@oglivedir",$oglive,0); $cmd->CreaParametro("@idmenu",$idmenu,1); $cmd->CreaParametro("@idprocedimiento",$idprocedimiento,1); $cmd->CreaParametro("@netiface",$netiface,0); @@ -203,27 +244,49 @@ function Gestiona(){ switch($opcion){ case $op_alta : - //Insertar fotoord con Values @fotoordenador - $cmd->texto="INSERT INTO ordenadores(nombreordenador,ip,mac,idperfilhard,idrepositorio, - idmenu,idproautoexec,idaula,grupoid,netiface,netdriver,fotoord,validacion,paginalogin,paginavalidacion) VALUES (@nombreordenador,@ip,@mac,@idperfilhard,@idrepositorio, - @idmenu,@idprocedimiento,@idaula,@grupoid,@netiface,@netdriver,@fotoordenador,@validacion,@paginalogin,@paginavalidacion)"; + // Comprueba que no existan duplicados + $ipduplicada='no'; + $nombreduplicado='no'; + $macduplicada='no'; + $cmd->texto="SELECT nombreordenador,ip,mac FROM ordenadores + WHERE nombreordenador=@nombreordenador OR ip=@ip OR mac=@mac"; + $rs=new Recordset; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(0); // Error al abrir recordset + $rs->Primero(); + while (!$rs->EOF){ + if ( $nombreordenador == $rs->campos["nombreordenador"]) $datosduplicados ="nombre: $nombreordenador,"; + if ( $ip == $rs->campos["ip"]) $datosduplicados .=" ip: $ip,"; + if ( $mac == $rs->campos["mac"]) $datosduplicados .=" mac: $mac,"; + $rs->Siguiente(); + } + $rs->Cerrar(); + // quitamos última coma + $datosduplicados = trim($datosduplicados, ','); + // Si no hay datos duplicados insertamos el ordenador; + if ( $datosduplicados == "" ) { + //Insertar fotoord con Values @fotoordenador + $cmd->texto="INSERT INTO ordenadores(nombreordenador,numserie,ip,mac,idperfilhard,idrepositorio,oglivedir, + idmenu,idproautoexec,idaula,grupoid,netiface,netdriver,fotoord,validacion,paginalogin,paginavalidacion) VALUES (@nombreordenador,@numserie,@ip,@mac,@idperfilhard,@idrepositorio,@oglivedir, + @idmenu,@idprocedimiento,@idaula,@grupoid,@netiface,@netdriver,@fotoordenador,@validacion,@paginalogin,@paginavalidacion)"; + } $resul=$cmd->Ejecutar(); - //echo $cmd->texto; if ($resul){ // Crea una tabla nodo para devolver a la página que llamó ésta - $idordenador=$cmd->Autonumerico(); - $arbolXML=SubarbolXML_ordenadores($idordenador,$nombreordenador); - $baseurlimg="../images/signos"; // Url de las imagenes de signo - $clasedefault="texto_arbol"; // Hoja de estilo (Clase por defecto) del árbol - $arbol=new ArbolVistaXML($arbolXML,0,$baseurlimg,$clasedefault); - $tablanodo=$arbol->CreaArbolVistaXML(); + $idordenador=$cmd->Autonumerico(); + // Crear fichero TFTP/PXE por defecto para el nuevo ordenador. + createBootMode ($cmd, "", $idordenador, $idioma); + // Insertar datos en el árbol de configuración. + $arbolXML=SubarbolXML_ordenadores($idordenador,$nombreordenador); + $baseurlimg="../images/signos"; // Url de las imagenes de signo + $clasedefault="texto_arbol"; // Hoja de estilo (Clase por defecto) del árbol + $arbol=new ArbolVistaXML($arbolXML,0,$baseurlimg,$clasedefault); + $tablanodo=$arbol->CreaArbolVistaXML(); } - // Crear fichero TFTP/PXE por defecto para el nuevo ordenador. - createBootMode ($cmd, "", $idordenador, $idioma); break; case $op_modificacion: - $cmd->texto="UPDATE ordenadores SET nombreordenador=@nombreordenador,ip=@ip,mac=@mac,idperfilhard=@idperfilhard, - idrepositorio=@idrepositorio,idmenu=@idmenu,idproautoexec=@idprocedimiento,netiface=@netiface,netdriver=@netdriver,fotoord=@fotoordenador,validacion=@validacion,paginalogin=@paginalogin,paginavalidacion=@paginavalidacion + $cmd->texto="UPDATE ordenadores SET nombreordenador=@nombreordenador,numserie=@numserie,ip=@ip,mac=@mac,idperfilhard=@idperfilhard, + idrepositorio=@idrepositorio,oglivedir=@oglivedir,idmenu=@idmenu,idproautoexec=@idprocedimiento,netiface=@netiface,netdriver=@netdriver,fotoord=@fotoordenador,validacion=@validacion,paginalogin=@paginalogin,paginavalidacion=@paginavalidacion WHERE idordenador=@idordenador"; $resul=$cmd->Ejecutar(); // Actualizar fichero TFTP/PXE a partir de la plantilla asociada. @@ -237,6 +300,8 @@ function Gestiona(){ case $op_movida : $cmd->texto="UPDATE ordenadores SET idaula=@idaula, grupoid=@grupoid WHERE idordenador=@idordenador"; $resul=$cmd->Ejecutar(); + // Actualizar fichero TFTP/PXE a partir de la plantilla asociada. + createBootMode ($cmd, $arranque, $idordenador, $idioma); break; default: break; diff --git a/admin/WebConsole/gestores/gestor_ordenadorestandar.php b/admin/WebConsole/gestores/gestor_ordenadorestandar.php index ddefd72e..d7eeb4d7 100644 --- a/admin/WebConsole/gestores/gestor_ordenadorestandar.php +++ b/admin/WebConsole/gestores/gestor_ordenadorestandar.php @@ -1,4 +1,4 @@ - -'.chr(13); @@ -65,7 +65,7 @@ else{ ?> -CreaParametro("@ip",$ip,0); $cmd->CreaParametro("@passguor",$passguor,0); $cmd->CreaParametro("@puertorepo",$puertorepo,0); + $cmd->CreaParametro("@apiKeyRepo",$apiKeyRepo,0); $cmd->CreaParametro("@comentarios",$comentarios,0); switch($opcion){ case $op_alta : - $cmd->texto="INSERT INTO repositorios(idcentro,grupoid,nombrerepositorio,ip,passguor,puertorepo,comentarios) VALUES (@idcentro,@grupoid,@nombrerepositorio,@ip,@passguor,@puertorepo,@comentarios)"; + $cmd->texto="INSERT INTO repositorios(idcentro,grupoid,nombrerepositorio,ip,passguor,puertorepo,comentarios,apikey) VALUES (@idcentro,@grupoid,@nombrerepositorio,@ip,@passguor,@puertorepo,@comentarios,@apiKeyRepo)"; $resul=$cmd->Ejecutar(); if ($resul){ // Crea una tabla nodo para devolver a la p�gina que llam� �sta $idrepositorio=$cmd->Autonumerico(); @@ -142,8 +147,11 @@ function Gestiona(){ } break; case $op_modificacion: - $cmd->texto="UPDATE repositorios SET nombrerepositorio=@nombrerepositorio,ip=@ip,passguor=@passguor,puertorepo=@puertorepo,comentarios=@comentarios WHERE idrepositorio=@idrepositorio"; + $cmd->texto="UPDATE repositorios SET nombrerepositorio=@nombrerepositorio,ip=@ip,passguor=@passguor,puertorepo=@puertorepo,comentarios=@comentarios, apikey=@apiKeyRepo WHERE idrepositorio=@idrepositorio"; $resul=$cmd->Ejecutar(); + if ($resul) { + updateBootRepo($cmd, $idrepositorio); + } break; case $op_eliminacion : $resul=Eliminarepositorios($cmd,$idrepositorio,"idrepositorio"); diff --git a/admin/WebConsole/gestores/gestor_reservas.php b/admin/WebConsole/gestores/gestor_reservas.php index 5150a42b..b983ecee 100644 --- a/admin/WebConsole/gestores/gestor_reservas.php +++ b/admin/WebConsole/gestores/gestor_reservas.php @@ -1,4 +1,4 @@ - - - - -CreaParametro("@idambito",$idambito,1); $cmd->CreaParametro("@ididioma",$ididioma,1); $cmd->CreaParametro("@idtipousuario",$idtipousuario,1); + // Generar clave de acceso a la API REST. + $apikey=md5(uniqid(rand(), true)); + $cmd->CreaParametro("@apikey",$apikey,0); switch($opcion){ case $op_alta : - $cmd->texto="INSERT INTO usuarios (usuario,pasguor,nombre,email,ididioma,idtipousuario ) VALUES (@usuario,@pasguor,@nombre,@email,@ididioma,@idtipousuario);"; + $cmd->texto="INSERT INTO usuarios (usuario,pasguor,nombre,email,ididioma,idtipousuario,apikey) VALUES (@usuario,SHA2(@pasguor,224),@nombre,@email,@ididioma,@idtipousuario,@apikey);"; $resul=$cmd->Ejecutar(); if ($resul){ // Crea una tabla nodo para devolver a la página que llamó ésta $idusuario=$cmd->Autonumerico(); @@ -141,7 +144,7 @@ function Gestiona(){ } break; case $op_modificacion: - $cmd->texto="UPDATE usuarios SET usuario=@usuario,pasguor=@pasguor,nombre=@nombre,email=@email,ididioma=@ididioma WHERE idusuario=@idusuario"; + $cmd->texto="UPDATE usuarios SET usuario=@usuario,pasguor=SHA2(@pasguor,224),nombre=@nombre,email=@email,ididioma=@ididioma WHERE idusuario=@idusuario"; $resul=$cmd->Ejecutar(); break; case $op_eliminacion : @@ -160,18 +163,16 @@ function Gestiona(){ ________________________________________________________________________________________________________*/ function toma_usuario($cmd,$idusuario){ global $usuario; - global $pasguor; global $idambito; global $idtipousuario; $rs=new Recordset; - $cmd->texto="SELECT usuario, pasguor,idambito,idtipousuario FROM usuarios WHERE idusuario=".$idusuario; + $cmd->texto="SELECT usuario, idambito, idtipousuario FROM usuarios WHERE idusuario=".$idusuario; $rs->Comando=&$cmd; if (!$rs->Abrir()) return(0); // Error al abrir recordset $rs->Primero(); if (!$rs->EOF){ $usuario=$rs->campos["usuario"]; - $pasguor=$rs->campos["pasguor"]; $idambito=$rs->campos["idambito"]; $idtipousuario=$rs->campos["idtipousuario"]; return(true); diff --git a/admin/WebConsole/gestores/relaciones/aulas_eliminacion.php b/admin/WebConsole/gestores/relaciones/aulas_eliminacion.php index a9d2bc10..f42c6744 100644 --- a/admin/WebConsole/gestores/relaciones/aulas_eliminacion.php +++ b/admin/WebConsole/gestores/relaciones/aulas_eliminacion.php @@ -1,4 +1,4 @@ -(léase OpenGénesis) reúne el esfuerzo conjunto de varias Universidades Públicas Españolas, para disponer de una serie de herramientas libres y abiertas que constituyan un sistema completo, versátil e intuitivo, para la gestión y clonación de equipos. Esta aplicación permite la distribución, instalación y despliegue de distintos sistemas operativos. '; -$TbMsg["LICENSE"]='OpenGnSys es un proyecto de Software Libre, todo el código está licenciado bajo '; +$TbMsg["DESCRIPTION"]='OpenGnsys (léase OpenGénesis) reúne el esfuerzo conjunto de varias Universidades Públicas Españolas, para disponer de una serie de herramientas libres y abiertas que constituyan un sistema completo, versátil e intuitivo, para la gestión y clonación de equipos. Esta aplicación permite la distribución, instalación y despliegue de distintos sistemas operativos. '; +$TbMsg["LICENSE"]='OpenGnsys es un proyecto de Software Libre, todo el código está licenciado bajo '; $TbMsg["LINK"]='Web del proyecto: '; $TbMsg["CHANGE"]='Canvis en: '; -$TbMsg["MANUAL"]='Manual OpenGnSys '; +$TbMsg["MANUAL"]='Manual OpenGnsys '; ?> diff --git a/admin/WebConsole/idiomas/php/cat/actualizar_cat.php b/admin/WebConsole/idiomas/php/cat/actualizar_cat.php index 5d7ef58d..40365eb0 100644 --- a/admin/WebConsole/idiomas/php/cat/actualizar_cat.php +++ b/admin/WebConsole/idiomas/php/cat/actualizar_cat.php @@ -1,4 +1,4 @@ -Un menú personalizado se define introduciendo la URL de la página HTML que lo define.
Un menú automático se compone a partir de los procedimientos definidos.'; +$TbMsg["WARN_GPT"]='AVISO: Para tabla de particiones GPT es necesario que la primera partición sea tipo EFI
y se recomienda un tamaño en torno a 512Mb.'; +$TbMsg["WARN_SCHEDULER"]='AVISO: activar calendario de eventos de la BD para habilitar esta propiedad.'; +$TbMsg["WARN_SOURCE_PATH"]='AVISO: La ruta de origen sólo se utiliza en las sincronizadas tipo directorio.'; ?> diff --git a/admin/WebConsole/idiomas/php/cat/barramenu_cat.php b/admin/WebConsole/idiomas/php/cat/barramenu_cat.php index 281b63e9..338ebb32 100644 --- a/admin/WebConsole/idiomas/php/cat/barramenu_cat.php +++ b/admin/WebConsole/idiomas/php/cat/barramenu_cat.php @@ -1,4 +1,4 @@ -semanas[5]=array ("5ª",0x10); $this->semanas[6]=array ("Última",0x20); - $this->numero_annos[1]=array ("2010",0x01); // tamaño 1 bytes - $this->numero_annos[2]=array ("2011",0x02); - $this->numero_annos[3]=array ("2012",0x04); - $this->numero_annos[4]=array ("2013",0x08); - $this->numero_annos[5]=array ("2014",0x10); - $this->numero_annos[6]=array ("2015",0x20); - $this->numero_annos[7]=array ("2016",0x40); - $this->numero_annos[8]=array ("2017",0x80); + $this->numero_annos[2010]=0x0001; // tamaño 2 bytes + $this->numero_annos[2011]=0x0002; + $this->numero_annos[2012]=0x0004; + $this->numero_annos[2013]=0x0008; + $this->numero_annos[2014]=0x0010; + $this->numero_annos[2015]=0x0020; + $this->numero_annos[2016]=0x0040; + $this->numero_annos[2017]=0x0080; + $this->numero_annos[2018]=0x0100; + $this->numero_annos[2019]=0x0200; + $this->numero_annos[2020]=0x0400; + $this->numero_annos[2021]=0x0800; + $this->numero_annos[2022]=0x1000; + $this->numero_annos[2023]=0x2000; + $this->numero_annos[2024]=0x4000; + $this->numero_annos[2025]=0x8000; $this->numero_dias[1]=0x00000001; // tamaño 4 bytes $this->numero_dias[2]=0x00000002; @@ -179,7 +187,7 @@ class Almanaque{ $HTML_calendario='
'.$nombreordenador.'
'.$ip.'
'.chr(13); $HTML_calendario.=''.chr(13); $HTML_calendario.=''.chr(13); // Literal años - for ($i=1;$i<9;$i++){ + for ($i=$ano_desde; $i<=ano_hasta; $i++){ $HTML_calendario.=''.chr(13); + $tablaHtml.=''.chr(13); } $swcc=$rs->campos["clonable"] && !empty($rs->campos["idnombreso"]); @@ -236,9 +233,8 @@ function tablaConfiguracionesCrearImagen($cmd,$idordenador,$idrepositorio) $tablaHtml.=''.chr(13); else $tablaHtml.=''.chr(13); + $tablaHtml.=''; - $tablaHtml.=''; - //$tablaHtml.=''; } $tablaHtml.=''.chr(13); $rs->Siguiente(); @@ -259,8 +255,7 @@ function tablaConfiguracionesCrearImagen($cmd,$idordenador,$idrepositorio) $inicioTabla.=' '.chr(13); $inicioTabla.=' '.chr(13); $inicioTabla.=' '.chr(13); - $inicioTabla.=' '.chr(13); - $inicioTabla.=' '.chr(13); + $inicioTabla.=' '.chr(13); $inicioTabla.=' '.chr(13); $tablaHtml=$inicioTabla.$tablaHtml; diff --git a/admin/WebConsole/includes/restfunctions.php b/admin/WebConsole/includes/restfunctions.php new file mode 100644 index 00000000..3f91f7f5 --- /dev/null +++ b/admin/WebConsole/includes/restfunctions.php @@ -0,0 +1,72 @@ + false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_TIMEOUT_MS => 500)) { + + // array of curl handles + $curly = array(); + // Data to be returned (response data and code) + $result = array(); + + // multi handle + $mh = curl_multi_init(); + + // loop through $data and create curl handles + // then add them to the multi-handle + foreach ($data as $id => $d) { + + + $curly[$id] = curl_init(); + + $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d; + curl_setopt($curly[$id], CURLOPT_URL, $url); + // HTTP headers? + if (is_array($d) && !empty($d['header'])) { + curl_setopt($curly[$id], CURLOPT_HTTPHEADER, $d['header']); + } else { + curl_setopt($curly[$id], CURLOPT_HEADER, 0); + } + curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); + + // post? + if (is_array($d)) { + if (!empty($d['post'])) { + curl_setopt($curly[$id], CURLOPT_POST, 1); + curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']); + } + } + + // extra options? + if (!empty($options)) { + curl_setopt_array($curly[$id], $options); + } + + curl_multi_add_handle($mh, $curly[$id]); + } + + // execute the handles + $running = null; + do { + curl_multi_exec($mh, $running); + } while($running > 0); + + + // Get content and HTTP code, and remove handles + foreach($curly as $id => $c) { + $result[$id]['data'] = curl_multi_getcontent($c); + $result[$id]['code'] = curl_getinfo($c, CURLINFO_HTTP_CODE); + curl_multi_remove_handle($mh, $c); + } + + // all done + curl_multi_close($mh); + + return $result; +} +?> diff --git a/admin/WebConsole/includes/tftputils.php b/admin/WebConsole/includes/tftputils.php index 13b126f3..55f7a871 100644 --- a/admin/WebConsole/includes/tftputils.php +++ b/admin/WebConsole/includes/tftputils.php @@ -11,6 +11,9 @@ include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); +// Directorio de ficheros PXE. +define("PXEDIR", "/opt/opengnsys/tftpboot/menu.lst"); + /** * @brief Sustituye espacio por "_" y quita acentos y tildes. @@ -21,7 +24,7 @@ include_once("../clases/AdoPhp.php"); * @date */ function cleanString ($cadena) { - return strtr ($cadena, " áéíóúñçÁÉÍÓÚÑÇ", "_aeiouncAEIOUNC"); + return strtr(trim($cadena), " áéíóúñçÁÉÍÓÚÑÇ", "_aeiouncAEIOUNC"); } @@ -51,9 +54,18 @@ function clientKernelVersion () { * @param {String} bootopt Plantilla de arranque PXE. * @param {Number} hostid Id. del ordenador. * @param {String} lang Idioma de arranque. - * @versión 1.0.5 - Primera versión, adaptada de NetBoot Avanzado. - * @authors Ramón Gómez - ETSII Universidad de Sevilla + * @version 1.0.5 - Primera versión, adaptada de NetBoot Avanzado (Antonio J. Doblas Viso - Universidad de Málaga) + * @author Ramón Gómez - ETSII Universidad de Sevilla * @date 2013-04-25 + * @version 1.1.0 - Se incluye la unidad organizativa como parametro del kernel: ogunit=directorio_unidad (ticket #678). + * @author Irina Gómez - ETSII Universidad de Sevilla + * @date 2015-12-16 + * @version 1.1.0 - La segunda fase de carga del ogLive se define en el SERVER para evitar erores de sincronismo entre versiones (ticket #787). + * @author Antonio J. Doblas Viso - Universidad de Malaga + * @date 2017-06-01 + * @version 1.1.0 - Se incluye el nombre del perfil hardware y se elimina el winboot (ticket #828). + * @author Antonio J. Doblas Viso - Universidad de Malaga + * @date 2018-01-21 */ function createBootMode ($cmd, $bootopt, $hostid, $lang) { @@ -69,13 +81,17 @@ function createBootMode ($cmd, $bootopt, $hostid, $lang) { // Obtener información de la base de datos. $cmd->texto="SELECT ordenadores.nombreordenador AS hostname, ordenadores.ip AS ip, ordenadores.mac AS mac, ordenadores.netiface AS netiface, + ordenadores.oglivedir AS oglivedir, aulas.netmask AS netmask, aulas.router AS router, - aulas.dns AS dns, aulas.proxy AS proxy, + aulas.ntp AS ntp, aulas.dns AS dns, aulas.proxy AS proxy, aulas.nombreaula AS grupo, repositorios.ip AS iprepo, (SELECT ipserveradm FROM entornos LIMIT 1) AS ipserveradm, - menus.resolucion AS vga, perfileshard.winboot AS winboot + menus.resolucion AS vga, perfileshard.descripcion AS hardprofile, + centros.directorio, entidades.ogunit FROM ordenadores JOIN aulas USING (idaula) + JOIN centros USING (idcentro) + JOIN entidades USING (identidad) JOIN repositorios USING (idrepositorio) LEFT JOIN menus USING (idmenu) LEFT JOIN perfileshard USING (idperfilhard) @@ -91,13 +107,21 @@ function createBootMode ($cmd, $bootopt, $hostid, $lang) { $netiface=$rs->campos["netiface"]; $netmask=$rs->campos["netmask"]; $router=$rs->campos["router"]; + $ntp=$rs->campos["ntp"]; $dns=$rs->campos["dns"]; $proxy=$rs->campos["proxy"]; $group=cleanString($rs->campos["grupo"]); $repo=$rs->campos["iprepo"]; $server=$rs->campos["ipserveradm"]; $vga=$rs->campos["vga"]; - $winboot=$rs->campos["winboot"]; + $hardprofile=cleanString($rs->campos["hardprofile"]); + $oglivedir=$rs->campos["oglivedir"]; + $ogunit=$rs->campos["ogunit"]; + if ($ogunit == 0 or $rs->campos["directorio"] == null) { + $directorio="" ; + } else { + $directorio=$rs->campos["directorio"]; + } $rs->Cerrar(); @@ -119,13 +143,14 @@ function createBootMode ($cmd, $bootopt, $hostid, $lang) { " ip=$ip:$server:$router:$netmask:$hostname:$netiface:none" . " group=$group" . " ogrepo=$repo" . - " oglive=$repo" . + " oglive=$server" . " oglog=$server" . " ogshare=$server"; // Añadir parámetros opcionales. + if (! empty ($ntp)) { $infohost.=" ogntp=$ntp"; } if (! empty ($dns)) { $infohost.=" ogdns=$dns"; } if (! empty ($proxy)) { $infohost.=" ogproxy=$proxy"; } - if (! empty ($winboot)) { $infohost.=" winboot=$winboot"; } + if (! empty ($hardprofile)) { $infohost.=" hardprofile=$hardprofile"; } // Comprobar si se usa el parámetro "vga" (número de 3 cifras) o "video" (cadena). if (! empty ($vga)) { // UHU - Se sustituye la función is_int por is_numeric, ya que al ser un string no funciona bien con is_int @@ -135,21 +160,20 @@ function createBootMode ($cmd, $bootopt, $hostid, $lang) { $infohost.=" video=$vga"; } } + if (! empty ($directorio)) { $infohost.=" ogunit=$directorio"; } - // Obtener nombre de fichero PXE a partir de la MAC del ordenador cliente. - $pxedir="/opt/opengnsys/tftpboot/menu.lst"; $mac = substr($mac,0,2) . ":" . substr($mac,2,2) . ":" . substr($mac,4,2) . ":" . substr($mac,6,2) . ":" . substr($mac,8,2) . ":" . substr($mac,10,2); - $macfile="$pxedir/01-" . str_replace(":","-",strtoupper($mac)); + $macfile = PXEDIR . "/01-" . str_replace(":", "-", strtoupper($mac)); // Crear fichero de arranque a partir de la plantilla y los datos del cliente. // UHU - si el parametro vga no existe, no se quita. if (! empty ($vga)) { - exec ("sed -e 's|vga=...||g' -e 's|INFOHOST|$infohost|g' $pxedir/templates/$bootopt > $macfile"); + exec("sed -e 's|vga=...||g; s|INFOHOST|$infohost|g; s|set ISODIR=.*|set ISODIR=$oglivedir|g' " . PXEDIR . "/templates/$bootopt > $macfile"); } else{ - exec ("sed -e 's|INFOHOST|$infohost|g' $pxedir/templates/$bootopt > $macfile"); + exec("sed -e 's|INFOHOST|$infohost|g; s|set ISODIR=.*|set ISODIR=$oglivedir|g; s|set ISODIR=.*|set ISODIR=$oglivedir|g' " . PXEDIR . "/templates/$bootopt > $macfile"); } - exec ("chmod 777 $macfile"); + chmod($macfile, 0777); } @@ -164,10 +188,10 @@ function createBootMode ($cmd, $bootopt, $hostid, $lang) { function deleteBootFile ($mac) { // Obtener nombre de fichero a partir de dirección MAC. - $pxedir="/opt/opengnsys/tftpboot/menu.lst"; - $macfile = "$pxedir/01-" . substr($mac,0,2) . "-" . substr($mac,2,2) . "-" . substr($mac,4,2) . "-" . substr($mac,6,2) . "-" . substr($mac,8,2) . "-" . substr($mac,10,2); + $mac = strtoupper($mac); + $macfile = PXEDIR . "/01-" . substr($mac, 0, 2) . "-" . substr($mac, 2, 2) . "-" . substr($mac, 4, 2) . "-" . substr($mac, 6, 2) . "-" . substr($mac, 8, 2) . "-" . substr($mac, 10, 2); // Eliminar el fichero. - exec ("rm -f $macfile"); + @unlink($macfile); } /** @@ -212,5 +236,47 @@ function updateBootMode ($cmd, $idfield, $idvalue, $lang) { } } +/** + * updateBootRepo ($cmd, $repoid) + * @brief Actualiza la IP del repositorio en los ficheros PXE de todos sus equipos asociados. + * @param {Object} cmd Objeto de conexión con la base de datos + * @param {Integer} repoid Campo identificador del repositorio + * @return {Integer} 0, sin errores; -1, error acceso a BD; >0, ficheros no modificados + * @versión 1.1.0 - Primera versión. + * @authors Ramón Gómez - ETSII Universidad de Sevilla + * @date 2018-01-19 + */ +function updateBootRepo ($cmd, $repoid) { + $errors = 0; + // Obtener todas las MAC de los ordenadores incluidos en el repositorio. + $cmd->texto = "SELECT UPPER(ordenadores.mac) AS mac, repositorios.ip AS iprepo + FROM ordenadores + JOIN repositorios USING (idrepositorio) + WHERE ordenadores.idrepositorio = '$repoid'"; + $rs = new Recordset; + $rs->Comando=&$cmd; + if ($rs->Abrir()) { + $rs->Primero(); + while (! $rs->EOF) { + $mac = $rs->campos["mac"]; + $repo = $rs->campos["iprepo"]; + // Obtener nombre de fichero PXE a partir de la MAC del ordenador cliente. + $macfile = PXEDIR . "/01-" . substr($mac, 0, 2) . "-" . substr($mac, 2, 2) . "-" . substr($mac, 4, 2) . "-" . substr($mac, 6, 2) . "-" . substr($mac, 8, 2) . "-" . substr($mac, 10, 2); + // Actualizar parámetro "ogrepo" en el fichero PXE. + if ($pxecode = @file_get_contents($macfile)) { + $pxecode = preg_replace("/ogrepo=[^ ]*/", "ogrepo=$repo", $pxecode); + if (! @file_put_contents($macfile, $pxecode)) { + $erros++; + } + } + $rs->Siguiente(); + } + $rs->Cerrar(); + } else { + $errors = -1; + } + return($errors); +} + ?> diff --git a/admin/WebConsole/index.php b/admin/WebConsole/index.php index 96f3abbb..d574c106 100644 --- a/admin/WebConsole/index.php +++ b/admin/WebConsole/index.php @@ -14,11 +14,6 @@ if(isset($_SESSION)){ // Si existe algua sesi session_unset(); // Elimina variables session_destroy(); // Destruye sesin } -# Cambiar a HTTPS -if (empty ($_SERVER["HTTPS"])) { - header ("Location: https://".$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"]); - exit (0); -} // Cargar configuracin. include_once("controlacceso.php"); @@ -42,8 +37,7 @@ if (!$cmd) die($TbMsg["ACCESS_ERROR"]); $rs=new Recordset; -// $cmd->texto="SELECT * FROM centros WHERE idcentro='$idc'"; - $cmd->texto="SELECT * FROM centros "; + $cmd->texto="SELECT * FROM centros"; $rs->Comando=&$cmd; if (!$rs->Abrir()) return(false); // Error al abrir recordset $rs->Primero(); @@ -115,13 +109,13 @@ function PulsaEnter(oEvento){

-

-

-

-

-

-

- +
+
+
+
+
+
+
@@ -130,7 +124,7 @@ function PulsaEnter(oEvento){ // Aadir versin y URL al proyecto. $versionfile="../doc/VERSION.txt"; if (file_exists ($versionfile)) { - echo ''; + echo ''; include ($versionfile); echo ''; } diff --git a/admin/WebConsole/jscripts/aula.js b/admin/WebConsole/jscripts/aula.js index f34c01ba..cc8f03d7 100644 --- a/admin/WebConsole/jscripts/aula.js +++ b/admin/WebConsole/jscripts/aula.js @@ -111,43 +111,32 @@ function soIMG(so) var MimgOrdenador=""; switch(so){ case 'INI': - MimgOrdenador="ordenador_INI.gif"; // Iniciando cliente + MimgOrdenador="ordenador_INI.png"; // Iniciando cliente break; case 'BSY': - MimgOrdenador="ordenador_BSY.gif"; // Cliente ocupado + MimgOrdenador="ordenador_BSY.png"; // Cliente ocupado break; case 'OPG': - MimgOrdenador="ordenador_OPG.gif"; // Cliente OpenGnSys - break; - case 'WS2': - MimgOrdenador="ordenador_WS2.gif"; // Windows Server 2003 - break; - case 'W2K': - MimgOrdenador="ordenador_W2K.gif"; // Windows 2000 + MimgOrdenador="ordenador_OPG.png"; // Cliente OpenGnsys break; + case 'WIN': case 'WXP': - MimgOrdenador="ordenador_WXP.gif"; // Windows XP - break; - case 'WNT': - MimgOrdenador="ordenador_WNT.gif"; // Windows NT + MimgOrdenador="ordenador_WIN.png"; // Windows break; - case 'W95': - MimgOrdenador="ordenador_W95.gif"; // Windows 95 + case 'WINS': + MimgOrdenador="ordenador_WINS.png"; // Sesión Windows break; - case 'W98': - MimgOrdenador="ordenador_W98.gif"; // Windows 98 - break; - case 'WML': - MimgOrdenador="ordenador_WML.gif"; // Windows Millenium + case 'LNX': + MimgOrdenador="ordenador_LNX.png"; // Linux break; - case 'WIN': - MimgOrdenador="ordenador_WXP.gif"; // Windows + case 'LNXS': + MimgOrdenador="ordenador_LNXS.png"; // Sesión Linux break; - case 'LNX': - MimgOrdenador="ordenador_LNX.gif"; // Linux + case 'OSX': + MimgOrdenador="ordenador_OSX.png"; // macOS break; default: - MimgOrdenador="ordenador_OFF.gif"; // Apagado + MimgOrdenador="ordenador_OFF.png"; // Apagado break; } return(MimgOrdenador); diff --git a/admin/WebConsole/jscripts/aulas.js b/admin/WebConsole/jscripts/aulas.js index 254e0ac0..33230e8c 100644 --- a/admin/WebConsole/jscripts/aulas.js +++ b/admin/WebConsole/jscripts/aulas.js @@ -33,10 +33,11 @@ function colocar_ordenador(swsufijo){ var sufijonodo=currentNodo.toma_sufijo() var identificador_ordenador=corte_currentNodo.toma_identificador() var swsf=parseInt(swsufijo) + var colo='s'; if (swsf==0) // El ordenador se mueve a un grupo de ordenadores - var prm="opcion="+op_movida+"&grupoid="+identificador+"&idordenador="+identificador_ordenador + var prm="opcion="+op_movida+"&grupoid="+identificador+"&idordenador="+identificador_ordenador+"&coloc="+colo else // El ordenador se mueve a un aula - var prm="opcion="+op_movida+"&idaula="+identificador+"&idordenador="+identificador_ordenador + var prm="opcion="+op_movida+"&idaula="+identificador+"&idordenador="+identificador_ordenador+"&coloc="+colo var wurl="../gestores/gestor_ordenadores.php"; CallPage(wurl,prm,"retornoColocar","POST"); diff --git a/admin/WebConsole/jscripts/comunes.js b/admin/WebConsole/jscripts/comunes.js index 5a87c0c2..f11bedd5 100644 --- a/admin/WebConsole/jscripts/comunes.js +++ b/admin/WebConsole/jscripts/comunes.js @@ -175,6 +175,7 @@ function insertar(l,t,w,h,pages,swi,idu){ function resultado_insertar(resul,descrierror,nwid,tablanodo){ if (!resul){ alert(descrierror); + return; } InsertaNodo(currentNodo,tablanodo); alert(CTbMsg[4]); diff --git a/admin/WebConsole/jscripts/propiedades_aulas.js b/admin/WebConsole/jscripts/propiedades_aulas.js index dd8502fe..8dda9478 100644 --- a/admin/WebConsole/jscripts/propiedades_aulas.js +++ b/admin/WebConsole/jscripts/propiedades_aulas.js @@ -123,6 +123,7 @@ function comprobar_datos(){ validate (form.comentarios, validate_text, 18) && validate (form.router, validate_ipadress_notnull, 4) && validate (form.netmask, validate_ipadress_notnull, 5) && + validate (form.ntp, validate_ipadress, 19) && validate (form.dns, validate_ipadress, 12) && validate (form.proxy, validate_url, 13) && validate (form.modp2p, validate_notnull, 6) && diff --git a/admin/WebConsole/jscripts/propiedades_centros.js b/admin/WebConsole/jscripts/propiedades_centros.js index 763e6906..d2695fd2 100644 --- a/admin/WebConsole/jscripts/propiedades_centros.js +++ b/admin/WebConsole/jscripts/propiedades_centros.js @@ -74,10 +74,16 @@ function confirmar(op){ // Comprobar_datos //________________________________________________________________________________________________________ function comprobar_datos(){ - if (document.fdatos.nombrecentro==""){ - alert(TbMsg[0]) - document.forms.fdatos.nombrecentro.focus() - return(false) - } - return(true); + function validate (field, validator, msgi) { + if (!validator (field.value)) { + alert(TbMsg[msgi]); + validation_highlight (field); + return false; + } + return true; + } + + return validate (fdatos.nombrecentro, validate_text_notnull,0) && + validate (fdatos.comentarios, validate_text, 1) && + validate (fdatos.directorio, validate_text, 2) } diff --git a/admin/WebConsole/jscripts/propiedades_entidades.js b/admin/WebConsole/jscripts/propiedades_entidades.js index f3c4494f..12e9cf39 100644 --- a/admin/WebConsole/jscripts/propiedades_entidades.js +++ b/admin/WebConsole/jscripts/propiedades_entidades.js @@ -69,15 +69,29 @@ function confirmar(op){ } document.fdatos.submit(); } +//________________________________________________________________________________________________________ +// Mensaje_ogunit() +//________________________________________________________________________________________________________ +function mensaje_ogunit() { + alert (TbMsg['PXE']); +} + //________________________________________________________________________________________________________ // // Comprobar_datos //________________________________________________________________________________________________________ function comprobar_datos(){ - if (document.fdatos.nombreentidad==""){ - alert(TbMsg[0]) - document.forms.fdatos.nombreentidad.focus() - return(false) + function validate (field, validator, msgi) { + if (!validator (field.value)) { + alert(TbMsg[msgi]); + validation_highlight (field); + return false; + } + return true; } - return(true); + + + + return validate (fdatos.nombreentidad, validate_text_notnull,0) && + validate (fdatos.comentarios, validate_text, 1) } diff --git a/admin/WebConsole/jscripts/propiedades_imagenes.js b/admin/WebConsole/jscripts/propiedades_imagenes.js index f8655a22..59a09baf 100644 --- a/admin/WebConsole/jscripts/propiedades_imagenes.js +++ b/admin/WebConsole/jscripts/propiedades_imagenes.js @@ -88,7 +88,6 @@ function comprobar_datos(){ return validate (form.nombreca, validate_nameimagefile, 3) && validate (form.nombreca, validate_notnull, 3) && validate (form.descripcion, validate_notnull, 0) && - validate (form.codpar, validate_notnull, 5) && validate (form.idrepositorio, validate_notnull, 6); } else{ diff --git a/admin/WebConsole/jscripts/propiedades_ordenadores.js b/admin/WebConsole/jscripts/propiedades_ordenadores.js index 21482f8f..f42c309f 100644 --- a/admin/WebConsole/jscripts/propiedades_ordenadores.js +++ b/admin/WebConsole/jscripts/propiedades_ordenadores.js @@ -92,8 +92,10 @@ function comprobar_datos(){ return(false); } - return validate (form.nombreordenador, validate_notnull, 0) && + return validate (form.nombreordenador, validate_notspace, 0) && + validate (form.nombreordenador, validate_text_notnull, 0) && validate (form.ip, validate_ipadress_notnull, 1) && validate (form.mac, validate_macaddress_notnull, 2) && + validate (form.numserie, validate_alphanum, 3) && validate (form.idrepositorio, validate_number_notnull, 5) ; } diff --git a/admin/WebConsole/jscripts/propiedades_usuarios.js b/admin/WebConsole/jscripts/propiedades_usuarios.js index d48cc031..f31a2872 100644 --- a/admin/WebConsole/jscripts/propiedades_usuarios.js +++ b/admin/WebConsole/jscripts/propiedades_usuarios.js @@ -79,8 +79,14 @@ function comprobar_datos(){ document.forms.fdatos.usuario.focus() return(false) } - if (document.fdatos.pasguor.value==""){ - alert(TbMsg[1]) + if (document.fdatos.pasguor.value.length < 8){ + alert(TbMsg[6]) + document.forms.fdatos.pasguor.focus() + return(false) + } + + if (document.fdatos.pasguor.value != document.fdatos.confirmarpasguor.value){ + alert(TbMsg[5]) document.forms.fdatos.pasguor.focus() return(false) } diff --git a/admin/WebConsole/jscripts/validators.js b/admin/WebConsole/jscripts/validators.js index 7c031f8b..5dacf1cb 100644 --- a/admin/WebConsole/jscripts/validators.js +++ b/admin/WebConsole/jscripts/validators.js @@ -94,6 +94,9 @@ function validate_text(value) { function validate_text_notnull(value) { return validate_text(value) && validate_notnull(value); } +function validate_notspace(value) { + return ! validate_expr(value, /.*[ ]/); +} function validation_highlight(field) { field.focus(); diff --git a/admin/WebConsole/menus/examplemenu.html b/admin/WebConsole/menus/examplemenu.html deleted file mode 100644 index 8ca86f4f..00000000 --- a/admin/WebConsole/menus/examplemenu.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - Init menu OpenGnSys client - - - - - - - - -

Option Menu

-
-
Init session Windows.
-
Normal boot Windows without changes.
-
Install Windows.
-
The installation process takes a few minutes.
-
- -
-
Restore Windows Image.
-
Restore Windows Image using synchronization.
-
- -
-
Init session GNU/Linux.
-
Normal boot GNU/Linux without changes.
-
Install GNU/Linux.
-
The installation process takes a few minutes.
-
- -
-
Power-off.
-
Power-off computer.
-
Reboot.
-
Reboot computer.
-
- - diff --git a/admin/WebConsole/menus/examplemenu.php b/admin/WebConsole/menus/examplemenu.php new file mode 100644 index 00000000..b04b3dd0 --- /dev/null +++ b/admin/WebConsole/menus/examplemenu.php @@ -0,0 +1,94 @@ + + + + + + Init menu for OpenGnsys clients + + + + + + + + +

Option Menu

+
+
Init session Windows.
+
Normal boot Windows without changes.
+
Install Windows.
+
The installation process takes a few minutes.
+
+ + + +
+
Init session GNU/Linux.
+
Normal boot GNU/Linux without changes.
+
Install GNU/Linux.
+
The installation process takes a few minutes.
+
+ +
+
Power-off.
+
Power-off computer.
+
Reboot.
+
Reboot computer.
+
+ + + + + + diff --git a/admin/WebConsole/menus/menuejemplo.html b/admin/WebConsole/menus/menuejemplo.html deleted file mode 100644 index 57a52a22..00000000 --- a/admin/WebConsole/menus/menuejemplo.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - Menú de inicio de los equipos OpenGnSys - - - - - - - -

Menú de opciones

- -
-
[1] Arrancar Windows.
-
Arranque normal de Windows sin modificaciones.
-
[2] Instalar Windows.
-
El proceso de instalación tardará unos minutos.
-
- - - -
-
[3] Arrancar GNU/Linux.
-
Arranque normal de GNU/Linux sin modificaciones.
- -
[4] Instalar GNU/Linux.
-
El proceso de instalación tardará unos minutos.
-
- -
-
[0] Apagar.
-
Apagar el ordenador.
- -
[6] Reiniciar.
-
Reiniciar el ordenador.
-
- - - - diff --git a/admin/WebConsole/menus/menuejemplo.php b/admin/WebConsole/menus/menuejemplo.php new file mode 100644 index 00000000..b3fcd175 --- /dev/null +++ b/admin/WebConsole/menus/menuejemplo.php @@ -0,0 +1,97 @@ + + + + + + Menú de inicio de los equipos OpenGnsys + + + + + + + +

Menú de opciones

+ +
+
[1] Arrancar Windows.
+
Arranque normal de Windows sin modificaciones.
+
[2] Instalar Windows.
+
El proceso de instalación tardará unos minutos.
+
+ + + +
+
[3] Arrancar GNU/Linux.
+
Arranque normal de GNU/Linux sin modificaciones.
+ +
[4] Instalar GNU/Linux.
+
El proceso de instalación tardará unos minutos.
+
+ +
+
[0] Apagar.
+
Apagar el ordenador.
+ +
[6] Reiniciar.
+
Reiniciar el ordenador.
+
+ + + + + + + diff --git a/admin/WebConsole/menus/privatemenu.php b/admin/WebConsole/menus/privatemenu.php new file mode 100644 index 00000000..268889d9 --- /dev/null +++ b/admin/WebConsole/menus/privatemenu.php @@ -0,0 +1,46 @@ + + + + + + + Private menu for OpenGnsys clients + + + + +

Option Menu

+ +
+

Link to return to the public zone

+ Return +
+ + diff --git a/admin/WebConsole/pagerror.php b/admin/WebConsole/pagerror.php index cd19cc4f..71aee05b 100644 --- a/admin/WebConsole/pagerror.php +++ b/admin/WebConsole/pagerror.php @@ -1,4 +1,4 @@ - - '.chr(13); echo ' var o=window.top;'.chr(13); echo ' var ao=o.parent;'.chr(13); diff --git a/admin/WebConsole/principal/acciones.php b/admin/WebConsole/principal/acciones.php index 72f0be9f..9b86e2d4 100644 --- a/admin/WebConsole/principal/acciones.php +++ b/admin/WebConsole/principal/acciones.php @@ -1,4 +1,4 @@ - - '?> - '?> + '?> + '?> -CreaArbolVistaXML(); // Crea árbol (HTML) a partir del XML $flotante=new MenuContextual(); // Crea objeto MenuContextual @@ -74,7 +74,7 @@ echo $flotante->CreaMenuContextual($XMLcontextual); ?> - -

OpenGnSys

+

OpenGnsys

 

 

 

-

OpenGnSys

+

OpenGnsys

Años
diff --git a/admin/WebConsole/idiomas/php/cat/comandos/conmutar_cat.php b/admin/WebConsole/idiomas/php/cat/comandos/conmutar_cat.php index 5be32591..9c171e04 100644 --- a/admin/WebConsole/idiomas/php/cat/comandos/conmutar_cat.php +++ b/admin/WebConsole/idiomas/php/cat/comandos/conmutar_cat.php @@ -1,4 +1,4 @@ -\n + * El modo usuario sólo es válido si está iniciada la sesión en modo gráfico.
\n + * El lenguaje del script a enviar debe corresponder al estado de cliente.
\n + * Para Windows hay que escapar las contrabarras."; $TbMsg["WDI10"]='Modificar código'; $TbMsg["WDI11"]='Asistent de Desplegament de la imatge'; diff --git a/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagencache_cat.php b/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagencache_cat.php index 5280c31a..68e70272 100644 --- a/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagencache_cat.php +++ b/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagencache_cat.php @@ -5,11 +5,11 @@ // Idioma: Catal� //________________________________________________________________________________________________________ if (empty ($TbMsg)) $TbMsg=array(); - $TbMsg[0]='Creació d\'Imatge'; - $TbMsg[1]='Característiques de l\'ordinador'; - $TbMsg[2]='Nom'; - $TbMsg[3]='Direcció IP'; - $TbMsg[4]='Direcció MAC'; + $TbMsg[0]='Unidad Organizativa'; + $TbMsg[1]='Grupo de aulas'; + $TbMsg[2]='Aula'; + $TbMsg[3]='Grupo de ordenadores'; + $TbMsg[4]='Ordenador'; $TbMsg[5]='Eliminar Imatge de la Cache en Client'; $TbMsg[6]='Dades a subministrar'; $TbMsg[7]='Imátges Disponibles'; diff --git a/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagenrepo_cat.php b/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagenrepo_cat.php index 4a179f64..a46d95cc 100644 --- a/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagenrepo_cat.php +++ b/admin/WebConsole/idiomas/php/cat/comandos/eliminarimagenrepo_cat.php @@ -1,4 +1,4 @@ - \ No newline at end of file + $TbMsg[33]='AVISO: La imagen está situada en un directorio que no corresponde a la unidad organizativa.'; +?> diff --git a/admin/WebConsole/idiomas/php/cat/comandos/enviarmensaje_cat.php b/admin/WebConsole/idiomas/php/cat/comandos/enviarmensaje_cat.php new file mode 100644 index 00000000..b6f3d68d --- /dev/null +++ b/admin/WebConsole/idiomas/php/cat/comandos/enviarmensaje_cat.php @@ -0,0 +1,23 @@ +y tengan instalado en nuevo agente de OpenGnsys."; + $TbMsg["OPTION"]="AVISO: El nuevo agente, en esta versión, no permite utilizar la cola de acciones."; +?> + diff --git a/admin/WebConsole/idiomas/php/cat/comandos/gestor_ejecutarscripts_cat.php b/admin/WebConsole/idiomas/php/cat/comandos/gestor_ejecutarscripts_cat.php index 2c1873aa..372a2d47 100644 --- a/admin/WebConsole/idiomas/php/cat/comandos/gestor_ejecutarscripts_cat.php +++ b/admin/WebConsole/idiomas/php/cat/comandos/gestor_ejecutarscripts_cat.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/cat/ecoremoto_cat.php b/admin/WebConsole/idiomas/php/cat/ecoremoto_cat.php index f14c1f7d..bf04e179 100644 --- a/admin/WebConsole/idiomas/php/cat/ecoremoto_cat.php +++ b/admin/WebConsole/idiomas/php/cat/ecoremoto_cat.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/cat/gestor_ordenadores_cat.php b/admin/WebConsole/idiomas/php/cat/gestor_ordenadores_cat.php new file mode 100644 index 00000000..3eebd1a9 --- /dev/null +++ b/admin/WebConsole/idiomas/php/cat/gestor_ordenadores_cat.php @@ -0,0 +1,10 @@ + + diff --git a/admin/WebConsole/idiomas/php/cat/hardwares_cat.php b/admin/WebConsole/idiomas/php/cat/hardwares_cat.php index 34c7dec6..d52d7a82 100644 --- a/admin/WebConsole/idiomas/php/cat/hardwares_cat.php +++ b/admin/WebConsole/idiomas/php/cat/hardwares_cat.php @@ -1,4 +1,4 @@ -En otro caso el protocolo es RSYNC.'; +$TbMsg["WARN_DIFFIMAGE"]='Hay una nueva versió de la imagen (se muestra la diferencia de revisiones).'; +$TbMsg["WARN_DIFFDISKSIZE"]='ATENCIÓN: no se pueden particionar grupos de ordenadores con distinto tamaño de disco.
Marcar la opción de "Desagrupar por tamaño de partición" y pulsar "Aceptar" en el menú superior para aplicar esta operación adecuadamente.'; ?> diff --git a/admin/WebConsole/idiomas/php/cat/procedimientoscomandos_cat.php b/admin/WebConsole/idiomas/php/cat/procedimientoscomandos_cat.php index 5adf0672..fff32291 100644 --- a/admin/WebConsole/idiomas/php/cat/procedimientoscomandos_cat.php +++ b/admin/WebConsole/idiomas/php/cat/procedimientoscomandos_cat.php @@ -1,4 +1,4 @@ -(opcional)"; $TbMsg['PROP_DNSIP']="IP Servidor DNS (opcional)"; $TbMsg['PROP_PROXYURL']="URL Servidor Proxy (opcional)"; +$TbMsg['COMM_DEFTIMEZONE']="zona horaria por defecto"; +$TbMsg['PROP_REMOTEACCESS']="Acceso remoto"; +$TbMsg['COMM_REMOTEACCESS']="permitir gestión de acceso remoto a los ordenadores"; +$TbMsg['COMM_DEFOGLIVE']="Assignat per l'administrador"; ?> diff --git a/admin/WebConsole/idiomas/php/cat/propiedades_centros_cat.php b/admin/WebConsole/idiomas/php/cat/propiedades_centros_cat.php index f081ecd6..26d81b96 100644 --- a/admin/WebConsole/idiomas/php/cat/propiedades_centros_cat.php +++ b/admin/WebConsole/idiomas/php/cat/propiedades_centros_cat.php @@ -1,4 +1,4 @@ -/opt/opengnsys/images
debe contener un subdirectorio llamado como el directorio indicado."; ?> - \ No newline at end of file + diff --git a/admin/WebConsole/idiomas/php/cat/propiedades_componentehardwares_cat.php b/admin/WebConsole/idiomas/php/cat/propiedades_componentehardwares_cat.php index e361b8f1..d32b2e4c 100644 --- a/admin/WebConsole/idiomas/php/cat/propiedades_componentehardwares_cat.php +++ b/admin/WebConsole/idiomas/php/cat/propiedades_componentehardwares_cat.php @@ -1,4 +1,4 @@ - - \ No newline at end of file + diff --git a/admin/WebConsole/idiomas/php/cat/propiedades_entornos_cat.php b/admin/WebConsole/idiomas/php/cat/propiedades_entornos_cat.php index 96ac190b..42ae5d85 100644 --- a/admin/WebConsole/idiomas/php/cat/propiedades_entornos_cat.php +++ b/admin/WebConsole/idiomas/php/cat/propiedades_entornos_cat.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/cat/propiedades_menus_cat.php b/admin/WebConsole/idiomas/php/cat/propiedades_menus_cat.php index c3c72b9d..a6fbbb73 100644 --- a/admin/WebConsole/idiomas/php/cat/propiedades_menus_cat.php +++ b/admin/WebConsole/idiomas/php/cat/propiedades_menus_cat.php @@ -22,4 +22,5 @@ $TbMsg[14]="Men $TbMsg[15]="URL men personalizado"; $TbMsg[17]="Resoluci de pantalla"; $TbMsg[18]="Imagen de fondo"; +$TbMsg["PROP_DEFAULT"]="Detectada por defecto"; ?> diff --git a/admin/WebConsole/idiomas/php/cat/propiedades_ordenadores_cat.php b/admin/WebConsole/idiomas/php/cat/propiedades_ordenadores_cat.php index 4baf492e..2cd27321 100644 --- a/admin/WebConsole/idiomas/php/cat/propiedades_ordenadores_cat.php +++ b/admin/WebConsole/idiomas/php/cat/propiedades_ordenadores_cat.php @@ -2,28 +2,34 @@ //____________________________________________________________ // // Fitxer d'idiomes php: propiedades_ordenadores_cat.php -// Idioma: Catal +// Idioma: Catal� //____________________________________________________________ -$TbMsg=array(); -$TbMsg[0]="Sense Opci"; +if (empty ($TbMsg)) $TbMsg=array(); +$TbMsg[0]="Sense Opci�"; $TbMsg[1]="Afegir"; $TbMsg[2]="Modificar"; $TbMsg[3]="Eliminar"; -$TbMsg[4]="Gesti Ordinadors"; +$TbMsg[4]="Gesti� Ordinadors"; $TbMsg[5]="Nom"; -$TbMsg[6]="Direcci IP"; -$TbMsg[7]="Direcci MAC"; +$TbMsg[6]="Direcci� IP"; +$TbMsg[7]="Direcci� MAC"; $TbMsg[8]="Perfil Hardware"; $TbMsg[9]="Autoexec"; $TbMsg[10]="Repositori"; -$TbMsg[11]="Men"; -$TbMsg[12]="Grandria Cach"; +$TbMsg[11]="Men�"; +$TbMsg[12]="Grand�ria Cach�"; $TbMsg[13]="Interficie de Xarxa"; $TbMsg[14]="Driver de Xarxa"; +// AGP +$TbMsg[18]="ogLive"; $TbMsg[509]="Foto ordinador"; $TbMsg[5091]="Afegir foto"; $TbMsg[5092]="Veure fotos"; -$TbMsg[495]="Data/Cach"; -$TbMsg[4951]="Cach lliure"; +$TbMsg[495]="Data/Cach�"; +$TbMsg[4951]="Cach� lliure"; +// AGP +$TbMsg["PROP_SERIALNO"]="Nº de serie"; +$TbMsg["WARN_NOTDETECTED"]="(no detectado)"; +$TbMsg['COMM_DEFOGLIVE']="Assignat per l'administrador"; ?> diff --git a/admin/WebConsole/idiomas/php/cat/propiedades_ordenadorestandar_cat.php b/admin/WebConsole/idiomas/php/cat/propiedades_ordenadorestandar_cat.php index 485b3a62..0883949f 100644 --- a/admin/WebConsole/idiomas/php/cat/propiedades_ordenadorestandar_cat.php +++ b/admin/WebConsole/idiomas/php/cat/propiedades_ordenadorestandar_cat.php @@ -1,4 +1,4 @@ -Revise la clave de acceso (campo Api Token debe coincidir con su valor en fichero "ogAdmRepo.cfg")'; +$TbMsg[17]='Api Token'; +$TbMsg['MSG_CONTENT']='Contenido'; +$TbMsg['MSG_IMAGE']='Imatge'; +$TbMsg['MSG_TYPE']='Tipo'; +$TbMsg['MSG_SIZE']='Tamaño'; +$TbMsg['MSG_MODIFIED']='Modificado'; +$TbMsg['MSG_PERMISSIONS']='Permisos'; ?> diff --git a/admin/WebConsole/idiomas/php/cat/propiedades_reservas_cat.php b/admin/WebConsole/idiomas/php/cat/propiedades_reservas_cat.php index bc739ee6..346d0b6c 100644 --- a/admin/WebConsole/idiomas/php/cat/propiedades_reservas_cat.php +++ b/admin/WebConsole/idiomas/php/cat/propiedades_reservas_cat.php @@ -1,4 +1,4 @@ -"; $TbMsg[15]="creat en el procs d'installaci,

"; -$TbMsg[16]=" -premi aqu
"; -$TbMsg[17]="http://opengnsys.es/wiki/ModificarUsuarios"; -?> \ No newline at end of file +$TbMsg[16]="premi aqu
"; +$TbMsg[17]="https://opengnsys.es/trac/wiki/ModificarUsuarios"; +$TbMsg[18]="Confirmar password"; +$TbMsg['APIKEY']="API key"; +$TbMsg['NEWAPIKEY']="La API key se generar automticamente al insertar el usuario."; +?> diff --git a/admin/WebConsole/idiomas/php/cat/purgar_cat.php b/admin/WebConsole/idiomas/php/cat/purgar_cat.php index 4b87974d..792d8700 100644 --- a/admin/WebConsole/idiomas/php/cat/purgar_cat.php +++ b/admin/WebConsole/idiomas/php/cat/purgar_cat.php @@ -1,4 +1,4 @@ - + diff --git a/admin/WebConsole/idiomas/php/eng/acceso_eng.php b/admin/WebConsole/idiomas/php/eng/acceso_eng.php index 05ccb65f..aab35ee9 100644 --- a/admin/WebConsole/idiomas/php/eng/acceso_eng.php +++ b/admin/WebConsole/idiomas/php/eng/acceso_eng.php @@ -1,4 +1,4 @@ - (Open Genesis) Project brings together the combined efforts of several Spanish Public Universities. OpenGnSys provide a number of free and open tools for managing and deploying computers. These tools supplies a complete, versatile and intuitive sytem. This system allows the arrangement, installation and deployment of different operating systems.'; -$TbMsg["LICENSE"]='OpenGnSys is a Free Software project. As such, all code is licensed under '; +$TbMsg["DESCRIPTION"]='OpenGnsys (Open Genesis) Project brings together the combined efforts of several Spanish Public Universities. OpenGnsys provide a number of free and open tools for managing and deploying computers. These tools supplies a complete, versatile and intuitive sytem. This system allows the arrangement, installation and deployment of different operating systems.'; +$TbMsg["LICENSE"]='OpenGnsys is a Free Software project. As such, all code is licensed under '; $TbMsg["LINK"]='Web project:'; $TbMsg["CHANGE"]='Changes in: '; -$TbMsg["MANUAL"]='Manual OpenGnSys '; +$TbMsg["MANUAL"]='Manual OpenGnsys '; ?> diff --git a/admin/WebConsole/idiomas/php/eng/actualizar_eng.php b/admin/WebConsole/idiomas/php/eng/actualizar_eng.php index 7abf81c8..7405b81d 100644 --- a/admin/WebConsole/idiomas/php/eng/actualizar_eng.php +++ b/admin/WebConsole/idiomas/php/eng/actualizar_eng.php @@ -1,4 +1,4 @@ -Un menú personalizado se define introduciendo la URL de la página HTML que lo define.
Un menú automático se compone a partir de los procedimientos definidos.'; +$TbMsg["WARN_GPT"]='AVISO: Para tabla de particiones GPT es necesario que la primera partición sea tipo EFI
y se recomienda un tamaño en torno a 512Mb.'; +$TbMsg["WARN_SCHEDULER"]='WARNING: turn on database event scheduler to enable this property.'; +$TbMsg["WARN_SOURCE_PATH"]='WARNING: The route origin is only used in directory-type synchronized.'; ?> diff --git a/admin/WebConsole/idiomas/php/eng/barramenu_eng.php b/admin/WebConsole/idiomas/php/eng/barramenu_eng.php index c418be9e..535a38df 100644 --- a/admin/WebConsole/idiomas/php/eng/barramenu_eng.php +++ b/admin/WebConsole/idiomas/php/eng/barramenu_eng.php @@ -1,4 +1,4 @@ -semanas[5]=array ("5",0x10); $this->semanas[6]=array ("Last",0x20); - $this->numero_annos[1]=array ("2010",0x01); // tamao 1 bytes - $this->numero_annos[2]=array ("2011",0x02); - $this->numero_annos[3]=array ("2012",0x04); - $this->numero_annos[4]=array ("2013",0x08); - $this->numero_annos[5]=array ("2014",0x10); - $this->numero_annos[6]=array ("2015",0x20); - $this->numero_annos[7]=array ("2016",0x40); - $this->numero_annos[8]=array ("2017",0x80); + $this->numero_annos[2010]=0x0001; // tamao 2 bytes + $this->numero_annos[2011]=0x0002; + $this->numero_annos[2012]=0x0004; + $this->numero_annos[2013]=0x0008; + $this->numero_annos[2014]=0x0010; + $this->numero_annos[2015]=0x0020; + $this->numero_annos[2016]=0x0040; + $this->numero_annos[2017]=0x0080; + $this->numero_annos[2018]=0x0100; + $this->numero_annos[2019]=0x0200; + $this->numero_annos[2020]=0x0400; + $this->numero_annos[2021]=0x0800; + $this->numero_annos[2022]=0x1000; + $this->numero_annos[2023]=0x2000; + $this->numero_annos[2024]=0x4000; + $this->numero_annos[2025]=0x8000; $this->numero_dias[1]=0x00000001; // tamao 4 bytes $this->numero_dias[2]=0x00000002; @@ -211,7 +219,7 @@ class Almanaque{ $HTML_calendario=''.chr(13); $HTML_calendario.=''.chr(13); $HTML_calendario.=''.chr(13); // Literal aos - for ($i=1;$i<9;$i++){ + for ($i=$ano_desde; $i<=ano_hasta; ){ $HTML_calendario.=''.chr(13); } $HTML_calendario.='
Years
'.$this->numero_annos[$i][0].'
'.chr(13); diff --git a/admin/WebConsole/idiomas/php/eng/clases/Calendario_eng.php b/admin/WebConsole/idiomas/php/eng/clases/Calendario_eng.php index e182f2ae..29d001d2 100644 --- a/admin/WebConsole/idiomas/php/eng/clases/Calendario_eng.php +++ b/admin/WebConsole/idiomas/php/eng/clases/Calendario_eng.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/eng/comandos/conmutar_eng.php b/admin/WebConsole/idiomas/php/eng/comandos/conmutar_eng.php index 82068595..fd6f9bbc 100644 --- a/admin/WebConsole/idiomas/php/eng/comandos/conmutar_eng.php +++ b/admin/WebConsole/idiomas/php/eng/comandos/conmutar_eng.php @@ -1,4 +1,4 @@ -\n + * El modo usuario sólo es válido si está iniciada la sesión en modo gráfico.
\n + * El lenguaje del script a enviar debe corresponder al estado de cliente.
\n + * Para Windows hay que escapar las contrabarras."; $TbMsg["WDI10"]='Modificar código'; $TbMsg["WDI11"]='Deploy Image Wizard'; diff --git a/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagencache_eng.php b/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagencache_eng.php index 475bcf90..1f9e10e3 100644 --- a/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagencache_eng.php +++ b/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagencache_eng.php @@ -5,12 +5,12 @@ // Idioma: English //________________________________________________________________________________________________________ if (empty ($TbMsg)) $TbMsg=array(); - $TbMsg[0]='Generation of software profiles'; - $TbMsg[1]='Computer features'; - $TbMsg[2]='Name'; - $TbMsg[3]='IP Address'; - $TbMsg[4]='MAC Address'; - $TbMsg[5]='Image Delete Cache Client'; + $TbMsg[0]='Organizational Unit'; + $TbMsg[1]='Group of labs'; + $TbMsg[2]='Lab'; + $TbMsg[3]='Group of comuters'; + $TbMsg[4]='Computer'; + $TbMsg[5]='Delete Images from Clients Cache'; $TbMsg[6]='Environment'; $TbMsg[7]='Available Images'; $TbMsg[8]='Par'; diff --git a/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagenrepo_eng.php b/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagenrepo_eng.php index b341b96e..3f164a40 100644 --- a/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagenrepo_eng.php +++ b/admin/WebConsole/idiomas/php/eng/comandos/eliminarimagenrepo_eng.php @@ -1,4 +1,4 @@ - \ No newline at end of file + $TbMsg[33]='AVISO: La imagen está situada en un directorio que no corresponde a la unidad organizativa.' +?> diff --git a/admin/WebConsole/idiomas/php/eng/comandos/enviarmensaje_eng.php b/admin/WebConsole/idiomas/php/eng/comandos/enviarmensaje_eng.php new file mode 100644 index 00000000..2f58c7c0 --- /dev/null +++ b/admin/WebConsole/idiomas/php/eng/comandos/enviarmensaje_eng.php @@ -0,0 +1,24 @@ +y tengan instalado en nuevo agente de OpenGnsys."; + $TbMsg["OPTION"]="AVISO: El nuevo agente, en esta versión, no permite utilizar la cola de acciones."; + +?> + diff --git a/admin/WebConsole/idiomas/php/eng/comandos/gestor_ejecutarscripts_eng.php b/admin/WebConsole/idiomas/php/eng/comandos/gestor_ejecutarscripts_eng.php index 74b05d73..fc8ccdc2 100644 --- a/admin/WebConsole/idiomas/php/eng/comandos/gestor_ejecutarscripts_eng.php +++ b/admin/WebConsole/idiomas/php/eng/comandos/gestor_ejecutarscripts_eng.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/eng/ecoremoto_eng.php b/admin/WebConsole/idiomas/php/eng/ecoremoto_eng.php index 669c225c..d291a1ec 100644 --- a/admin/WebConsole/idiomas/php/eng/ecoremoto_eng.php +++ b/admin/WebConsole/idiomas/php/eng/ecoremoto_eng.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/eng/gestor_ordenadores_eng.php b/admin/WebConsole/idiomas/php/eng/gestor_ordenadores_eng.php new file mode 100644 index 00000000..df1fa293 --- /dev/null +++ b/admin/WebConsole/idiomas/php/eng/gestor_ordenadores_eng.php @@ -0,0 +1,10 @@ + + diff --git a/admin/WebConsole/idiomas/php/eng/hardwares_eng.php b/admin/WebConsole/idiomas/php/eng/hardwares_eng.php index eba4f609..9a2bf838 100644 --- a/admin/WebConsole/idiomas/php/eng/hardwares_eng.php +++ b/admin/WebConsole/idiomas/php/eng/hardwares_eng.php @@ -1,4 +1,4 @@ -En otro caso el protocolo es RSYNC.'; +$TbMsg["WARN_DIFFIMAGE"]='There is a new image version (showing revision difference).'; +$TbMsg["WARN_DIFFDISKSIZE"]='ATENTION: a group of computers with different disk sizes can not be partitioned.
Check "Ungroup by partition size" option and press "Accept" in the top menu to apply this operation properly.'; ?> diff --git a/admin/WebConsole/idiomas/php/eng/procedimientoscomandos_eng.php b/admin/WebConsole/idiomas/php/eng/procedimientoscomandos_eng.php index e9ae615f..02dc078f 100644 --- a/admin/WebConsole/idiomas/php/eng/procedimientoscomandos_eng.php +++ b/admin/WebConsole/idiomas/php/eng/procedimientoscomandos_eng.php @@ -1,4 +1,4 @@ -(optional)"; $TbMsg['PROP_DNSIP']="DNS Server IP (optional)"; $TbMsg['PROP_PROXYURL']="Proxy Server URL (optional)"; +$TbMsg['COMM_DEFTIMEZONE']="default time zone"; +$TbMsg['PROP_REMOTEACCESS']="Remote access"; +$TbMsg['COMM_REMOTEACCESS']="allow management of remote access to the computers"; +$TbMsg['COMM_DEFOGLIVE']="Assigned by administrator"; ?> diff --git a/admin/WebConsole/idiomas/php/eng/propiedades_centros_eng.php b/admin/WebConsole/idiomas/php/eng/propiedades_centros_eng.php index 75c96b60..1c2e2be7 100644 --- a/admin/WebConsole/idiomas/php/eng/propiedades_centros_eng.php +++ b/admin/WebConsole/idiomas/php/eng/propiedades_centros_eng.php @@ -1,4 +1,4 @@ -/opt/opengnsys/images
debe contener un subdirectorio llamado como el directorio indicado."; ?> diff --git a/admin/WebConsole/idiomas/php/eng/propiedades_componentehardwares_eng.php b/admin/WebConsole/idiomas/php/eng/propiedades_componentehardwares_eng.php index 93c26a47..a364c4ac 100644 --- a/admin/WebConsole/idiomas/php/eng/propiedades_componentehardwares_eng.php +++ b/admin/WebConsole/idiomas/php/eng/propiedades_componentehardwares_eng.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/eng/propiedades_entornos_eng.php b/admin/WebConsole/idiomas/php/eng/propiedades_entornos_eng.php index 65819325..1ad82b4a 100644 --- a/admin/WebConsole/idiomas/php/eng/propiedades_entornos_eng.php +++ b/admin/WebConsole/idiomas/php/eng/propiedades_entornos_eng.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/eng/propiedades_menus_eng.php b/admin/WebConsole/idiomas/php/eng/propiedades_menus_eng.php index f1bf3262..a408378f 100644 --- a/admin/WebConsole/idiomas/php/eng/propiedades_menus_eng.php +++ b/admin/WebConsole/idiomas/php/eng/propiedades_menus_eng.php @@ -23,4 +23,5 @@ $TbMsg[14]="Double menu"; $TbMsg[15]="URL menú personalizado"; $TbMsg[17]="Screen resolution"; $TbMsg[18]="Background image"; +$TbMsg["PROP_DEFAULT"]="Detected by default"; ?> diff --git a/admin/WebConsole/idiomas/php/eng/propiedades_ordenadores_eng.php b/admin/WebConsole/idiomas/php/eng/propiedades_ordenadores_eng.php index 8b5541be..8b966214 100644 --- a/admin/WebConsole/idiomas/php/eng/propiedades_ordenadores_eng.php +++ b/admin/WebConsole/idiomas/php/eng/propiedades_ordenadores_eng.php @@ -4,7 +4,7 @@ // Php language file: propiedades_ordenadores_eng.php // Language: English //_________________________________________________________ -$TbMsg=array(); +if (empty ($TbMsg)) $TbMsg=array(); $TbMsg[0]="No Option"; $TbMsg[1]="Insert"; $TbMsg[2]="Modify"; @@ -19,11 +19,16 @@ $TbMsg[10]="Repository"; $TbMsg[11]="Menu"; $TbMsg[12]="Cache size"; $TbMsg[13]="Network interface"; -$TbMsg[14]="Network driver"; +// AGP +$TbMsg[18]="ogLive"; $TbMsg[509]="Computer Photo"; $TbMsg[5091]="Insert Photo"; $TbMsg[5092]="View Images"; $TbMsg[495]="Content Cache"; $TbMsg[4951]="Cache Free"; +// AGP +$TbMsg["PROP_SERIALNO"]="Serial No."; +$TbMsg["WARN_NOTDETECTED"]="(does not detected)"; +$TbMsg['COMM_DEFOGLIVE']="Assigned by administrator"; ?> diff --git a/admin/WebConsole/idiomas/php/eng/propiedades_ordenadorestandar_eng.php b/admin/WebConsole/idiomas/php/eng/propiedades_ordenadorestandar_eng.php index d038f2de..322d0a02 100644 --- a/admin/WebConsole/idiomas/php/eng/propiedades_ordenadorestandar_eng.php +++ b/admin/WebConsole/idiomas/php/eng/propiedades_ordenadorestandar_eng.php @@ -1,4 +1,4 @@ -Check access key (Api Token field must match its value in "ogAdmRepo" file)'; +$TbMsg[17]='Api Token'; +$TbMsg['MSG_CONTENT']='Content'; +$TbMsg['MSG_IMAGE']='Image'; +$TbMsg['MSG_TYPE']='Type'; +$TbMsg['MSG_SIZE']='Size'; +$TbMsg['MSG_MODIFIED']='Modified'; +$TbMsg['MSG_PERMISSIONS']='Permissions'; ?> diff --git a/admin/WebConsole/idiomas/php/eng/propiedades_reservas_eng.php b/admin/WebConsole/idiomas/php/eng/propiedades_reservas_eng.php index 42b33988..abe434f7 100644 --- a/admin/WebConsole/idiomas/php/eng/propiedades_reservas_eng.php +++ b/admin/WebConsole/idiomas/php/eng/propiedades_reservas_eng.php @@ -1,4 +1,4 @@ -"; $TbMsg[15]="created in the installation,

"; $TbMsg[16]="click here
"; -$TbMsg[17]="http://opengnsys.es/wiki/ModificarUsuarios"; -?> \ No newline at end of file +$TbMsg[17]="https://opengnsys.es/trac/wiki/ModificarUsuarios"; +$TbMsg['APIKEY']="API key"; +$TbMsg['NEWAPIKEY']="La API key se generará automáticamente al insertar el usuario."; +?> diff --git a/admin/WebConsole/idiomas/php/eng/purgar_eng.php b/admin/WebConsole/idiomas/php/eng/purgar_eng.php index cb1c488f..39a6f81a 100644 --- a/admin/WebConsole/idiomas/php/eng/purgar_eng.php +++ b/admin/WebConsole/idiomas/php/eng/purgar_eng.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/esp/acceso_esp.php b/admin/WebConsole/idiomas/php/esp/acceso_esp.php index 7dcd76a3..e5d084f5 100644 --- a/admin/WebConsole/idiomas/php/esp/acceso_esp.php +++ b/admin/WebConsole/idiomas/php/esp/acceso_esp.php @@ -1,4 +1,4 @@ -(léase OpenGénesis) reúne el esfuerzo conjunto de varias Universidades Públicas Españolas, para disponer de una serie de herramientas libres y abiertas que constituyan un sistema completo, versátil e intuitivo, para la gestión y clonación de equipos. Esta aplicación permite la distribución, instalación y despliegue de distintos sistemas operativos. '; -$TbMsg["LICENSE"]='OpenGnSys es un proyecto de Software Libre, todo el código está licenciado bajo '; +$TbMsg["DESCRIPTION"]='OpenGnsys (léase OpenGénesis) reúne el esfuerzo conjunto de varias Universidades Públicas Españolas, para disponer de una serie de herramientas libres y abiertas que constituyan un sistema completo, versátil e intuitivo, para la gestión y clonación de equipos. Esta aplicación permite la distribución, instalación y despliegue de distintos sistemas operativos. '; +$TbMsg["LICENSE"]='OpenGnsys es un proyecto de Software Libre, todo el código está licenciado bajo '; $TbMsg["LINK"]='Web del proyecto: '; $TbMsg["CHANGE"]='Cambios en: '; -$TbMsg["MANUAL"]='Manual OpenGnSys '; +$TbMsg["MANUAL"]='Manual OpenGnsys '; ?> diff --git a/admin/WebConsole/idiomas/php/esp/actualizar_esp.php b/admin/WebConsole/idiomas/php/esp/actualizar_esp.php index 74517ab4..4c60f353 100644 --- a/admin/WebConsole/idiomas/php/esp/actualizar_esp.php +++ b/admin/WebConsole/idiomas/php/esp/actualizar_esp.php @@ -1,4 +1,4 @@ -Un menú personalizado se define introduciendo la URL de la página HTML que lo define.
Un menú automático se compone a partir de los procedimientos definidos.'; +$TbMsg["WARN_GPT"]='AVISO: Para tabla de particiones GPT es necesario que la primera partición sea tipo EFI
y se recomienda un tamaño en torno a 512Mb.'; +$TbMsg["WARN_SCHEDULER"]='AVISO: activar calendario de eventos de la BD para habilitar esta propiedad'; +$TbMsg["WARN_SOURCE_PATH"]='AVISO: La ruta de origen sólo se utiliza en las sincronizadas tipo directorio.'; ?> diff --git a/admin/WebConsole/idiomas/php/esp/barramenu_esp.php b/admin/WebConsole/idiomas/php/esp/barramenu_esp.php index 63c387a9..1ea51290 100644 --- a/admin/WebConsole/idiomas/php/esp/barramenu_esp.php +++ b/admin/WebConsole/idiomas/php/esp/barramenu_esp.php @@ -1,4 +1,4 @@ -semanas[5]=array ("5ª",0x10); $this->semanas[6]=array ("Última",0x20); - $this->numero_annos[1]=array ("2010",0x01); // tamaño 1 bytes - $this->numero_annos[2]=array ("2011",0x02); - $this->numero_annos[3]=array ("2012",0x04); - $this->numero_annos[4]=array ("2013",0x08); - $this->numero_annos[5]=array ("2014",0x10); - $this->numero_annos[6]=array ("2015",0x20); - $this->numero_annos[7]=array ("2016",0x40); - $this->numero_annos[8]=array ("2017",0x80); + $this->numero_annos[2010]=0x0001; // tamaño 2 bytes + $this->numero_annos[2011]=0x0002; + $this->numero_annos[2012]=0x0004; + $this->numero_annos[2013]=0x0008; + $this->numero_annos[2014]=0x0010; + $this->numero_annos[2015]=0x0020; + $this->numero_annos[2016]=0x0040; + $this->numero_annos[2017]=0x0080; + $this->numero_annos[2018]=0x0100; + $this->numero_annos[2019]=0x0200; + $this->numero_annos[2020]=0x0400; + $this->numero_annos[2021]=0x0800; + $this->numero_annos[2022]=0x1000; + $this->numero_annos[2023]=0x2000; + $this->numero_annos[2024]=0x4000; + $this->numero_annos[2025]=0x8000; $this->numero_dias[1]=0x00000001; // tamaño 4 bytes $this->numero_dias[2]=0x00000002; @@ -179,11 +187,11 @@ class Almanaque{ $HTML_calendario=''.chr(13); $HTML_calendario.=''.chr(13); $HTML_calendario.=''.chr(13); // Literal años - for ($i=1;$i<9;$i++){ - $HTML_calendario.=''.chr(13); + onclick="'.$this->onclick.'">'.$i.''.chr(13); } $HTML_calendario.='
Años
'.$this->numero_annos[$i][0].'
'.chr(13); return($HTML_calendario); diff --git a/admin/WebConsole/idiomas/php/esp/clases/Calendario_esp.php b/admin/WebConsole/idiomas/php/esp/clases/Calendario_esp.php index 91fcd2e6..bd529710 100644 --- a/admin/WebConsole/idiomas/php/esp/clases/Calendario_esp.php +++ b/admin/WebConsole/idiomas/php/esp/clases/Calendario_esp.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/esp/comandos/conmutar_esp.php b/admin/WebConsole/idiomas/php/esp/comandos/conmutar_esp.php index c34c5804..67ab7a7c 100644 --- a/admin/WebConsole/idiomas/php/esp/comandos/conmutar_esp.php +++ b/admin/WebConsole/idiomas/php/esp/comandos/conmutar_esp.php @@ -1,4 +1,4 @@ - + * El modo usuario sólo es válido si está iniciada la sesión en modo gráfico.
+ * El lenguaje del script a enviar debe corresponder al estado de cliente.
+ * Para Windows hay que escapar las contrabarras."; $TbMsg["WDI10"]='Modificar código'; $TbMsg["WDI11"]='Asistente de Despliegue de la imagen'; diff --git a/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagencache_esp.php b/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagencache_esp.php index ecb710b1..2107a4f8 100644 --- a/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagencache_esp.php +++ b/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagencache_esp.php @@ -5,11 +5,11 @@ // Idioma: Espa�ol //________________________________________________________________________________________________________ if (empty ($TbMsg)) $TbMsg=array(); - $TbMsg[0]='Creación de Imagen'; - $TbMsg[1]='Características del ordenador'; - $TbMsg[2]='Nombre'; - $TbMsg[3]='Dirección IP'; - $TbMsg[4]='Dirección MAC'; + $TbMsg[0]='Unidad Organizativa'; + $TbMsg[1]='Grupo de aulas'; + $TbMsg[2]='Aula'; + $TbMsg[3]='Grupo de ordenadores'; + $TbMsg[4]='Ordenador'; $TbMsg[5]='Eliminar Imagen de la Cache en Cliente'; $TbMsg[6]='Datos a suministrar'; $TbMsg[7]='Imágenes Disponibles'; diff --git a/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagenrepo_esp.php b/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagenrepo_esp.php index c10f5094..d63711a9 100644 --- a/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagenrepo_esp.php +++ b/admin/WebConsole/idiomas/php/esp/comandos/eliminarimagenrepo_esp.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/esp/comandos/enviarmensaje_esp.php b/admin/WebConsole/idiomas/php/esp/comandos/enviarmensaje_esp.php new file mode 100644 index 00000000..1e24f37f --- /dev/null +++ b/admin/WebConsole/idiomas/php/esp/comandos/enviarmensaje_esp.php @@ -0,0 +1,24 @@ +y tengan instalado en nuevo agente de OpenGnsys."; + $TbMsg["OPTION"]="AVISO: El nuevo agente, en esta versión, no permite utilizar la cola de acciones."; + +?> + diff --git a/admin/WebConsole/idiomas/php/esp/comandos/gestor_ejecutarscripts_esp.php b/admin/WebConsole/idiomas/php/esp/comandos/gestor_ejecutarscripts_esp.php index ca0d1042..1b8386e5 100644 --- a/admin/WebConsole/idiomas/php/esp/comandos/gestor_ejecutarscripts_esp.php +++ b/admin/WebConsole/idiomas/php/esp/comandos/gestor_ejecutarscripts_esp.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/esp/ecoremoto_esp.php b/admin/WebConsole/idiomas/php/esp/ecoremoto_esp.php index 669c225c..d291a1ec 100644 --- a/admin/WebConsole/idiomas/php/esp/ecoremoto_esp.php +++ b/admin/WebConsole/idiomas/php/esp/ecoremoto_esp.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/esp/gestor_ordenadores_esp.php b/admin/WebConsole/idiomas/php/esp/gestor_ordenadores_esp.php new file mode 100644 index 00000000..2946a0c4 --- /dev/null +++ b/admin/WebConsole/idiomas/php/esp/gestor_ordenadores_esp.php @@ -0,0 +1,10 @@ + + diff --git a/admin/WebConsole/idiomas/php/esp/hardwares_esp.php b/admin/WebConsole/idiomas/php/esp/hardwares_esp.php index be3ae563..070cbe82 100644 --- a/admin/WebConsole/idiomas/php/esp/hardwares_esp.php +++ b/admin/WebConsole/idiomas/php/esp/hardwares_esp.php @@ -1,4 +1,4 @@ -En otro caso el protocolo es RSYNC.'; +$TbMsg["WARN_DIFFIMAGE"]='Hay una nueva versión de la imagen (se muestra la diferencia de revisiones).'; +$TbMsg["WARN_DIFFDISKSIZE"]='ATENCIÓN: no se pueden particionar grupos de ordenadores con distinto tamaño de disco.
Marcar la opción de "Desagrupar por tamaño de partición" y pulsar "Aceptar" en el menú superior para aplicar esta operación adecuadamente.'; ?> diff --git a/admin/WebConsole/idiomas/php/esp/procedimientoscomandos_esp.php b/admin/WebConsole/idiomas/php/esp/procedimientoscomandos_esp.php index ced99b29..ec630b99 100644 --- a/admin/WebConsole/idiomas/php/esp/procedimientoscomandos_esp.php +++ b/admin/WebConsole/idiomas/php/esp/procedimientoscomandos_esp.php @@ -1,4 +1,4 @@ -(opcional)"; $TbMsg['PROP_DNSIP']="IP Servidor DNS (opcional)"; $TbMsg['PROP_PROXYURL']="URL Servidor Proxy (opcional)"; +$TbMsg['COMM_DEFTIMEZONE']="zona horaria por defecto"; +$TbMsg['PROP_REMOTEACCESS']="Acceso remoto"; +$TbMsg['COMM_REMOTEACCESS']="permitir gestión de acceso remoto a los ordenadores"; +$TbMsg['COMM_DEFOGLIVE']="Asignado por el administrador"; ?> diff --git a/admin/WebConsole/idiomas/php/esp/propiedades_centros_esp.php b/admin/WebConsole/idiomas/php/esp/propiedades_centros_esp.php index 65d3092c..9ae392d5 100644 --- a/admin/WebConsole/idiomas/php/esp/propiedades_centros_esp.php +++ b/admin/WebConsole/idiomas/php/esp/propiedades_centros_esp.php @@ -1,4 +1,4 @@ -/opt/opengnsys/images
debe contener un subdirectorio llamado como el directorio indicado."; ?> - \ No newline at end of file diff --git a/admin/WebConsole/idiomas/php/esp/propiedades_componentehardwares_esp.php b/admin/WebConsole/idiomas/php/esp/propiedades_componentehardwares_esp.php index 2badfbd2..e567637a 100644 --- a/admin/WebConsole/idiomas/php/esp/propiedades_componentehardwares_esp.php +++ b/admin/WebConsole/idiomas/php/esp/propiedades_componentehardwares_esp.php @@ -1,4 +1,4 @@ - - \ No newline at end of file diff --git a/admin/WebConsole/idiomas/php/esp/propiedades_entornos_esp.php b/admin/WebConsole/idiomas/php/esp/propiedades_entornos_esp.php index dd7bbb53..3366d1b1 100644 --- a/admin/WebConsole/idiomas/php/esp/propiedades_entornos_esp.php +++ b/admin/WebConsole/idiomas/php/esp/propiedades_entornos_esp.php @@ -1,4 +1,4 @@ - +$TbMsg[12]="Gestión Imágenes Básicas"; +$TbMsg[13]="Gestión Imágenes Incrementales"; +$TbMsg[14]="Imagen básica"; +$TbMsg[15]="ATENCIÓN.- Una imagen que tiene perfil software indica que en algún momento se ha creado
y por tanto no pueden modificarse ciertos datos a menos que la elimine y la vuelva a crear"; $TbMsg[16]="Ruta Origen"; -$TbMsg[17]='"Nombre canónico fichero-imagen existe : Introduzca otro nombre"'; +$TbMsg[17]='"Nombre canónico fichero-imagen existe : Introduzca otro nombre"'; // JavaScript $TbMsg[18]="Introduzca otro Nombre"; $TbMsg[19]="Equipo modelo"; -$TbMsg[20]="Fecha de creación"; +$TbMsg[20]="Fecha de creación"; +$TbMsg[21]='"Descripción Nombre fichero-imagen existe : Introduzca otra Descripción"'; // JavaScript +$TbMsg[22]="Introduzca otra Descripción"; +$TbMsg['PROP_OS']="Sistema operativo"; +$TbMsg['PROP_REMOTEACCESS']="Acceso remoto"; +$TbMsg['COMM_REMOTEACCESS']="permitir gestión de acceso remoto a los ordenadores"; ?> diff --git a/admin/WebConsole/idiomas/php/esp/propiedades_menus_esp.php b/admin/WebConsole/idiomas/php/esp/propiedades_menus_esp.php index b39705ef..7435bb5a 100644 --- a/admin/WebConsole/idiomas/php/esp/propiedades_menus_esp.php +++ b/admin/WebConsole/idiomas/php/esp/propiedades_menus_esp.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/idiomas/php/esp/propiedades_ordenadores_esp.php b/admin/WebConsole/idiomas/php/esp/propiedades_ordenadores_esp.php index 21d3498e..faa5c3cd 100644 --- a/admin/WebConsole/idiomas/php/esp/propiedades_ordenadores_esp.php +++ b/admin/WebConsole/idiomas/php/esp/propiedades_ordenadores_esp.php @@ -4,7 +4,7 @@ // Fichero de idiomas php: propiedades_ordenadores_esp.php // Idioma: Español //______________________________________________________________ -$TbMsg=array(); +if (empty ($TbMsg)) $TbMsg=array(); $TbMsg[0]="Sin Opción"; $TbMsg[1]="Insertar"; $TbMsg[2]="Modificar"; @@ -25,10 +25,16 @@ $TbMsg[15]="Validación"; $TbMsg[16]="Pagina login"; $TbMsg[17]="Pagina validación"; // UHU +// AGP +$TbMsg[18]="ogLive"; $TbMsg[509]="Foto ordenador"; $TbMsg[5091]="Insertar foto"; $TbMsg[5092]="Ver fotos"; $TbMsg[495]="Fecha/Caché"; $TbMsg[4951]="Caché libre"; +//AGP +$TbMsg["PROP_SERIALNO"]="Nº de serie"; +$TbMsg["WARN_NOTDETECTED"]="(no detectado)"; +$TbMsg['COMM_DEFOGLIVE']="Asignado por el administrador"; ?> diff --git a/admin/WebConsole/idiomas/php/esp/propiedades_ordenadorestandar_esp.php b/admin/WebConsole/idiomas/php/esp/propiedades_ordenadorestandar_esp.php index c21e9b5a..a46a21f5 100644 --- a/admin/WebConsole/idiomas/php/esp/propiedades_ordenadorestandar_esp.php +++ b/admin/WebConsole/idiomas/php/esp/propiedades_ordenadorestandar_esp.php @@ -1,4 +1,4 @@ -Revise la clave de acceso (campo Api Token debe coincidir con su valor en fichero "ogAdmRepo.cfg")'; +$TbMsg[17]='Api Token'; +$TbMsg['MSG_CONTENT']='Contenido'; +$TbMsg['MSG_IMAGE']='Imagen'; +$TbMsg['MSG_TYPE']='Tipo'; +$TbMsg['MSG_SIZE']='Tamaño'; +$TbMsg['MSG_MODIFIED']='Modificado'; +$TbMsg['MSG_PERMISSIONS']='Permisos'; ?> diff --git a/admin/WebConsole/idiomas/php/esp/propiedades_reservas_esp.php b/admin/WebConsole/idiomas/php/esp/propiedades_reservas_esp.php index 6115645b..49abddd6 100644 --- a/admin/WebConsole/idiomas/php/esp/propiedades_reservas_esp.php +++ b/admin/WebConsole/idiomas/php/esp/propiedades_reservas_esp.php @@ -1,4 +1,4 @@ -"; $TbMsg[15]="creado en el proceso de instalación,

"; $TbMsg[16]="pulse aquí
"; -$TbMsg[17]="http://opengnsys.es/wiki/ModificarUsuarios"; -?> \ No newline at end of file +$TbMsg[17]="https://opengnsys.es/trac/wiki/ModificarUsuarios"; +$TbMsg[18]="Confirmar password"; +$TbMsg['APIKEY']="API key"; +$TbMsg['NEWAPIKEY']="La API key se generará automáticamente al insertar el usuario."; +?> diff --git a/admin/WebConsole/idiomas/php/esp/purgar_esp.php b/admin/WebConsole/idiomas/php/esp/purgar_esp.php index 82de0465..db6c41f8 100644 --- a/admin/WebConsole/idiomas/php/esp/purgar_esp.php +++ b/admin/WebConsole/idiomas/php/esp/purgar_esp.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/images/L_Iconos.php b/admin/WebConsole/images/L_Iconos.php index 9c03528a..1087eda5 100644 --- a/admin/WebConsole/images/L_Iconos.php +++ b/admin/WebConsole/images/L_Iconos.php @@ -1,4 +1,4 @@ - -'?> +'?> -

+

- + '; echo ''; diff --git a/admin/WebConsole/includes/opcionesprotocolos.php b/admin/WebConsole/includes/opcionesprotocolos.php index 5002316c..29a845bd 100644 --- a/admin/WebConsole/includes/opcionesprotocolos.php +++ b/admin/WebConsole/includes/opcionesprotocolos.php @@ -1,9 +1,11 @@ -texto='SELECT pormul, ipmul, modomul, velmul, puestos FROM aulas - WHERE aulas.idaula=' . $idambito ; +$cmd->texto="SELECT pormul, ipmul, modomul, velmul, ". + " count(idordenador) as puestos ". + " FROM aulas INNER JOIN ordenadores USING (idaula) ". + " WHERE aulas.idaula=$idambito" ; } if ($ambito == 8) { -$cmd->texto='SELECT pormul, ipmul, modomul, velmul, puestos FROM aulas - JOIN gruposordenadores ON aulas.idaula=gruposordenadores.idaula - WHERE gruposordenadores.idgrupo=' . $idambito ; +$cmd->texto=" SELECT pormul, ipmul, modomul, velmul, ". + " count(idordenador) as puestos ". + " FROM ordenadores ". + " INNER JOIN gruposordenadores ON ordenadores.grupoid = gruposordenadores.idgrupo ". + " INNER JOIN aulas ON gruposordenadores.idaula=aulas.idaula ". + " WHERE idgrupo=$idambito" ; } if ($ambito == 16) { -$cmd->texto='SELECT pormul, ipmul, modomul, velmul, puestos FROM aulas +$cmd->texto='SELECT pormul, ipmul, modomul, velmul, 1 AS puestos FROM aulas JOIN ordenadores ON ordenadores.idaula=aulas.idaula WHERE ordenadores.idordenador=' . $idambito ; } + $rs=new Recordset; $rs->Comando=&$cmd; if ($rs->Abrir()){ diff --git a/admin/WebConsole/includes/pintaParticiones.php b/admin/WebConsole/includes/pintaParticiones.php index e818bb3e..505defe1 100644 --- a/admin/WebConsole/includes/pintaParticiones.php +++ b/admin/WebConsole/includes/pintaParticiones.php @@ -63,10 +63,11 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) echo ''; // Recorremos todas las configuraciones encontradas para cada disco - + $aviso=""; foreach($diskConfigs as $disk => $diskConfig){ - echo''.chr(13); - echo ''.chr(13); + $disk = (int)$disk; + echo''.chr(13); + echo ''.chr(13); @@ -87,6 +88,8 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) break; case 3: $disktable[$tbKeys[$k]["numdisk"]] = "LVM"; break; + case 4: $disktable[$tbKeys[$k]["numdisk"]] = "ZPOOL"; + break; default: $disktable[$tbKeys[$k]["numdisk"]] = ""; } } @@ -94,7 +97,7 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) echo''.chr(13); echo''.chr(13); echo''.chr(13); - if ($disktable[$tbKeys[$k]["numdisk"]] == "LVM") { + if ($disktable[$tbKeys[$k]["numdisk"]] == "LVM" or $disktable[$tbKeys[$k]["numdisk"]] == "ZPOOL") { echo ''.chr(13); } else { @@ -108,12 +111,22 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) $filesys=tomaSistemasFicheros($tbKeys[$k]["numpar"],$idordenadores,false,$tbKeys[$k]["numdisk"]); echo''.chr(13); - echo ''.chr(13); - - echo''.chr(13); - + echo ''.chr(13); + // Mostrar uso solo en clientes individuales. + $uso=tomaUso($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]); + if ($uso > 0 and strpos($idordenadores, ',') === false) { + echo''.chr(13); + } else { + echo''.chr(13); + } + + // Si es CACHE incluyo campo oculto con el tamaño + if ($tbKeys[$k]["tipopar"]== "CACHE"){ + echo "".chr(13); + } + echo''.chr(13); - + echo''.chr(13); if ($filesys == "CACHE") { @@ -146,7 +159,12 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) echo ' '.chr(13); } else { - echo''.chr(13); + if ($tbKeys[$k]["difimagen"] > 0 ) { + echo''.chr(13); + $aviso=$TbMsg["WARN_DIFFIMAGE"]; + } else { + echo''.chr(13); + } } echo''.chr(13); @@ -163,7 +181,7 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) echo''.chr(13); echo''.chr(13); echo''.chr(13); - echo''.chr(13); + echo''.chr(13); // Creamos un campo oculto para guardar información sobre el disco y su tamaño separados por ; echo "\n"; echo''.chr(13); @@ -172,6 +190,9 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) echo''.chr(13); } } + if (!empty($aviso)) { + echo ''."\n"; + } echo ''; } @@ -188,6 +209,9 @@ function pintaParticiones($cmd,$configuraciones,$idordenadores,$cc) // Ejemplo:1;7;30000000;3;3;0;@2;130;20000000;5;4;0;@3;131;1000000;0;0;0;0 // Devuelve: // El código html de la tabla +// version 1.1: cliente con varios repositorios - HTMLSELECT_imagenes: cambia parametros idordenadores por idambito +// autor: Irina Gomez, Universidad de Sevilla +// fecha 2015-06-17 //________________________________________________________________________________________________________ function pintaParticionesRestaurarImagen($cmd,$configuraciones,$idordenadores,$cc,$ambito,$idambito) { @@ -217,8 +241,9 @@ function pintaParticionesRestaurarImagen($cmd,$configuraciones,$idordenadores,$c // Recorremos todas las configuraciones encontradas para cada disco foreach($diskConfigs as $disk => $diskConfig){ - echo''.chr(13); - echo ''.chr(13); + $disk = (int)$disk; + echo''.chr(13); + echo ''.chr(13); $auxCfg=split("@",$diskConfig); // Crea lista de particiones for($i=0;$i '.tomaNombresSO($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).' '.chr(13); echo''.chr(13); echo''.chr(13); - echo ''; - echo ''; + echo ''; + echo ''; //Clonación $metodos="UNICAST=UNICAST-CACHE".chr(13); @@ -291,15 +316,16 @@ function pintaParticionesConfigurar($cmd,$configuraciones,$idordenadores,$cc) $colums=7; echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; echo ''; + $aviso=false; $auxCfg=split("@",$configuraciones); // Crea lista de particiones for($i=0;$i'; + // Datos del disco + $tm=tomaTamano(0,$idordenadores); + echo ''. + "\n\n\n".$TbMsg["DISK"]."". + "\n\n '.(isset($tm)?$tm:("".$TbMsg["VARIABLE"].""))." ". + "\n\n\n"; + echo ''; // Mostrar aviso: solo disco 1 con tabla MSDOS. if ($aviso) { - echo ''; + echo ''; } // Botones de añadir y confirmar. - echo ''; + } else { + echo ''."\n"; + } } /* @@ -396,8 +432,9 @@ function pintaParticionesRestaurarImagenSincronizacion1($cmd,$configuraciones,$i // Recorremos todas las configuraciones encontradas para cada disco foreach($diskConfigs as $disk => $diskConfig){ - echo''.chr(13); - echo ''.chr(13); + $disk = (int)$disk; + echo''.chr(13); + echo ''.chr(13); $auxCfg=split("@",$diskConfig); // Crea lista de particiones for($i=0;$i $diskConfig){ - echo''.chr(13); - echo ''.chr(13); + $disk = (int)$disk; + echo''.chr(13); + echo ''.chr(13); $auxCfg=split("@",$diskConfig); // Crea lista de particiones for($i=0;$i $diskConfig){ - echo''.chr(13); - echo ''.chr(13); + $disk = (int)$disk; + echo''.chr(13); + echo ''.chr(13); $auxCfg=split("@",$diskConfig); // Crea lista de particiones for($i=0;$itexto="SELECT ordenadores.ip AS masterip,ordenadores_particiones.numdisk, ordenadores_particiones.numpar,ordenadores_particiones.codpar,ordenadores_particiones.tamano, ordenadores_particiones.idnombreso,nombresos.nombreso,tipospar.tipopar,tipospar.clonable, imagenes.nombreca,imagenes.descripcion as imagen,perfilessoft.idperfilsoft, @@ -208,20 +207,18 @@ function tablaConfiguracionesCrearImagen($cmd,$idordenador,$idrepositorio) LEFT OUTER JOIN perfilessoft ON perfilessoft.idperfilsoft=ordenadores_particiones.idperfilsoft LEFT OUTER JOIN sistemasficheros ON sistemasficheros.idsistemafichero=ordenadores_particiones.idsistemafichero WHERE ordenadores.idordenador=".$idordenador." ORDER BY ordenadores_particiones.numdisk,ordenadores_particiones.numpar"; - //echo $cmd->texto; - $rs->Comando=&$cmd; $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return($tablaHtml."
   -   Buscar

-

numeroderegistros?>

+

numeroderegistros?>

- - + + - EOF){?> - - - - + + + - + - Siguiente();}?> + Siguiente();}?>
A            T 
campos["idicono"]?> style="cursor:hand" onclick="menu_contextual(this)" src="../images/iconos/administrar_off.gif"> campos["descripcion"])] ) ? $TbMsg[basename($rs->campos["descripcion"])] : basename($rs->campos["descripcion"]); ?>  campos["urlicono"])?>  " + campos["idicono"]?> style="cursor:hand" onclick="menu_contextual(this)" src="../images/iconos/administrar_off.gif"> campos["descripcion"])] ) ? $TbMsg[basename($rs->campos["descripcion"])] : basename($rs->campos["descripcion"]); ?>  campos["urlicono"])?>  " - campos["idtipoicono"]==2) //icono item + campos["idtipoicono"]==2) //icono item echo " width=64 "; else echo " width=16 "; ?> >  campos["idtipoicono"]] ?>  campos["idtipoicono"]] ?> 
-CreaMenuContextual($XMLcontextual); - -'?> +'?>
- - - - - + + + + +
-


-

-

+


+

+

- - - - - - - - - + + + + + + - + - + - - - + - + - - + + - - + - - + +
       + +
      
 Icono 
    +    
      
    +    
@@ -256,7 +256,7 @@ if($accion==$INSERTAR_REGISTRO || $accion==$MODIFICAR_REGISTRO){
- '; break; @@ -274,7 +274,7 @@ if($accion==$INSERTAR_REGISTRO || $accion==$MODIFICAR_REGISTRO){ -'; @@ -286,7 +286,7 @@ echo ''; - texto="SELECT CONCAT_WS( ';',ordenadores_particiones.numdisk,ordenadores_particiones.numpar, "; - if($sws & $msk_tamano) + // Comprobar modos SQL para hacer que la consulta sea compatible. + $cmd->texto="SELECT @@sql_mode AS mode"; + $cmd->ejecutar(); + @$mode=$cmd->Recordset->campos["mode"]; + + $cmd->texto="SELECT CONCAT_WS(';', LPAD(ordenadores_particiones.numdisk, 3, 0), + LPAD(ordenadores_particiones.numpar, 3, 0), "; + + if($sws & $msk_tamano) $cmd->texto.=" ordenadores_particiones.tamano,"; - if($sws & $msk_sysFi) + if($sws & $msk_sysFi) $cmd->texto.=" ordenadores_particiones.idsistemafichero, "; - - if($sws & $msk_nombreSO) + + if($sws & $msk_nombreSO) $cmd->texto.=" ordenadores_particiones.idnombreso, "; if($sws & $msk_imagen) @@ -83,60 +89,62 @@ function cargaCaves($cmd,$idambito,$ambito,$sws,$swr) $cmd->texto.=" ordenadores_particiones.idperfilsoft, "; if($sws & $msk_cache) - $cmd->texto.=" ordenadores_particiones.cache, "; + $cmd->texto.=" ordenadores_particiones.cache, "; $cmd->texto.=" ordenadores_particiones.codpar) AS configuracion, - ordenadores_particiones.numdisk, - ordenadores_particiones.numpar , - ordenadores_particiones.codpar , - IFNULL (tipospar.tipopar, ordenadores_particiones.codpar) AS tipopar, - tipospar.clonable, - ordenadores_particiones.tamano, - sistemasficheros.descripcion AS sistemafichero, - ordenadores_particiones.idnombreso, - nombresos.nombreso, - imagenes.idimagen, - imagenes.descripcion AS imagen, - imagenes.nombreca AS nombreca, - imagenes.idrepositorio AS repositorio, - ordenadores_particiones.fechadespliegue, - ordenadores_particiones.idperfilsoft, - perfilessoft.descripcion AS perfilsoft - + ANY_VALUE(ordenadores_particiones.numdisk) AS numdisk, + ANY_VALUE(ordenadores_particiones.numpar) AS numpar, + ANY_VALUE(ordenadores_particiones.codpar) AS codpar, + IFNULL (ANY_VALUE(tipospar.tipopar), ANY_VALUE(ordenadores_particiones.codpar)) AS tipopar, + ANY_VALUE(tipospar.clonable) AS clonable, + ANY_VALUE(ordenadores_particiones.tamano) AS tamano, + ANY_VALUE(ordenadores_particiones.uso) AS uso, + ANY_VALUE(sistemasficheros.descripcion) AS sistemafichero, + ANY_VALUE(ordenadores_particiones.idnombreso) AS idnombreso, + ANY_VALUE(nombresos.nombreso) AS nombreso, + ANY_VALUE(imagenes.idimagen) AS idimagen, + ANY_VALUE(imagenes.descripcion) AS imagen, + (ANY_VALUE(imagenes.revision) - ANY_VALUE(ordenadores_particiones.revision)) AS difimagen, + ANY_VALUE(imagenes.nombreca) AS nombreca, + ANY_VALUE(imagenes.idrepositorio) AS repositorio, + ANY_VALUE(ordenadores_particiones.fechadespliegue) AS fechadespliegue, + ANY_VALUE(ordenadores_particiones.idperfilsoft) AS idperfilsoft, + ANY_VALUE(perfilessoft.descripcion) AS perfilsoft FROM ordenadores - INNER JOIN ordenadores_particiones ON ordenadores_particiones.idordenador=ordenadores.idordenador - LEFT OUTER JOIN nombresos ON nombresos.idnombreso=ordenadores_particiones.idnombreso - LEFT OUTER JOIN tipospar ON tipospar.codpar=ordenadores_particiones.codpar - LEFT OUTER JOIN imagenes ON imagenes.idimagen=ordenadores_particiones.idimagen - LEFT OUTER JOIN perfilessoft ON perfilessoft.idperfilsoft=ordenadores_particiones.idperfilsoft - LEFT OUTER JOIN sistemasficheros ON sistemasficheros.idsistemafichero=ordenadores_particiones.idsistemafichero"; - + INNER JOIN ordenadores_particiones ON ordenadores_particiones.idordenador=ordenadores.idordenador + LEFT OUTER JOIN nombresos ON nombresos.idnombreso=ordenadores_particiones.idnombreso + LEFT OUTER JOIN tipospar ON tipospar.codpar=ordenadores_particiones.codpar + LEFT OUTER JOIN imagenes ON imagenes.idimagen=ordenadores_particiones.idimagen + LEFT OUTER JOIN perfilessoft ON perfilessoft.idperfilsoft=ordenadores_particiones.idperfilsoft + LEFT OUTER JOIN sistemasficheros ON sistemasficheros.idsistemafichero=ordenadores_particiones.idsistemafichero"; + switch($ambito){ case $AMBITO_AULAS : $cmd->texto.=" INNER JOIN aulas ON aulas.idaula = ordenadores.idaula - WHERE aulas.idaula =".$idambito; + WHERE aulas.idaula=".$idambito; break; case $AMBITO_GRUPOSORDENADORES : $cmd->texto.=" INNER JOIN gruposordenadores ON gruposordenadores.idgrupo = ordenadores.grupoid - WHERE gruposordenadores.idgrupo =".$idambito; + WHERE gruposordenadores.idgrupo=".$idambito; break; case $AMBITO_ORDENADORES : - $cmd->texto.=" WHERE ordenadores.idordenador =".$idambito; + $cmd->texto.=" WHERE ordenadores.idordenador=".$idambito; break; } - + if($swr) // Si se trata de restauración no se tiene en cuenta las partciones no clonables $cmd->texto.=" AND tipospar.clonable=1 AND ordenadores_particiones.numpar>0 "; - $cmd->texto.=" GROUP by configuracion"; + $cmd->texto.=" GROUP BY configuracion"; + // Comprobar compatiblidad de cláusula GROUP BY. + if (strpos($mode, 'ONLY_FULL_GROUP_BY') === false) + $cmd->texto=preg_replace('/ANY_VALUE/', '', $cmd->texto); - //echo "carga claves:".$cmd->texto; $rs=new Recordset; $rs->Comando=&$cmd; - if (!$rs->Abrir()) return($tablaHtml); // Error al abrir recordset + if (!$rs->Abrir()) return(false); // Error al abrir recordset $rs->Primero(); $idx=0; - //echo $cmd->texto; while (!$rs->EOF){ $tbKeys[$idx]["cfg"]=$rs->campos["configuracion"]; $tbKeys[$idx]["numdisk"]=$rs->campos["numdisk"]; @@ -145,6 +153,7 @@ function cargaCaves($cmd,$idambito,$ambito,$sws,$swr) $tbKeys[$idx]["tipopar"]=$rs->campos["tipopar"]; $tbKeys[$idx]["clonable"]=$rs->campos["clonable"]; $tbKeys[$idx]["tamano"]=$rs->campos["tamano"]; + $tbKeys[$idx]["uso"]=$rs->campos["uso"]; $tbKeys[$idx]["sistemafichero"]=$rs->campos["sistemafichero"]; $tbKeys[$idx]["idnombreso"]=$rs->campos["idnombreso"]; $tbKeys[$idx]["nombreso"]=$rs->campos["nombreso"]; @@ -153,6 +162,7 @@ function cargaCaves($cmd,$idambito,$ambito,$sws,$swr) $tbKeys[$idx]["nombreca"]=$rs->campos["nombreca"]; $tbKeys[$idx]["repositorio"]=$rs->campos["repositorio"]; $tbKeys[$idx]["fechadespliegue"]=$rs->campos["fechadespliegue"]; + $tbKeys[$idx]["difimagen"]=$rs->campos["difimagen"]; $tbKeys[$idx]["idperfilsoft"]=$rs->campos["idperfilsoft"]; $tbKeys[$idx]["perfilsoft"]=$rs->campos["perfilsoft"]; //$tbKeys[$idx]["cache"]=$rs->campos["cache"]; @@ -199,7 +209,6 @@ function pintaConfiguraciones($cmd,$idambito,$ambito,$colums,$sws,$swr,$pintaPar cargaNombresSO($cmd,$idambito,$ambito); cargaTamano($cmd,$idambito,$ambito); cargaCache($cmd,$idambito,$ambito); - $cmd->texto="SELECT COUNT(*) AS con, GROUP_CONCAT(CAST( temp2.idordenador AS CHAR(11) ) ORDER BY temp2.idordenador SEPARATOR ',' ) AS idordenadores, temp2.configuraciones @@ -208,8 +217,8 @@ function pintaConfiguraciones($cmd,$idambito,$ambito,$colums,$sws,$swr,$pintaPar GROUP_CONCAT(CAST( temp1.configuracion AS CHAR(250) ) ORDER BY temp1.configuracion SEPARATOR '@' ) AS configuraciones FROM (SELECT ordenadores_particiones.idordenador,ordenadores_particiones.numdisk, ordenadores_particiones.numpar, - concat_WS( ';', ordenadores_particiones.numdisk, - ordenadores_particiones.numpar, "; + CONCAT_WS(';', LPAD(ordenadores_particiones.numdisk, 3, 0), + LPAD(ordenadores_particiones.numpar, 3, 0), "; if($sws & $msk_tamano) $cmd->texto.=" ordenadores_particiones.tamano,"; @@ -375,19 +384,18 @@ function cargaSistemasFicheros($cmd,$idambito,$ambito) break; } $cmd->texto.=" GROUP BY ordenadores_particiones.numdisk,ordenadores_particiones.numpar, ordenadores_particiones.idsistemafichero"; - + $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return; // Error al abrir recordset $rs->Primero(); $idx=0; - //echo $cmd->texto; while (!$rs->EOF){ $tbSysFi[$idx]["idsistemafichero"]=$rs->campos["idsistemafichero"]; $tbSysFi[$idx]["numdisk"]=$rs->campos["numdisk"]; $tbSysFi[$idx]["numpar"]=$rs->campos["numpar"]; $tbSysFi[$idx]["sistemafichero"]=$rs->campos["sistemafichero"]; - $tbSysFi[$idx]["ordenadores"]=$rs->campos["ordenadores"]; + $tbSysFi[$idx]["ordenadores"]=$rs->campos["ordenadores"]; $idx++; $rs->Siguiente(); } @@ -407,8 +415,6 @@ function tomaSistemasFicheros($numpar,$ordenadores,$sw=false,$numdisk = 1) for ($k=0; $k<$conSysFi; $k++){ if ($tbSysFi[$k]["numdisk"] == $numdisk && $tbSysFi[$k]["numpar"] == $numpar) { - //$pos = strpos($tbSysFi[$k]["ordenadores"], $ordenadores); - //if ($pos !== false) { // Cadena encontrada $pcs = explode (",", $ordenadores); $intersec = array_intersect (explode(",", $tbSysFi[$k]["ordenadores"]), $pcs); if (array_diff ($pcs, $intersec) == NULL) { @@ -459,7 +465,7 @@ function cargaPerfiles($cmd,$idambito,$ambito) break; } $cmd->texto.=" GROUP BY ordenadores_particiones.numdisk,ordenadores_particiones.numpar, ordenadores_particiones.idperfilsoft"; - //echo "carga perfiles:".$cmd->texto; + $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return; // Error al abrir recordset @@ -488,9 +494,6 @@ function tomaPerfiles($numpar,$ordenadores,$numdisk = 1) global $conPerfil; // Contador de elementos anteriores for ($k=0; $k<$conPerfil; $k++){ - //$pos = strpos($tbPerfil[$k]["ordenadores"], $ordenadores); - //if ($pos !== false) { // Cadena encontrada - //if($tbPerfil[$k]["numpar"]==$numpar) if ($tbPerfil[$k]["numdisk"] == $numdisk && $tbPerfil[$k]["numpar"] == $numpar) { $pcs = explode (",", $ordenadores); $intersec = array_intersect (explode(",", $tbPerfil[$k]["ordenadores"]), $pcs); @@ -538,7 +541,7 @@ function cargaImagenes($cmd,$idambito,$ambito) break; } $cmd->texto.=" GROUP BY ordenadores_particiones.numdisk,ordenadores_particiones.numpar, ordenadores_particiones.idimagen"; - //echo "carga imagenes:".$cmd->texto; + $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return; // Error al abrir recordset @@ -567,9 +570,6 @@ function tomaImagenes($numpar,$ordenadores, $numdisk = 1) global $conImg; // Contador de elementos anteriores for ($k=0; $k<$conImg; $k++) { - //$pos = strpos($tbImg[$k]["ordenadores"], $ordenadores); - //if ($pos !== false) { // Cadena encontrada - //if($tbImg[$k]["numpar"]==$numpar){ if ($tbImg[$k]["numdisk"] == $numdisk && $tbImg[$k]["numpar"] == $numpar) { $pcs = explode (",", $ordenadores); $intersec = array_intersect (explode(",", $tbImg[$k]["ordenadores"]), $pcs); @@ -615,7 +615,7 @@ function cargaNombresSO($cmd,$idambito,$ambito) break; } $cmd->texto.=" GROUP BY ordenadores_particiones.numdisk,ordenadores_particiones.numpar, ordenadores_particiones.idnombreso"; - //echo "carga nombresos:".$cmd->texto; + $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return; // Error al abrir recordset @@ -668,10 +668,15 @@ function cargaTamano($cmd,$idambito,$ambito) global $AMBITO_GRUPOSORDENADORES; global $AMBITO_ORDENADORES; + // Comprobar modos SQL para hacer que la consulta sea compatible. + $cmd->texto="SELECT @@sql_mode AS mode"; + $cmd->ejecutar(); + @$mode=$cmd->Recordset->campos["mode"]; $cmd->texto="SELECT COUNT(*) AS con, - ordenadores_particiones.tamano, - ordenadores_particiones.numdisk, - ordenadores_particiones.numpar, + ANY_VALUE(ordenadores_particiones.tamano) AS tamano, + ANY_VALUE(ordenadores_particiones.uso) AS uso, + ANY_VALUE(ordenadores_particiones.numdisk) AS numdisk, + ANY_VALUE(ordenadores_particiones.numpar) AS numpar, GROUP_CONCAT(CAST(ordenadores_particiones.idordenador AS CHAR(11) ) ORDER BY ordenadores_particiones.idordenador SEPARATOR ',' ) AS ordenadores FROM ordenadores @@ -691,18 +696,22 @@ function cargaTamano($cmd,$idambito,$ambito) break; } $cmd->texto.=" GROUP BY ordenadores_particiones.numdisk,ordenadores_particiones.numpar, ordenadores_particiones.tamano"; - //echo "carga tamaños:".$cmd->texto; + // Comprobar compatiblidad de cláusula GROUP BY. + if (strpos($mode, 'ONLY_FULL_GROUP_BY') === false) + $cmd->texto=preg_replace('/ANY_VALUE/', '', $cmd->texto); + $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return; // Error al abrir recordset $rs->Primero(); $idx=0; while (!$rs->EOF){ - $tbTam[$idx]["tamano"]=$rs->campos["tamano"]; - $tbTam[$idx]["numdisk"]=$rs->campos["numdisk"]; - $tbTam[$idx]["numpar"]=$rs->campos["numpar"]; - $tbTam[$idx]["ordenadores"]=$rs->campos["ordenadores"]; - $idx++; + $tbTam[$idx]["tamano"]=$rs->campos["tamano"]; + $tbTam[$idx]["uso"]=$rs->campos["uso"]; + $tbTam[$idx]["numdisk"]=$rs->campos["numdisk"]; + $tbTam[$idx]["numpar"]=$rs->campos["numpar"]; + $tbTam[$idx]["ordenadores"]=$rs->campos["ordenadores"]; + $idx++; $rs->Siguiente(); } $conTam=$idx; // Guarda contador @@ -730,6 +739,27 @@ function tomaTamano($numpar,$ordenadores,$numdisk = 1) } } } +/*________________________________________________________________________________________________________ + + Toma porcentaje de uso de partición común a los ordenadores pasados como parámetros +________________________________________________________________________________________________________*/ +function tomaUso($numpar, $ordenadores, $numdisk=1) +{ + global $tbTam; // Tabla contenedora de ordenadores incluidos en la consulta + global $conTam; // Contador de elementos anteriores + + for ($k=0; $k<$conTam; $k++) { + if ($tbTam[$k]["numdisk"] == $numdisk && $tbTam[$k]["numpar"] == $numpar) { +// $pos = strpos ($tbTam[$k]["ordenadores"], $ordenadores); +// if ($pos !== FALSE) { // Cadena encontrada + $pcs = explode (",", $ordenadores); + $intersec = array_intersect (explode(",", $tbTam[$k]["ordenadores"]), $pcs); + if (array_diff ($pcs, $intersec) == NULL) { + return ($tbTam[$k]["uso"]); + } + } + } +} /*________________________________________________________________________________________________________ Selecciona los ordenadores que tienen el mismo Contenido de Cache para la misma partición @@ -766,6 +796,7 @@ function cargaCache($cmd,$idambito,$ambito) break; } $cmd->texto.=" GROUP BY ordenadores_particiones.numdisk,ordenadores_particiones.numpar, ordenadores_particiones.cache"; + $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return; // Error al abrir recordset diff --git a/admin/WebConsole/includes/CreaComando.php b/admin/WebConsole/includes/CreaComando.php index 06bce0bb..f8d3f8d7 100644 --- a/admin/WebConsole/includes/CreaComando.php +++ b/admin/WebConsole/includes/CreaComando.php @@ -1,4 +1,4 @@ - \ No newline at end of file +?> diff --git a/admin/WebConsole/includes/RecopilaIpesMacs.php b/admin/WebConsole/includes/RecopilaIpesMacs.php index f3caac06..70a7f8e3 100644 --- a/admin/WebConsole/includes/RecopilaIpesMacs.php +++ b/admin/WebConsole/includes/RecopilaIpesMacs.php @@ -1,4 +1,4 @@ -texto="SELECT ip, mac, nombreordenador, idordenador FROM ordenadores WHERE ip IN (".$filtroip.")"; + $cmd->texto="SELECT ip, mac, nombreordenador, idordenador, agentkey + FROM ordenadores + WHERE ip IN (".$filtroip.")"; RecorreOrdenadores($cmd); } else{ @@ -60,13 +62,16 @@ function RecopilaIpesMacs($cmd,$ambito,$idambito,$filtroip=""){ RecorreGruposOrdenadores($cmd); break; case $AMBITO_ORDENADORES : - $cmd->texto="SELECT ip,mac,nombreordenador,idordenador FROM ordenadores WHERE idordenador=".$idambito; + $cmd->texto="SELECT ip, mac, nombreordenador, idordenador, agentkey + FROM ordenadores + WHERE idordenador=".$idambito; RecorreOrdenadores($cmd); break; default: // Se trata de un conjunto aleatorio de ordenadores - $cmd->texto="SELECT ip,mac,nombreordenador,idordenador FROM ordenadores WHERE idordenador IN (".$idambito.")"; + $cmd->texto="SELECT ip, mac, nombreordenador, idordenador, agentkey + FROM ordenadores + WHERE idordenador IN (".$idambito.")"; RecorreOrdenadores($cmd); - } } $cadenaid=substr($cadenaid,0,strlen($cadenaid)-1); // Quita la coma @@ -116,7 +121,9 @@ function RecorreAulas($cmd){ $idaula=$rs->campos["idaula"]; $cmd->texto="SELECT idgrupo,nombregrupoordenador FROM gruposordenadores WHERE idaula=".$idaula." AND grupoid=0"; RecorreGruposOrdenadores($cmd); - $cmd->texto="SELECT ip,mac,nombreordenador,idordenador FROM ordenadores WHERE idaula=".$idaula." AND grupoid=0"; + $cmd->texto="SELECT ip, mac, nombreordenador, idordenador, agentkey + FROM ordenadores + WHERE idaula=".$idaula." AND grupoid=0"; RecorreOrdenadores($cmd); $rs->Siguiente(); } @@ -132,7 +139,9 @@ function RecorreGruposOrdenadores($cmd){ $idgrupo=$rs->campos["idgrupo"]; $cmd->texto="SELECT idgrupo,nombregrupoordenador FROM gruposordenadores WHERE grupoid=".$idgrupo; RecorreGruposOrdenadores($cmd); - $cmd->texto="SELECT ip,mac,nombreordenador,idordenador FROM ordenadores WHERE grupoid=".$idgrupo; + $cmd->texto="SELECT ip, mac, nombreordenador, idordenador, agentkey + FROM ordenadores + WHERE grupoid=".$idgrupo; RecorreOrdenadores($cmd); $rs->Siguiente(); } @@ -143,6 +152,7 @@ function RecorreOrdenadores($cmd){ global $cadenaid; global $cadenaip; global $cadenamac; + global $cadenaoga; $rs=new Recordset; $rs->Comando=&$cmd; if (!$rs->Abrir()) return; // Error al abrir recordset @@ -150,6 +160,7 @@ function RecorreOrdenadores($cmd){ $cadenaid.=$rs->campos["idordenador"].","; $cadenaip.=$rs->campos["ip"].";"; $cadenamac.=$rs->campos["mac"].";"; + $cadenaoga.=(is_null($rs->campos["agentkey"])?"":$rs->campos["agentkey"]).";"; $rs->Siguiente(); } $rs->Cerrar(); diff --git a/admin/WebConsole/includes/RedireccionaError.php b/admin/WebConsole/includes/RedireccionaError.php index 92a6cd4c..420f47a4 100644 --- a/admin/WebConsole/includes/RedireccionaError.php +++ b/admin/WebConsole/includes/RedireccionaError.php @@ -1,4 +1,4 @@ - - + - +
diff --git a/admin/WebConsole/includes/opcionesbotonesop.php b/admin/WebConsole/includes/opcionesbotonesop.php index d86755d7..85138063 100644 --- a/admin/WebConsole/includes/opcionesbotonesop.php +++ b/admin/WebConsole/includes/opcionesbotonesop.php @@ -1,4 +1,4 @@ -'; echo '
 '.$TbMsg["DISK"].' '.$disk.'
 '.$TbMsg["DISK"].' '.$disk.'
 '.$tbKeys[$k]["numpar"].' '.$filesys.'  '.tomaNombresSO($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).'  '.tomaTamano($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).'  '.tomaNombresSO($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).'  '.tomaTamano($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).'  '.tomaTamano($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).'  '.tomaImagenes($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).'  '.tomaPerfiles($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).'  '.$tbKeys[$k]["fechadespliegue"].'  '.$tbKeys[$k]["fechadespliegue"].' (* '.$tbKeys[$k]["difimagen"].')  '.$tbKeys[$k]["fechadespliegue"].' 
 '.$disksize[$disk].'  '.(isset($disksize[$disk])?$disksize[$disk]:(''.$TbMsg["VARIABLE"].'')).' 
 * '.$aviso.' 
 
 '.$TbMsg["DISK"].' '.$disk.'
 '.$TbMsg["DISK"].' '.$disk.' '.tomaSistemasFicheros($tbKeys[$k]["numpar"],$idordenadores,false,$tbKeys[$k]["numdisk"]).'  '.tomaTamano($tbKeys[$k]["numpar"],$idordenadores,$tbKeys[$k]["numdisk"]).' '.HTMLSELECT_imagenes($cmd,$tbKeys[$k]["idimagen"],$tbKeys[$k]["numpar"],$tbKeys[$k]["codpar"],$icp,true,$idordenadores,$ambito).''.HTMLSELECT_imagenes($cmd,$tbKeys[$k]["idimagen"],$tbKeys[$k]["numpar"],$tbKeys[$k]["codpar"],$icp,false,$idordenadores,$ambito).''.HTMLSELECT_imagenes($cmd,$tbKeys[$k]["idimagen"],$tbKeys[$k]["numpar"],$tbKeys[$k]["codpar"],$icp,true,$idambito,$ambito).''.HTMLSELECT_imagenes($cmd,$tbKeys[$k]["idimagen"],$tbKeys[$k]["numpar"],$tbKeys[$k]["codpar"],$icp,false,$idambito,$ambito).'
 '.$TbMsg[8].'  '.$TbMsg[24].'  '.$TbMsg[27].'  '.$TbMsg[22].'  '.$TbMsg[21].'  '.$TbMsg[14].'  '.$TbMsg['REMOVE'].'  '.$TbMsg['PARTITION'].'  '.$TbMsg['PARTITION_TYPE'].'  '.$TbMsg['FILESYSTEM'].'  '.$TbMsg['SIZE_KB'].'  '.$TbMsg['INSTALLED_OS'].'  '.$TbMsg['REFORMAT'].' 
 
 '.$TbMsg["WARN_DISKSIZE"].'
'.$TbMsg["CONFIG_NODISK1MSDOS"].'
'.$TbMsg["CONFIG_NODISK1MSDOS"].'
'; - echo ' + if (isset($tm)) { + echo '
'; + echo '         
'.$TbMsg["WARN_DIFFDISKSIZE"].'
 '.$TbMsg["DISK"].' '.$disk.'
 '.$TbMsg["DISK"].' '.$disk.'
 '.$TbMsg["DISK"].' '.$disk.'
 '.$TbMsg["DISK"].' '.$disk.'
 '.$TbMsg["DISK"].' '.$disk.'
 '.$TbMsg["DISK"].' '.$disk.'
"); // Error al abrir recordset $rs->Primero(); $actualDisk = 0; - $columns = 6; + $columns = 5; while (!$rs->EOF){ if($actualDisk != $rs->campos["numdisk"]){ $actualDisk = $rs->campos["numdisk"]; - $tablaHtml.='
 '.$TbMsg["DISK"].' '.$actualDisk.'
 '.$TbMsg["DISK"].' '.$actualDisk.'
 '.''.$TbMsg[12].' '.$rs->campos["nombreso"].' '.HTMLSELECT_imagenes($cmd,$idrepositorio,$rs->campos["idperfilsoft"],$rs->campos["numdisk"],$rs->campos["numpar"],$rs->campos["masterip"]).''.HTMLSELECT_repositorios($cmd,$idcentro,$idrepositorio,$rs->campos["numdisk"],$rs->campos["numpar"],$rs->campos["masterip"]).' 
 '. $TbMsg["PARTITION"] .'  '. $TbMsg["PARTITION_TYPE"] .'  '. $TbMsg["SO_NAME"] .'  '. $TbMsg["IMAGE_TO_CREATE"] .'  '. $TbMsg["DESTINATION_REPOSITORY"] .'  '. $TbMsg["IMAGE_TO_CREATE"].' -- '.$TbMsg["DESTINATION_REPOSITORY"] .' 

@@ -123,7 +124,7 @@ fclose($crearficheroinicio);

-

GPL v3

+

GPL v3

-

".$TbMsg["MANUAL"]."";?>

+

".$TbMsg["MANUAL"]."";?>

-

opengnsys.es

+

opengnsys.es

diff --git a/admin/WebConsole/principal/actualizar.php b/admin/WebConsole/principal/actualizar.php index 3647c87d..a67e3585 100644 --- a/admin/WebConsole/principal/actualizar.php +++ b/admin/WebConsole/principal/actualizar.php @@ -1,4 +1,4 @@ - - '?> - '?> + '?> + '?> -CreaArbolVistaXML(); // Crea �bol (HTML) a partir del XML @@ -66,7 +66,7 @@ $flotante=new MenuContextual(); // Crea objeto MenuContextual ?> - -'?> -'?> -'?> +'?> + - - + + -CreaMenuContextual($XMLcontextual); @@ -138,7 +138,7 @@ echo $flotante->CreaMenuContextual($XMLcontextual); -campos["idordenador"]; $Midordenador[$k]=$rs->campos["idordenador"]; $Mnombreordenador[$k]=$rs->campos["nombreordenador"]; - $MimgOrdenador[$k]="ordenador_OFF.gif"; + $MimgOrdenador[$k]="ordenador_OFF.png"; $Mip[$k]=$rs->campos["ip"]; $Mmac[$k]=$rs->campos["mac"]; $cadenaip.=$rs->campos["ip"].";"; @@ -295,13 +295,17 @@ function pintaordenadores(){ } } echo '
'; - echo ' -

- - '; - foreach ( Array ("OPG", "BSY", "WXP", "LNX", "OFF") as $status) { - echo ' '; + echo '

'; + echo '

'.$status.'
'.$TbMsg["STATUS_$status"].'
'; + echo ' '; + foreach (Array ("OPG", "WIN", "LNX", "OSX") as $status) { + echo ' '; } + echo ' '; + foreach (Array ("BSY", "WINS", "LNXS", "OFF") as $status) { + echo ' '; + } + echo ' '; echo ' '; echo '
'.$status.'
'.$TbMsg["STATUS_$status"].'
'.$status.'
'.str_replace(" ", "
", $TbMsg["STATUS_$status"]).'
'; if ($nombreaula!="") diff --git a/admin/WebConsole/principal/aulas.php b/admin/WebConsole/principal/aulas.php index 6d8887fc..631e68dc 100644 --- a/admin/WebConsole/principal/aulas.php +++ b/admin/WebConsole/principal/aulas.php @@ -54,7 +54,7 @@ $arbol=new ArbolVistaXML($arbolXML,0,$baseurlimg,$clasedefault,1,0,5); // Crea e -CreaArbolVistaXML(); // Crea árbol (HTML) a partir del XML $flotante=new MenuContextual(); // Crea objeto MenuContextual @@ -116,7 +116,7 @@ echo $flotante->CreaMenuContextual($XMLcontextual); ?> -'; - $layerXML.=''; - $layerXML.=''; - - $layerXML.='

- - - - + + + + "; ?> @@ -169,7 +168,6 @@ if (!empty($_SESSION["widcentro"])) $desconocido="00unknown"; // - echo $estado; //mostrar los datos for($i=0; $i





- - - - + + + + @@ -92,9 +92,9 @@ if ($opcioncrear == 1)






- - - + + + @@ -158,10 +158,10 @@ boot";
- - - - + + + + @@ -170,9 +170,9 @@ boot";
- - - + + + @@ -209,9 +209,9 @@ if ($opcioncrear == 2) - - -






- - - + + + @@ -233,9 +233,9 @@ if ($opcioncrear == 2) - - - - + + + + - - - - + + + + - - - - + + + + @@ -573,10 +573,10 @@ for ($b=0;$b - - - - + + + + @@ -585,9 +585,9 @@ for ($b=0;$b
- - - + + + @@ -677,9 +677,9 @@ $rs->Cerrar();






- - - + + + @@ -298,10 +298,10 @@ if ($numeros > 19)

- - - - + + + + @@ -314,10 +314,10 @@ if ($numeros > 19) 19){ ?>

@@ -341,10 +341,10 @@ if ($numeros > 19)
@@ -387,10 +387,10 @@ if ($numeros > 19) - - - - + + + + @@ -399,9 +399,9 @@ if ($numeros > 19)
- - - + + + @@ -489,10 +489,10 @@ for ($b=0;$b

- - - - + + + +

@@ -741,9 +741,9 @@ array_multisort($pn); @@ -12,9 +12,9 @@ diff --git a/admin/WebConsole/principal/boot_pxelinux.php b/admin/WebConsole/principal/boot_pxelinux.php deleted file mode 100644 index babd2bfe..00000000 --- a/admin/WebConsole/principal/boot_pxelinux.php +++ /dev/null @@ -1,217 +0,0 @@ - -Administración web de aulas - - - - - - - - - - - - - -






- - - + + +
- - - + + + @@ -752,9 +752,9 @@ array_multisort($pn);
- - - + + +
diff --git a/admin/WebConsole/principal/boot_grub4dos_tabla.php b/admin/WebConsole/principal/boot_grub4dos_tabla.php index d381e3e4..7baae042 100644 --- a/admin/WebConsole/principal/boot_grub4dos_tabla.php +++ b/admin/WebConsole/principal/boot_grub4dos_tabla.php @@ -2,9 +2,9 @@
- - - + + +

- - - + + + name="nuevoarran"> @@ -24,9 +24,9 @@

- - - + + + name="nuevoarran"> @@ -35,9 +35,9 @@

- - - + + + name="nuevoarran">
@@ -46,9 +46,9 @@
- - - + + +
- - - -

Gestión Arranque Avanzado
- -

- - - - - - - -"; -?> - - - - - - - -texto="SELECT * FROM menuboot where label <> 'pxe' "; -$rsmenu=new Recordset; -$rsmenu->Comando=&$cmd; -if (!$rsmenu->Abrir()) echo "error"; -$rsmenu->Primero(); -while (!$rsmenu->EOF) -{ - echo ""; - echo ""; - $rsmenu->Siguiente(); -} -$rsmenu->Cerrar(); - - - - - - - -// esta funcion genera los elementos de un select(formulario html) donde aparecen los nombres de los ordenadores, según su menu pxe -function listaequipos($cmd,$menupxe,$seleccion) -{ -$cmd->texto="SELECT * FROM ordenadores where arranque='" . $menupxe ."' " . $seleccion; -$rs=new Recordset; -$rs->Comando=&$cmd; -if (!$rs->Abrir()) echo "error"; -$rs->Primero(); -while (!$rs->EOF) -{ - echo ""; - $rs->Siguiente(); -} -$rs->Cerrar(); -} - -?> - - - - -
- -
OG-Live

- -
"; - echo $rsmenu->campos['description']; - #echo " " . $rsmenu->campos['description'] . "
". $rs->campos['label'] . "
"; - echo "
"; - echo ""; - echo ""; - echo "
"; - echo ""; - echo "
- - - diff --git a/admin/WebConsole/principal/colasacciones.php b/admin/WebConsole/principal/colasacciones.php index 7e9a2c97..6cc6d822 100644 --- a/admin/WebConsole/principal/colasacciones.php +++ b/admin/WebConsole/principal/colasacciones.php @@ -150,7 +150,7 @@ - '?> + '?> - + @@ -322,10 +322,10 @@ @@ -333,10 +333,10 @@ @@ -356,26 +356,26 @@
  +
  -
  - + +
  -
  - + +
  -
@@ -345,10 +345,10 @@
  - + +  
    -  
  - + +  
    -  
  - + +  
    -  
- - - + - + - CreaMenuContextual($XMLcontextual); @@ -406,7 +406,7 @@ ?> -campos["fechahorafin"],0)); - if ($fecha=="0000-00-00") $hora=""; + if ($fecha=="1970-01-01") $hora=""; $html.=''; $html.=''; list($fecha,$hora)=split(" ",substr($rs->campos["fechahorareg"],0)); - if ($fecha=="0000-00-00") $hora=""; + if ($fecha=="1970-01-01") $hora=""; $html.=''; $html.=''; } @@ -930,7 +930,7 @@ function escribeResumen($oA) } /* Descripción de la notificación (Descripción del error si se ha producido alguno) */ - $html.=''; + $html.=''; /* Estado */ $html.=''; @@ -1129,10 +1129,10 @@ function escribeCheck() echo'
 '.InvFecha($fecha).'  '.$hora.'  '.InvFecha($fecha).'  '.$hora.'  '.$rs->campos["descrinotificacion"].'  '.@$rs->campos["descrinotificacion"].'  
- TH height=15 align="center" colspan=14> + TH height=15 align="center" colspan=14> - + diff --git a/admin/WebConsole/principal/colasreservas.php b/admin/WebConsole/principal/colasreservas.php index a6ca90f7..e59ffe64 100644 --- a/admin/WebConsole/principal/colasreservas.php +++ b/admin/WebConsole/principal/colasreservas.php @@ -1,4 +1,4 @@ - - '?> - '?> + '?> + '?> - - - - + +

COMANDOS 
-

-

+
- -Conexion->Cerrar(); // Cierra la conexión ?> -Conexion->Cerrar(); // Cierra la conexión ?> + -

+

- - + +
 
- + - - + + - - + + - - + + - - + + - - + + - - + + @@ -171,8 +171,8 @@ function datosAulas($cmd,$idaula) ?>
>>  >>  >>  >>  >>  >>
- '; echo ' + src=""> +
 
- -    + '.$ubicacion.''; ?> - -
   -    + '. $nombreaula.''; echo ' '.$TbMsg[7].'  "> -
 
     -    + '; ?>
  -   + '.$puestos.''; ?> -    -    + '.$comentarios.''; ?>
-
   - '.$ip.'';?> +    + '.$ip.'';?>
   - '.$mac.'';?> +    + '.$mac.'';?>
   - '.$perfilhard.'';?> +    + '.$perfilhard.'';?>
- - -
 '.$nombreaula?>  -  '.$nombreaula?>  + '.$nombregrupoordenador.'
diff --git a/admin/WebConsole/principal/consolaremota.php b/admin/WebConsole/principal/consolaremota.php index 7ab72b5b..ea5dbf1c 100644 --- a/admin/WebConsole/principal/consolaremota.php +++ b/admin/WebConsole/principal/consolaremota.php @@ -1,4 +1,4 @@ - -'?> +'?> - > - > - > - > + > + > + > + > -


+


-  

+  

- + - '; ?> + + + + '; + } else { + echo ''; + else + echo 'disabled> '.$TbMsg['WARN_SCHEDULER'].''; + } + ?> + - -    + '.$router.''; else @@ -226,14 +244,27 @@ function abrir_ventana(URL){ - -    + '.$netmask.''; else echo ''; ?> + + + + '.$ntp.''; + } else { + echo '"; + } + ?> + @@ -254,9 +285,8 @@ function abrir_ventana(URL){ - -    + '.$modp2p.''; else { echo ' - -    + '.$timep2p.''; else echo ''; @@ -281,9 +310,8 @@ function abrir_ventana(URL){ - -    + - -    + '.$ipmul.''; else echo ''; @@ -309,9 +336,8 @@ function abrir_ventana(URL){ - -    + '.$pormul.''; else { echo ' - -    + '.$velmul.''; else echo ''; ?> - + +
   ('.$TbMsg['COMM_REMOTEACCESS'].')
  
 
   '; + if (exec("timedatectl status | awk -F'[:()]' '/Time.*zone/ {print $2}'", $out, $err)) { + echo '('.$TbMsg['COMM_DEFTIMEZONE'].': '.$out[0].')'; + } + echo "
  
  '; @@ -271,9 +301,8 @@ function abrir_ventana(URL){
  
  
  
  '; @@ -325,43 +351,64 @@ function abrir_ventana(URL){
  

+ + + - - - + + + - -    + '.TomaDato($cmd,$idcentro,'menus',$idmenu,'idmenu','descripcion').' '; else echo ''; ?> - + - -    + '.TomaDato($cmd,$idcentro,'repositorios',$idrepositorio,'idrepositorio','nombrerepositorio').' '; else echo ''; ?> + + + + '.$oglive.($cntDiff>0?' ('.$TbMsg[34]." ==> $cntDiff.)":"").' '; + } else { + echo '\n"; + } + ?> + - -    + '.TomaDato($cmd,$idcentro,'procedimientos',$idprocedimiento,'idprocedimiento','descripcion').' '; else echo ''; @@ -369,9 +416,8 @@ function abrir_ventana(URL){ - -    + '.TomaDato($cmd,$idcentro,'perfileshard',$idperfilhard,'idperfilhard','descripcion').' '; else echo ''; @@ -430,6 +476,8 @@ function TomaPropiedades($cmd,$ida) global $idaula; global $nombreaula; global $urlfoto; + global $inremotepc; + global $scheduler; global $cagnon; global $pizarra; global $ubicacion; @@ -449,6 +497,8 @@ function TomaPropiedades($cmd,$ida) global $gidprocedimiento; global $gidrepositorio; global $gidperfilhard; + global $oglive; + global $cntDiff; ###################### ADV global $router; global $netmask; @@ -460,6 +510,7 @@ function TomaPropiedades($cmd,$ida) global $pormul; global $velmul; ###################### Ramón + global $ntp; global $dns; global $proxy; ###################### UHU @@ -471,6 +522,8 @@ function TomaPropiedades($cmd,$ida) $idaula=0; $nombreaula=""; $urlfoto=""; + $inremotepc=false; + $scheduler=false; $cagnon=false; $pizarra=false; $ubicacion=""; @@ -502,6 +555,8 @@ function TomaPropiedades($cmd,$ida) $gidprocedimiento=0; $gidrepositorio=0; $gidperfilhard=0; + $oglive=""; + $cntDiff=0; $rs=new Recordset; $cmd->texto="SELECT aulas.*, COUNT(ordenadores.idordenador) AS numordenadores, @@ -512,7 +567,13 @@ function TomaPropiedades($cmd,$ida) GROUP_CONCAT(DISTINCT CAST( ordenadores.idperfilhard AS char( 11 ) ) ORDER BY ordenadores.idperfilhard SEPARATOR ',' ) AS idperfileshard, GROUP_CONCAT(DISTINCT CAST( ordenadores.idproautoexec AS char( 11 ) ) - ORDER BY ordenadores.idproautoexec SEPARATOR ',' ) AS idprocedimientos + ORDER BY ordenadores.idproautoexec SEPARATOR ',' ) AS idprocedimientos, + (SELECT COUNT(*) + FROM ordenadores + JOIN aulas USING(idaula) + WHERE aulas.idaula = $ida + AND aulas.oglivedir<>ordenadores.oglivedir) AS cntdiff, + IF(@@GLOBAL.event_scheduler='ON',1,0) AS scheduler FROM aulas LEFT OUTER JOIN ordenadores ON ordenadores.idaula = aulas.idaula WHERE aulas.idaula =".$ida." @@ -543,13 +604,18 @@ function TomaPropiedades($cmd,$ida) $modp2p=$rs->campos["modp2p"]; $timep2p=$rs->campos["timep2p"]; #################### Ramón + $ntp=$rs->campos["ntp"]; $dns=$rs->campos["dns"]; $proxy=$rs->campos["proxy"]; #################### UHU $validacion=$rs->campos["validacion"]; $paginalogin=$rs->campos["paginalogin"]; $paginavalidacion=$rs->campos["paginavalidacion"]; -###################### UHU +#################### Ramón + $inremotepc=$rs->campos["inremotepc"]; + $scheduler=$rs->campos["scheduler"]; + $oglive=$rs->campos["oglivedir"]; + $cntDiff=$rs->campos["cntdiff"]; $ordenadores=$rs->campos["numordenadores"]; $idmenu=$rs->campos["idmenus"]; @@ -573,5 +639,25 @@ function TomaPropiedades($cmd,$ida) } return(false); } + +//________________________________________________________________________________________________________ +// Recupera algunos datos de configuración de la base de datos +// Parametros: +// - cmd: comando ya operativo (con conexión abierta) +//________________________________________________________________________________________________________ +function TomaConfiguracion($cmd) { + global $scheduler; + + $rs=new Recordset; + $cmd->texto="SELECT IF(@@GLOBAL.event_scheduler='ON',1,0) AS scheduler"; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error al abrir recordset + if (!$rs->EOF) { + $scheduler=$rs->campos["scheduler"]; + $rs->Cerrar(); + return(true); + } + return(false); +} ?> diff --git a/admin/WebConsole/propiedades/propiedades_centros.php b/admin/WebConsole/propiedades/propiedades_centros.php index 37b6e8e2..c4f89fb2 100644 --- a/admin/WebConsole/propiedades/propiedades_centros.php +++ b/admin/WebConsole/propiedades/propiedades_centros.php @@ -1,4 +1,4 @@ - -Administración web de aulas +Administración web de aulas - '?> + + '?> + - - > - > -


-

+ + > + > +


+

  
  
  '.HTMLSELECT($cmd,$idcentro,'menus',$idmenu,'idmenu','descripcion',330).'
  '.HTMLSELECT($cmd,$idcentro,'repositorios',$idrepositorio,'idrepositorio','nombrerepositorio',330).'
  '; + exec("/opt/opengnsys/bin/oglivecli list", $data); + $ogliveList="ogLive=".$TbMsg['COMM_DEFOGLIVE'].($oglive=="ogLive"?" *":"").chr(13); + foreach ($data as $ogl) { + $ogl=preg_replace("/[0-9]* /","",$ogl); + $ogliveList.="$ogl=$ogl".($oglive==$ogl?" *":"").chr(13); + } + echo HTMLCTESELECT($ogliveList,"oglive","estilodesple"," ",$cntDiff==0?$oglive:" ",200); + if ($cntDiff > 0) { + echo ' '.$TbMsg[34]."   ==> $cntDiff\n"; + } + echo "
  '.HTMLSELECT($cmd,$idcentro,'procedimientos',$idprocedimiento,'idprocedimiento','descripcion',330).'
  '.HTMLSELECT($cmd,$idcentro,'perfileshard',$idperfilhard,'idperfilhard','descripcion',330).'
- - - - - + + + + - + '.$comentarios.''; else echo ''; ?> + + + \n". + " \n". + " \n". + " \n". + " \n". + " ". + " \n"; + } + ?>
   - +    +
   -   
 ".$TbMsg['DIR']." 
 *".$TbMsg['MSG_OGUNIT']."
- - -texto="SELECT * FROM centros WHERE idcentro=".$id; @@ -106,6 +127,7 @@ function TomaPropiedades($cmd,$id){ if (!$rs->EOF){ $nombrecentro=$rs->campos["nombrecentro"]; $comentarios=$rs->campos["comentarios"]; + $directorio=$rs->campos["directorio"]; $rs->Cerrar(); return(true); } diff --git a/admin/WebConsole/propiedades/propiedades_componentehardwares.php b/admin/WebConsole/propiedades/propiedades_componentehardwares.php index 927b7010..4cba86ad 100644 --- a/admin/WebConsole/propiedades/propiedades_componentehardwares.php +++ b/admin/WebConsole/propiedades/propiedades_componentehardwares.php @@ -1,4 +1,4 @@ - - '?> + '?>
- - > - > -


-

+ + > + > +


+

- ';?> -
   -    + '.$descripcion.''; else echo '
   -    + '.TomaDato($cmd,0,'tipohardwares',$idtipohardware,'idtipohardware','descripcion').''; else @@ -78,14 +78,14 @@ if ($opcion!=$op_alta){
- - - '?> + '?>
- - > - > -


-

+ + > + > +


+

- -    + '.$descripcion.''; else echo '';?> - -    + '.TomaDato($cmd,0,'tiposoftwares',$idtiposoftware,'idtiposoftware','descripcion').''; else @@ -76,13 +76,13 @@ if ($opcion!=$op_alta){ ?> - '; else echo ''; ?> - -    + '.TomaDato($cmd,0,'tiposos',$idtiposo,'idtiposo','descripcion').''; else @@ -93,14 +93,14 @@ if ($opcion!=$op_alta){
  
  
  
- - -Administración web de aulas +Administración web de aulas - '?> + + '?>
- > - > - > - > -


-

+ > + > + > + > +


+

- - - - - + + + + - '; ?> + + \n". + " \n". + " \n"; + } + ?>
   - +    +
   -    + '.$comentarios.''; else echo '
 ".$TbMsg['OGUNIT']." \n". + "
- -texto="SELECT * FROM entidades WHERE identidad=".$id; @@ -108,6 +126,7 @@ function TomaPropiedades($cmd,$id){ if (!$rs->EOF){ $nombreentidad=$rs->campos["nombreentidad"]; $comentarios=$rs->campos["comentarios"]; + $ogunit=$rs->campos["ogunit"]; $rs->Cerrar(); return(true); } diff --git a/admin/WebConsole/propiedades/propiedades_entornos.php b/admin/WebConsole/propiedades/propiedades_entornos.php index 6d99d337..2d21fa30 100644 --- a/admin/WebConsole/propiedades/propiedades_entornos.php +++ b/admin/WebConsole/propiedades/propiedades_entornos.php @@ -1,4 +1,4 @@ - - '?> - '?> + '?> + '?>
- + -


-

+


+

- - '; @@ -94,8 +94,8 @@ if ($opcion!=$op_alta){ -
   -    + '. $ipserveradm.''; } @@ -84,8 +84,8 @@ if ($opcion!=$op_alta){
   -    + '.$portserveradm.'  '; else echo '
   -    + '.$protoclonacion.''; else{ @@ -110,14 +110,14 @@ if ($opcion!=$op_alta){
- - - '?> + '?>
- > - > - > - > - - > - > -

 
-

+ > + > + > + > + + > + > +

 
+

- -
   +    '.$nombregrupo.''; else @@ -161,7 +161,7 @@ switch($literaltipo){
   +    '.$comentarios.''; else diff --git a/admin/WebConsole/propiedades/propiedades_imagenes.php b/admin/WebConsole/propiedades/propiedades_imagenes.php index bdd7b21c..036dc914 100644 --- a/admin/WebConsole/propiedades/propiedades_imagenes.php +++ b/admin/WebConsole/propiedades/propiedades_imagenes.php @@ -15,7 +15,10 @@ include_once("../includes/opciones.php"); include_once("../includes/CreaComando.php"); include_once("../includes/HTMLSELECT.php"); include_once("../includes/TomaDato.php"); +include_once("../includes/comunes.php"); +include_once("../includes/restfunctions.php"); include_once("../idiomas/php/".$idioma."/propiedades_imagenes_".$idioma.".php"); +include_once("../idiomas/php/".$idioma."/avisos_".$idioma.".php"); //________________________________________________________________________________________________________ if (isset($_POST["opcion"])) {$opcion=$_POST["opcion"];}else{$opcion=0;} // Recoge parametros @@ -34,12 +37,19 @@ $codpar=0; $idperfilsoft=0; $perfilsoft=""; $comentarios=""; +$inremotepc=""; +$scheduler=""; $grupoid=0; $litamb=""; $tipoimg=0; $idrepositorio=0; +$repoip=""; +$repokey=""; $fechacreacion=""; +$revision=0; $imagenid=0; +$validnombreca=""; +$validdescripcion=""; if (isset($_POST["validnombreca"])) {$opcion=$_POST["validnombreca"];}else{$validnombreca="";} // Recoge parametros if (isset($_POST["datospost"])) {$datospost=$_POST["datospost"];}else{$datospost=0;} // Recoge parametros if (isset($_GET["opcion"])) $opcion=$_GET["opcion"]; // Recoge parametros @@ -52,24 +62,29 @@ if (isset($_GET["tipoimg"])) $tipoimg=$_GET["tipoimg"]; //________________________________________________________________________________________________________ $cmd=CreaComando($cadenaconexion); // Crea objeto comando if (!$cmd) - Header('Location: '.$pagerror.'?herror=2'); // Error de conexión con servidor B.D. -if ($opcion!=$op_alta){ + header('Location: '.$pagerror.'?herror=2'); // Error de conexión con servidor B.D. +if ($opcion!=$op_alta) $resul=TomaPropiedades($cmd,$idimagen); - if (!$resul) - Header('Location: '.$pagerror.'?herror=3'); // Error de recuperación de datos. -} +else + $resul=TomaConfiguracion($cmd); +if (!$resul) + header('Location: '.$pagerror.'?herror=3'); // Error de recuperación de datos. -if ( $opcion == 1 && $datospost == 1) - { +if ($opcion == 1 && $datospost == 1) { if (isset($_POST["opcion"])) $opcion=$_POST["opcion"];// Recoge parametros + if (isset($_POST["idrepositorio"])) $idrepositorio=$_POST["idrepositorio"]; if (isset($_POST["idimagen"])) $idimagen=$_POST["idimagen"]; - if (isset($_POST["nombreca"])) - {$nombreca=$_POST["nombreca"];ValidaNombre($cmd,$nombreca);}if ($validnombreca != 1 ) {$validnombreca=0;} + if (isset($_POST["nombreca"])) { + $nombreca=$_POST["nombreca"]; + ValidaNombre($cmd,$nombreca,$idrepositorio); + } + if ($validnombreca != 1) {$validnombreca=0;} if (isset($_POST["ruta"])) $ruta=$_POST["ruta"]; - if (isset($_POST["descripcion"])) $descripcion=$_POST["descripcion"]; + if (isset($_POST["descripcion"])) {$descripcion=$_POST["descripcion"];} if (isset($_POST["grupoid"])) $grupoid=$_POST["grupoid"]; if (isset($_POST["idperfilsoft"])) $idperfilsoft=$_POST["idperfilsoft"]; if (isset($_POST["comentarios"])) $comentarios=$_POST["comentarios"]; + if (isset($_POST["inremotepc"])) $inremotepc=$_POST["inremotepc"]; if (isset($_POST["identificador"])) $idimagen=$_POST["identificador"]; if (isset($_POST["modelo"])) $numpar=$_POST["modelo"]; if (isset($_POST["numdisk"])) $numpar=$_POST["numdisk"]; @@ -80,9 +95,24 @@ if ( $opcion == 1 && $datospost == 1) if (isset($_POST["tipoimg"])) $tipoimg=$_POST["tipoimg"]; if (isset($_POST["fechacreacion"])) $fechacreacion=$_POST["fechacreacion"]; if (isset($_POST["litamb"])) $litamb=$_POST["litamb"]; - - } +// Solicitar datos del fichero de imagen a la API REST de su repositorio. +if ($opcion!=$op_alta and isset($repokey)) { + $repo[0]['url'] = "https://$repoip/opengnsys/rest/repository/image/$nombreca"; + $repo[0]['header'] = array('Authorization: '.$repokey); + $result = multiRequest($repo); + if ($result[0]['code'] === 200) { + $result = json_decode($result[0]['data']); + $imgpath = (@$result->type==="dir" ? @$result->name : @$result->name.".".@$result->type); + $imgsize = humanSize(@$result->size); + $imgbackup = @$result->backedup; + $imgbksize = isset($result->backupsize) ? humanSize($result->backupsize) : 0; + $imglock = @$result->locked; + } else { + $imgpath = ""; + } +} + //________________________________________________________________________________________________________ ?> @@ -94,21 +124,21 @@ if ( $opcion == 1 && $datospost == 1) - '?> + '?>
- + - - - - - + + + + + -


- +


+

- - '; + } ?> - + - - + - - - - '.$tipopar.' ('.dechex($codpar).') -  '; - else - echo ''; - ?> - - - + - - + - + + + + '; + } else { + echo ''; + else + echo 'disabled> '.$TbMsg['WARN_SCHEDULER'].''; + } + ?> + + + - + - + - + - - + - '; - + '; + } ?> - + + + + + + + + + + + + + + + + +EOT; + if ($imgbackup) { + print <<< EOT + + + + +EOT; + } + if ($imglock) { + print <<< EOT + + + + +EOT; + } + } + ?> + '; + } + }?>
   -    + '.$nombreca.'  '; else @@ -140,18 +170,21 @@ if ( $opcion == 1 && $datospost == 1)
   - '.$descripcion.''; - else - echo '';?> +    + '.$descripcion.' +  '; + } else { + echo ''; + if ($validnombreca == 0 && $validdescripcion == 1){echo ' '.$TbMsg[22].'';} + echo '
   -    + '.TomaDato($cmd,$idcentro,'imagenes',$imagenid,'imagenid','descripcion').'  '; else @@ -159,24 +192,12 @@ if ( $opcion == 1 && $datospost == 1) tipo=".$IMAGENES_BASICAS,"imagenid").''; ?>
  '.HTMLSELECT($cmd,0,'tipospar',$codpar,'codpar',"CONCAT(CASE WHEN codpar BETWEEN 1 AND 255 THEN '1-MSDOS' WHEN codpar BETWEEN 256 AND 65535 THEN '2-GPT' ELSE codpar END,': ',tipopar,' (',HEX(codpar),')')",170,"","","clonable=1").'
   -    + '.$nombrerepositorio.'  '; else @@ -184,60 +205,125 @@ if ( $opcion == 1 && $datospost == 1) ?>
   -    + '.$ruta.'  '; else echo '';?>
   -    + '.$comentarios.''; else echo ''; ?>
   ('.$TbMsg['COMM_REMOTEACCESS'].')
      
    -   -    + +
    -   0 ? "(r$revision)" : "") ?> +
   - '.$perfilsoft.' -     +  '.$perfilsoft.' +  '; + } else { + echo ''.HTMLSELECT($cmd,$idcentro,'perfilessoft',$idperfilsoft,'idperfilsoft','descripcion',300).'
   
Datos del repositorio
Camino /$imgpath 
Tamaño $imgsize 
Copia de seguridad $imgbksize 
Bloqueada Atención: la imagen está bloqueda por operación de uso exclusivo 
'.$TbMsg["WARN_SOURCE_PATH"].'
- @@ -251,20 +337,20 @@ if ($validnombreca=="0"){ echo ''; - } +} if ($validnombreca=="1"){ echo ''; +} - } include_once("../includes/opcionesbotonesop.php"); //________________________________________________________________________________________________________ ?> -texto="SELECT imagenes.*, tipospar.tipopar, repositorios.nombrerepositorio, perfilessoft.descripcion AS perfilsoft, CONCAT (ordenadores.nombreordenador,' (',aulas.nombreaula,')') AS modelo + $cmd->texto="SELECT imagenes.*, tipospar.tipopar, repositorios.nombrerepositorio, + repositorios.ip, repositorios.apikey, + perfilessoft.descripcion AS perfilsoft, nombreso AS sistoperativo, + CONCAT (ordenadores.nombreordenador,' (',aulas.nombreaula,')') AS modelo, + IF(@@GLOBAL.event_scheduler='ON',1,0) AS scheduler FROM imagenes LEFT OUTER JOIN tipospar ON tipospar.codpar=imagenes.codpar LEFT OUTER JOIN repositorios ON repositorios.idrepositorio=imagenes.idrepositorio LEFT OUTER JOIN perfilessoft ON perfilessoft.idperfilsoft=imagenes.idperfilsoft LEFT OUTER JOIN ordenadores ON ordenadores.idordenador=imagenes.idordenador LEFT OUTER JOIN aulas ON ordenadores.idaula=aulas.idaula + LEFT OUTER JOIN nombresos ON perfilessoft.idnombreso=nombresos.idnombreso WHERE imagenes.idimagen=".$idmagen; $rs->Comando=&$cmd; if (!$rs->Abrir()) return(0); // Error al abrir recordset @@ -308,6 +405,8 @@ function TomaPropiedades($cmd,$idmagen){ $descripcion=$rs->campos["descripcion"]; $idperfilsoft=$rs->campos["idperfilsoft"]; $comentarios=$rs->campos["comentarios"]; + $inremotepc=$rs->campos["inremotepc"]; + $scheduler=$rs->campos["scheduler"]; $modelo=$rs->campos["modelo"]; $numdisk=$rs->campos["numdisk"]; $numpar=$rs->campos["numpar"]; @@ -315,14 +414,37 @@ function TomaPropiedades($cmd,$idmagen){ $codpar=$rs->campos["codpar"]; $idrepositorio=$rs->campos["idrepositorio"]; $nombrerepositorio=$rs->campos["nombrerepositorio"]; + $repoip=$rs->campos["ip"]; + $repokey=$rs->campos["apikey"]; $perfilsoft=$rs->campos["perfilsoft"]; + $sistoperativo=$rs->campos["sistoperativo"]; $imagenid=$rs->campos["imagenid"]; $fechacreacion=$rs->campos["fechacreacion"]; + $revision=$rs->campos["revision"]; $rs->Cerrar(); return(true); } - else + return(false); +} + +//________________________________________________________________________________________________________ +// Recupera los algunos datos de configuración de la base de datos +// Parametros: +// - cmd: comando ya operativo (con conexión abierta) +//________________________________________________________________________________________________________ +function TomaConfiguracion($cmd) { + global $scheduler; + + $rs=new Recordset; + $cmd->texto="SELECT IF(@@GLOBAL.event_scheduler='ON',1,0) AS scheduler"; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(0); // Error al abrir recordset + if (!$rs->EOF){ + $scheduler=$rs->campos["scheduler"]; + $rs->Cerrar(); return(true); + } + return(false); } //________________________________________________________________________________________________________ @@ -330,25 +452,55 @@ function TomaPropiedades($cmd,$idmagen){ // Comprueba Nombre de la imagen // Parametros: // - cmd: Una comando ya operativo (con conexión abierta) -// - id: El identificador de la imagen +// - nombreca: Nombre de la imagen +// - descripcion: Descripcion de la imagen //________________________________________________________________________________________________________ -function ValidaNombre($cmd,$nombreca){ +function ValidaNombre($cmd,$nombreca,$idrepositorio){ global $nombreca; global $validnombreca; + global $idrepositorio; - $rs=new Recordset; + $rs=new Recordset; $cmd->texto="SELECT * from imagenes WHERE nombreca='$nombreca'"; - $rs->Comando=&$cmd; + $rs->Comando=&$cmd; if (!$rs->Abrir()) return(0); // Error al abrir recordset - $rs->Primero(); + $rs->Primero(); if (!$rs->EOF){ $nombrecabase=$rs->campos["nombreca"]; - if ( $nombrecabase == $nombreca ) + $idrepositoriobase=$rs->campos["idrepositorio"]; + if ( $nombrecabase == $nombreca && $idrepositoriobase == $idrepositorio) {$validnombreca="1";}else{$validnombreca="0";} - } - $rs->Cerrar(); + } + $rs->Cerrar(); +} + +//________________________________________________________________________________________________________ +// Comprueba Descripcion del nombre canónico +// Parametros: +// - cmd: Una comando ya operativo (con conexión abierta) +// - nombreca: Nombre de la imagen +// - descripcion: Descripcion de la imagen +//________________________________________________________________________________________________________ + +function ValidaDescripcion($cmd,$nombreca,$descripcion){ + global $nombreca; + global $validnombreca; + global $descripcion; + global $validdescripcion; + $rs=new Recordset; + $cmd->texto="SELECT * from imagenes WHERE nombreca='$nombreca'"; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(0); // Error al abrir recordset + $rs->Primero(); + if (!$rs->EOF){ + $nombrecabase=$rs->campos["nombreca"]; + $descripcionbase=$rs->campos["descripcion"]; + if ( $nombrecabase == $nombreca && "$descripcionbase" == "$descripcion" ) + {$validdescripcion="1";}else{$validdescripcion="0";} + } + $rs->Cerrar(); } ?> diff --git a/admin/WebConsole/propiedades/propiedades_menus.php b/admin/WebConsole/propiedades/propiedades_menus.php index efe3575b..8e996841 100644 --- a/admin/WebConsole/propiedades/propiedades_menus.php +++ b/admin/WebConsole/propiedades/propiedades_menus.php @@ -56,19 +56,19 @@ if ($opcion!=$op_alta){ - '?> + '?>
- > - > - > + > + > + >


- + '.$descripcion.''; else @@ -76,7 +76,7 @@ if ($opcion!=$op_alta){ - + '.$titulo.''; else @@ -84,7 +84,7 @@ if ($opcion!=$op_alta){ - + '.TomaDato($cmd,0,'iconos',$idurlimg,'idicono','descripcion').' '; else @@ -106,6 +106,10 @@ if ($opcion!=$op_alta){ $tbresolucion[792]="1024x768 24bits"; $tbresolucion[795]="1280x1024 24bits"; $tbresolucion[799]="1600x1200 24bits"; + $tbresolucion[814]="800x600 32bits"; + $tbresolucion[824]="1024x768 32bits"; + $tbresolucion[829]="1280x1024 32bits"; + $tbresolucion[834]="1600x1200 32bits"; if (empty ($tbresolucion[$resolucion])) { $res = $resolucion; } else { @@ -124,18 +128,27 @@ if ($opcion!=$op_alta){ $parametros.="789=800x600 24bits".chr(13); $parametros.="792=1024x768 24bits".chr(13); $parametros.="795=1280x1024 24bits".chr(13); - $parametros.="799=1600x1200 24bits"; + $parametros.="799=1600x1200 24bits".chr(13); + $parametros.="814=800x600 32bits".chr(13); + $parametros.="824=1024x768 32bits".chr(13); + $parametros.="829=1280x1024 32bits".chr(13); + $parametros.="834=1600x1200 32bits"; } else { // Kernel 3.7 y superior usa parámetro "video". - $parametros ="uvesafb:800x600-16=800x600, 16bit".chr(13); + $parametros ="uvesafb:D=".$TbMsg["PROP_DEFAULT"].chr(13); + $parametros.="uvesafb:800x600-16=800x600, 16bit".chr(13); $parametros.="uvesafb:800x600-24=800x600, 24bit".chr(13); + $parametros.="uvesafb:800x600-32=800x600, 32bit".chr(13); $parametros.="uvesafb:1024x768-16=1024x768, 16bit".chr(13); $parametros.="uvesafb:1024x768-24=1024x768, 24bit".chr(13); + $parametros.="uvesafb:1024x768-32=1024x768, 32bit".chr(13); $parametros.="uvesafb:1152x864-16=1152x864, 16bit".chr(13); $parametros.="uvesafb:1280x1024,16=1280x1024, 16bit".chr(13); $parametros.="uvesafb:1280x1024,24=1280x1024, 24bit".chr(13); + $parametros.="uvesafb:1280x1024,32=1280x1024, 32bit".chr(13); + $parametros.="uvesafb:1600x1200,16=1600x1200, 16bit".chr(13); $parametros.="uvesafb:1600x1200,24=1600x1200, 24bit".chr(13); - $parametros.="uvesafb:1600x1200,24=1600x1200, 16bit"; + $parametros.="uvesafb:1600x1200,32=1600x1200, 32bit"; } echo ''; } @@ -143,7 +156,7 @@ if ($opcion!=$op_alta){ - + '.$comentarios.' '; else @@ -156,7 +169,7 @@ if ($opcion!=$op_alta){
    
    
     '.HTMLCTESELECT($parametros,"resolucion","estilodesple","",$resolucion,150).'
    
- + @@ -178,8 +191,8 @@ if ($opcion!=$op_alta){ - -     + '.$htmlmenupub.''; else echo ''; @@ -187,7 +200,7 @@ if ($opcion!=$op_alta){ - + @@ -208,8 +221,8 @@ if ($opcion!=$op_alta){ ?> - -     + '.$htmlmenupri.''; else echo ''; diff --git a/admin/WebConsole/propiedades/propiedades_ordenadores.php b/admin/WebConsole/propiedades/propiedades_ordenadores.php index b4ebc196..57444a16 100644 --- a/admin/WebConsole/propiedades/propiedades_ordenadores.php +++ b/admin/WebConsole/propiedades/propiedades_ordenadores.php @@ -24,6 +24,7 @@ $opciones=array($TbMsg[0],$TbMsg[1],$TbMsg[2],$TbMsg[3]); //________________________________________________________________________________________________________ $idordenador=0; $nombreordenador=""; +$numserie=""; $ip=""; $mac=""; $idperfilhard=0; @@ -81,8 +82,8 @@ function abrir_ventana(URL){ -


-

+


+

    
   
    
   
@@ -97,7 +98,7 @@ function abrir_ventana(URL){ $fotomenu=$fotoordenador; $dirfotos="../images/fotos"; ?> - '; ?> + + + + '.(isset($numserie)?$numserie:$TbMsg["WARN_NOTDETECTED"]).''; + } else { + echo '\n"; + } + ?> + - -    + '.$fotoordenador.''; else { @@ -144,24 +159,24 @@ function abrir_ventana(URL){ while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") {?> - - "> +        - + - - -    + '.TomaDato($cmd,$idcentro,'perfileshard',$idperfilhard,'idperfilhard','descripcion').''; else @@ -170,18 +185,52 @@ function abrir_ventana(URL){ - -    + '.TomaDato($cmd,$idcentro,'repositorios',$idrepositorio,'idrepositorio','nombrerepositorio').''; else echo ''; ?> + + + +texto="SELECT * FROM ordenadores WHERE idordenador=".$idordenador; +$rs=new Recordset; +$rs->Comando=&$cmd; +if (!$rs->Abrir()) return(true); // Error al abrir recordset +$rs->Primero(); +if (!$rs->EOF){ + $bdogLive=$rs->campos["oglivedir"]; +} +$rs->Cerrar(); + +if ($opcion==$op_eliminacion){ + echo ''; +}else{ + exec("bash /opt/opengnsys/bin/oglivecli list", $listogcli); + echo ' - -    + '.TomaDato($cmd,$idcentro,'menus',$idmenu,'idmenu','descripcion').''; else @@ -190,8 +239,8 @@ function abrir_ventana(URL){ - -    + '.TomaDato($cmd,$idcentro,'procedimientos',$idprocedimiento,'idprocedimiento','descripcion').' '; else @@ -200,7 +249,7 @@ function abrir_ventana(URL){ - + '.$netiface.''; } else { @@ -215,7 +264,7 @@ function abrir_ventana(URL){ - + '.$netdriver.''; } else { @@ -230,7 +279,7 @@ function abrir_ventana(URL){ - + '.$validacion.''; } else { @@ -242,7 +291,7 @@ function abrir_ventana(URL){ ?> - + '.$paginalogin.''; else @@ -250,7 +299,7 @@ function abrir_ventana(URL){ ?> - + '.$paginavalidacion.''; else @@ -280,9 +329,12 @@ include_once("../includes/opcionesbotonesop.php"); opcion=$op_alta if ($opcion!=$op_alta) { + echo '
'; + echo ''; + echo '
'; echo '
'; echo ''; @@ -302,6 +354,7 @@ if ($opcion!=$op_alta) { function TomaPropiedades($cmd,$id){ global $idordenador; global $nombreordenador; + global $numserie; global $ip; global $mac; global $fotoordenador; @@ -325,6 +378,7 @@ function TomaPropiedades($cmd,$id){ $rs->Primero(); if (!$rs->EOF){ $nombreordenador=$rs->campos["nombreordenador"]; + $numserie=$rs->campos["numserie"]; $ip=$rs->campos["ip"]; $mac=$rs->campos["mac"]; $idperfilhard=$rs->campos["idperfilhard"]; diff --git a/admin/WebConsole/propiedades/propiedades_ordenadorestandar.php b/admin/WebConsole/propiedades/propiedades_ordenadorestandar.php index 815670f6..6decd954 100644 --- a/admin/WebConsole/propiedades/propiedades_ordenadorestandar.php +++ b/admin/WebConsole/propiedades/propiedades_ordenadorestandar.php @@ -1,4 +1,4 @@ - - '?> + '?> -

 :
-

+

 :
+

+ (150X110)-(jpg - gif - png) ---- '.$TbMsg[5091].'>
'; @@ -124,10 +125,24 @@ function abrir_ventana(URL){ echo '
  '; + if (empty($numserie)) { + echo $TbMsg["WARN_NOTDETECTED"]; + } + echo "
  
  
  '.HTMLSELECT($cmd,$idcentro,'repositorios',$idrepositorio,'idrepositorio','nombrerepositorio',250).'
  '.$bdogLive.''."\n"; +} +?> +
  
  
    
    
   
    
    
- - - - - - - @@ -112,22 +112,22 @@ if ($opcion!=$op_alta){
   -    + '; ?>
   -    + '; ?>
   -    + '; ?>
   -    + '.HTMLSELECT($cmd,$idcentro,'perfileshard',$idperfilhard,'idperfilhard','descripcion',250).''; ?>
   -    + '.HTMLSELECT($cmd,$idcentro,'repositorios',$idrepositorio,'idrepositorio','nombrerepositorios',250).''; ?>
   -    + '; ?>
   -    + '; ?>
- + - + - +
 



 
 
   
-
- - - - -


-

+ + + + + +


+

- + '.$descripcion.''; else @@ -78,30 +82,18 @@ if ($opcion!=$op_alta){ echo ''; ?> - - - - $winboot"; - else { - $params = "reboot=".$TbMsg["HARD_REBOOT"].chr(13); - $params.= "kexec=".$TbMsg["HARD_KEXEC"]; - echo ""; - } - ?> -
    
  * ".HTMLCTESELECT($params,"winboot","estilodesple","","$winboot",110)."
- - - '?> + '?>
- > - > - > - > -


-

+ > + > + > + > +


+

- -    + '.$descripcion.''; else echo '';?> - + - -    + '.$comentarios.''; else echo ''; @@ -79,14 +79,14 @@ if ($opcion!=$op_alta){
  
 Images: 

 Images: 
  
- - - '?> + '?>
- > - > - > -


-

+ > + > + > +


+

- ';?> - '; @@ -76,14 +76,14 @@ if ($opcion!=$op_alta){
   -    + '.$descripcion.''; else echo '
   -    + '.$comentarios.''; else echo '
- -texto="SELECT * FROM repositorios WHERE idrepositorio=$idrepositorio"; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(true); // Error al abrir recordset - $rs->Primero(); - if (!$rs->EOF){ - $nombrerepositorio=$rs->campos["nombrerepositorio"]; - $iprepositorio=$rs->campos["ip"]; - } - $rs->Cerrar(); - -if ($iprepositorio == $ipservidor) -{ - $repolocal="si"; - $espaciorepo=exec("df -h /opt/opengnsys/images"); - $espaciorepo=split(" ",$espaciorepo); - for ($j=0;$jdirectory; + $totalrepo = humanSize($result->disk->total); + $librerepo = humanSize($result->disk->free); + $ocupadorepo = humanSize($result->disk->total - $result->disk->free); + $porcentajerepo = 100 - floor(100 * $result->disk->free / $result->disk->total); + $repoOus = $result->ous; + $repoImages = $result->images; + $repoWithApi = true; + } else { + // Error de acceso a la API REST. + $repoWithApi = false; + $repoImages = null; } +} else { + // Error de acceso a la API REST. + $repoWithApi = false; + $repoImages = null; } -else{ - $repolocaL="no"; - } //######################################################################### ?> @@ -88,104 +82,141 @@ else{ - '?> + '?>
- - - - + + + + -


-

+


+

- + - '; + echo ''; ?> - + - + - '; + echo''; ?> - + - '; + else + echo''; ?> - + - '; + '; + ?> + + + + '; ?> - +
   -    + '.$nombrerepositorio.''; else - echo '
- -
 Ordenadores: 
+ +
 Ordenadores: 
   -    + '.$ip.''; else - echo'
   -    + '.$puertorepo.''; - else - echo'
   - '.$comentarios.''; - else - echo '   + '.$apiKeyRepo.''; + else + echo'
   + '.$comentarios.''; + else + echo '
- + - + - - - - - + + + + + \n"; + +echo "\n"; + foreach($repoImages as $image){ + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo "\n"; + } + foreach($repoOus as $ou) { + foreach($ou->images as $image) { + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo "\n"; + } + } + } + ?> - +
   -    -    -    +    +    +    +   
                
".$TbMsg['MSG_CONTENT']." $repodir
".$TbMsg['MSG_IMAGE']." (".$TbMsg['MSG_TYPE'].")".$TbMsg['MSG_SIZE']."".$TbMsg['MSG_MODIFIED']."".$TbMsg['MSG_PERMISSIONS']."
".$image->name." (".$image->type.")".humanSize($image->size)."".$image->modified."".$image->mode."
".$ou->subdir." / ".$image->name." (".$image->type.")".$image->size." bytes".$image->modified."".$image->mode."
 '.$TbMsg[15].'
'.$TbMsg[16] ?>
+
- -campos["ip"]; $comentarios=$rs->campos["comentarios"]; $puertorepo=$rs->campos["puertorepo"]; + $apiKeyRepo=$rs->campos["apikey"]; // $ordenadores=$rs->campos["numordenadores"]; } $rs->Cerrar(); diff --git a/admin/WebConsole/propiedades/propiedades_reservas.php b/admin/WebConsole/propiedades/propiedades_reservas.php index 153e56c7..1cf4f79c 100644 --- a/admin/WebConsole/propiedades/propiedades_reservas.php +++ b/admin/WebConsole/propiedades/propiedades_reservas.php @@ -1,4 +1,4 @@ - - '?> + '?>
- > - > - > - > -


-

+ > + > + > + > +


+

- -    + '.$descripcion.''; else echo '';?> - -    + '.$solicitante.''; else echo ''; @@ -87,8 +87,8 @@ if ($opcion!=$op_alta){ - -    + '.$email.''; else echo ''; @@ -96,8 +96,8 @@ if ($opcion!=$op_alta){ - -    + '.TomaDato($cmd,0,'estatus',$idestatus,'idestatus','descripcion').''; else @@ -106,8 +106,8 @@ if ($opcion!=$op_alta){ - -    + '.TomaDato($cmd,$idcentro,'aulas',$idaula,'idaula','nombreaula').''; else @@ -116,8 +116,8 @@ if ($opcion!=$op_alta){ - -    + '.TomaDato($cmd,$idcentro,'imagenes',$idimagen,'idimagen','descripcion').''; else @@ -126,8 +126,8 @@ if ($opcion!=$op_alta){ - -    + '.TomaDato($cmd,$idcentro,'tareas',$idtarea,'idtarea','descripcion').''; else @@ -136,8 +136,8 @@ if ($opcion!=$op_alta){ - -    + '.TomaDato($cmd,$idcentro,'trabajos',$idtrabajo,'idtrabajo','descripcion').''; else @@ -145,14 +145,14 @@ if ($opcion!=$op_alta){ ?> - - -    +   ('.$TbMsg[12+$estado].')'; else{ echo ' - '; @@ -184,14 +184,14 @@ if ($opcion!=$op_alta){
  
  
  
  
  
  
  
  
  '; @@ -174,8 +174,8 @@ if ($opcion!=$op_alta){
   -    + '.$comentarios.''; else echo '
- - - '?> + '?>
- > - > - > - > -


-

+ > + > + > + > +


+

- ';?> - '; @@ -81,8 +81,8 @@ if ($opcion!=$op_alta){ - -
   -    + '.$descripcion.''; else echo '
   -    + '.$comentarios.''; else echo '
   -    +
   -    + '.$textambito.''; @@ -117,14 +117,14 @@ if ($opcion!=$op_alta){
- - - '?> + '?>
- > - > - > -


-

+ > + > + > +


+

- ';?> -
   -    + '.$descripcion.''; else echo '
   -    + '.TomaDato($cmd,0,'iconos',basename($urlimg),'urlicono','urlicono',0).''; else @@ -80,14 +80,14 @@ if ($opcion!=$op_alta){
- - - '?> + '?>
- > - > -


-

+ > + > +


+

- - '; @@ -75,14 +75,14 @@ else
  - ';?> +   + ';?>
   -    + '.$comentarios.''; else echo '
- - - '?> + '?>
- > - > - > - > + > + > + > + > -


-

+


+

- - - - - + + + + - - - - - + + + + + + + + + + + - - - - - + + + + - - - - - + + + + - - - - - - + + + + + + + + + + + + + + + + + + +
     - +      + - +
   - + +   **** + +
  **** +
   - +    +
   - +    +
    
  
@@ -138,18 +163,17 @@ switch($idtipousuario){ if ($idusuario==1){ ///* - echo ''; - echo ''; - echo ''; - echo '
'; - echo ''; - echo ''; - echo '
 '.$TbMsg[14].$TbMsg[15].$TbMsg[16].$TbMsg[17].'
'.$nombreambito.$TbMsg[23].'
'.$TbMsg[24].' 
'; + echo ''; + echo ''; + echo ''; + echo ''; + echo '
 '.$TbMsg[14].$TbMsg[15].''.$TbMsg[16].' 
'; + echo '

'; //*/ } ?> - -Primero(); if (!$rs->EOF){ $usuario=$rs->campos["usuario"]; - $pasguor=$rs->campos["pasguor"]; $nombre=$rs->campos["nombre"]; $email=$rs->campos["email"]; - $idambito=$rs->campos["idambito"]; + $apikey=$rs->campos["apikey"]; $ididioma=$rs->campos["ididioma"]; $idtipousuario=$rs->campos["idtipousuario"]; $rs->Cerrar(); diff --git a/admin/WebConsole/rest/common.php b/admin/WebConsole/rest/common.php new file mode 100644 index 00000000..8d192035 --- /dev/null +++ b/admin/WebConsole/rest/common.php @@ -0,0 +1,292 @@ +response->getStatus() . ": " . + $app->request->getMethod() . " " . + $app->request->getPathInfo() . ": $message\n", + FILE_APPEND); + } +} + +/** + * @brief Compose JSON response. + * @param int status Status code for HTTP response. + * @param array response Response data. + * @param int opts Options to encode JSON data. + * @return string JSON response. + */ +function jsonResponse($status, $response, $opts=0) { + $app = \Slim\Slim::getInstance(); + // HTTP status code. + $app->status($status); + // Content-type HTTP header. + $app->contentType('application/json; charset=utf-8'); + // JSON response. + echo json_encode($response, $opts); +} + +/** + * @brief Print immediately JSON response to continue processing. + * @param int status Status code for HTTP response. + * @param array response Response data. + * @param int opts Options to encode JSON data. + * @return string JSON response. + */ +function jsonResponseNow($status, $response, $opts=0) { + // Flush buffer. + ob_end_clean(); + ob_end_flush(); + header("Connection: close"); + // Compose headers and content. + http_response_code((int)$status); + header('Content-type: application/json; charset=utf-8'); + ignore_user_abort(); + ob_start(); + echo json_encode($response, $opts); + $size = ob_get_length(); + header("Content-Length: $size"); + // Print content. + ob_end_flush(); + flush(); + session_write_close(); +} + +/** + * @brief Validate API key included in "Authorization" HTTP header. + * @return JSON response on error. + */ +function validateApiKey() { + global $cmd; + global $userid; + $response = array(); + $app = \Slim\Slim::getInstance(); + // Read Authorization HTTP header. + if (! empty($_SERVER['HTTP_AUTHORIZATION'])) { + // Assign user id. that match this key to global variable. + $apikey = htmlspecialchars($_SERVER['HTTP_AUTHORIZATION']); + $cmd->texto = "SELECT idusuario + FROM usuarios + WHERE apikey='$apikey' LIMIT 1"; + $rs=new Recordset; + $rs->Comando=&$cmd; + if ($rs->Abrir()) { + $rs->Primero(); + if (!$rs->EOF){ + // Fetch user id. + $userid = $rs->campos["idusuario"]; + } else { + // Credentials error. + $response['message'] = 'Login failed. Incorrect credentials'; + jsonResponse(401, $response); + $app->stop(); + } + $rs->Cerrar(); + } else { + // Database error. + $response['message'] = "An error occurred, please try again"; + jsonResponse(500, $response); + } + } else { + // Error: missing API key. + $response['message'] = 'Missing API key'; + jsonResponse(400, $response); + $app->stop(); + } +} + +/** + * @brief Check if parameter is set and print error messages if empty. + * @param string param Parameter to check. + * @return boolean "false" if parameter is null, otherwise "true". + */ +function checkParameter($param) { + if (isset($param)) { + return true; + } else { + // Print error message. + $response['message'] = 'Parameter not found'; + jsonResponse(400, $response); + return false; + } +} + +/** + * @brief Check if all parameters are positive integer numbers. + * @param int id ... Identificators to check (variable number of parameters). + * @return boolean "true" if all ids are int>0, otherwise "false". + */ +function checkIds() { + $opts = Array('options' => Array('min_range' => 1)); // Check for int>0 + foreach (func_get_args() as $id) { + if (filter_var($id, FILTER_VALIDATE_INT, $opts) === false) { + return false; + } + } + return true; +} + +/** + * @fn sendCommand($serverip, $serverport, $reqframe, &$values) + * @brief Send a command to an OpenGnsys ogAdmServer and get request. + * @param string serverip Server IP address. + * @param string serverport Server port. + * @param string reqframe Request frame (field's separator is "\r"). + * @param array values Response values (out parameter). + * @return boolean "true" if success, otherwise "false". + */ +function sendCommand($serverip, $serverport, $reqframe, &$values) { + global $LONCABECERA; + global $LONHEXPRM; + + // Connect to server. + $respvalues = ""; + $connect = new SockHidra($serverip, $serverport); + if ($connect->conectar()) { + // Send request frame to server. + $result = $connect->envia_peticion($reqframe); + if ($result) { + // Parse request frame. + $respframe = $connect->recibe_respuesta(); + $connect->desconectar(); + $paramlen = hexdec(substr($respframe, $LONCABECERA, $LONHEXPRM)); + $params = substr($respframe, $LONCABECERA+$LONHEXPRM, $paramlen); + // Fetch values and return result. + $values = extrae_parametros($params, "\r", '='); + return ($values); + } else { + // Return with error. + return (false); + } + } else { + // Return with error. + return (false); + } +} + +/** + * @brief Show custom message for "not found" error (404). + */ +$app->notFound(function() { + echo "REST route not found."; + } +); + +/** + * @brief Hook to write a REST init log message, if debug is enabled. + * @warning Message will be written in REST log file. + */ +$app->hook('slim.before', function() use ($app) { + if ($app->settings['debug']) + writeRestLog("Init."); + } +); + +/** + * @brief Hook to write an error log message and a REST exit log message if debug is enabled. + * @warning Error message will be written in web server's error file. + * @warning REST message will be written in REST log file. + */ +$app->hook('slim.after', function() use ($app) { + if ($app->response->getStatus() != 200 ) { + // Compose error message (truncating long lines). + $app->log->error(date(DATE_ISO8601) . ': ' . + $app->getName() . ': ' . + $_SERVER['REMOTE_ADDR'] . ": " . + (isset($userid) ? $userid : "-") . ": " . + $app->response->getStatus() . ': ' . + $app->request->getMethod() . ' ' . + $app->request->getPathInfo() . ': ' . + substr($app->response->getBody(), 0, 100)); + } + if ($app->settings['debug']) + writeRestLog("Exit."); + } +); + + +// Common routes. + +/** + * @brief Get general server information + * @note Route: /info, Method: GET + * @param no + * @return JSON object with basic server information (version, services, etc.) + */ +$app->get('/info', function() { + // Reading version file. + @list($project, $version, $release) = explode(' ', file_get_contents('/opt/opengnsys/doc/VERSION.txt')); + $response['project'] = trim($project); + $response['version'] = trim($version); + $response['release'] = trim($release); + // Getting actived services. + @$services = parse_ini_file('/etc/default/opengnsys'); + $response['services'] = Array(); + if (@$services["RUN_OGADMSERVER"] === "yes") { + array_push($response['services'], "server"); + $hasOglive = true; + } + if (@$services["RUN_OGADMREPO"] === "yes") array_push($response['services'], "repository"); + if (@$services["RUN_BTTRACKER"] === "yes") array_push($response['services'], "tracker"); + // Reading installed ogLive information file. + if ($hasOglive === true) { + $data = json_decode(@file_get_contents('/opt/opengnsys/etc/ogliveinfo.json')); + if (isset($data->oglive)) { + $response['oglive'] = $data->oglive; + } + } + jsonResponse(200, $response); + } +); + +/** + * @brief Get the server status + * @note Route: /status, Method: GET + * @param no + * @return JSON object with all data collected from server status (RAM, %CPU, etc.). + */ +$app->get('/status', function() { + // Getting memory and CPU information. + exec("awk '$1~/Mem/ {print $2}' /proc/meminfo",$memInfo); + $memInfo = array("total" => $memInfo[0], "used" => $memInfo[1]); + $cpuInfo = exec("awk '$1==\"cpu\" {printf \"%.2f\",($2+$4)*100/($2+$4+$5)}' /proc/stat"); + $cpuModel = exec("awk -F: '$1~/model name/ {print $2}' /proc/cpuinfo"); + $response["memInfo"] = $memInfo; + $response["cpu"] = array("model" => trim($cpuModel), "usage" => $cpuInfo); + jsonResponse(200, $response); + } +); +?> diff --git a/admin/WebConsole/rest/index.php b/admin/WebConsole/rest/index.php new file mode 100644 index 00000000..51f00dec --- /dev/null +++ b/admin/WebConsole/rest/index.php @@ -0,0 +1,75 @@ + 'production', ... ); +$app = new \Slim\Slim(array( + 'mode' => 'production', + 'log.enabled' => true, + 'log.level' => \Slim\Log::ERROR, + 'debug' => false)); +$app->setName('opengnsys'); + +// Global variables. +$userid = NULL; // User id. with access to REST API. + +// Common funtions and routes. +include("common.php"); + +// Check if services are running. +$config = parse_ini_file("/etc/default/opengnsys"); + +// If server is running, include its routes and OGAgent push routes. +if ($config['RUN_OGADMSERVER'] === "yes") { + include("server.php"); + include("ogagent.php"); + include("remotepc.php"); +} + +// If repository is running, include its routes. +if ($config['RUN_OGADMREPO'] === "yes") { + include("repository.php"); +} + +// Showing API information page using Swagger-UI. +$app->get('/', + function() use ($app) { + $app->response->redirect('swagger-ui/index.html?url=../../opengnsys-api.yml'); + } +); + + +// Execute REST using Slim. +$app->run(); + +?> diff --git a/admin/WebConsole/rest/ogagent.php b/admin/WebConsole/rest/ogagent.php new file mode 100644 index 00000000..65c6cf64 --- /dev/null +++ b/admin/WebConsole/rest/ogagent.php @@ -0,0 +1,272 @@ +post('/ogagent/started', + function() use ($app) { + global $cmd; + $osType = $osVersion = "none"; + try { + // Reading POST parameters in JSON format. + $input = json_decode($app->request()->getBody()); + $ip = htmlspecialchars($input->ip); + $mac = htmlspecialchars($input->mac); + if (isset($input->ostype)) $osType = htmlspecialchars($input->ostype); + if (isset($input->osversion)) $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion)); + // Check sender agent type and IP address consistency (same as parameter value). + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) { + throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + // Client secret key for secure communications. + if (isset($input->secret)) { + // Check if secret key is valid (32 alphanumeric characters). + if (! ctype_alnum($input->secret) or strlen($input->secret) !== 32) { + throw new Exception("Bad secret key: ip=$ip, mac=$mac, os=$osType:$osVersion."); + } + // Store secret key in DB. + if (isset($input->secret)) $secret = htmlspecialchars($input->secret); + $cmd->texto = <<Ejecutar() !== true or mysql_affected_rows() !== 1) { + // DB access error or not updated. + throw new Exception("Cannot store new secret key: ip=$ip, mac=$mac, os=$osType:$osVersion."); + } + } else { + // Insecure agent exception. + throw new Exception("Insecure OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion."); + } + // Default processing: log activity. + writeLog("OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion."); + // Response. + $response = ""; + jsonResponse(200, $response); + } catch (Exception $e) { + // Communication error. + $response["message"] = $e->getMessage(); + writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); + jsonResponse(400, $response); + } + } +); + +/** + * @brief OGAgent notifies that its service is stopped on client. + * @note Route: /ogagent/stopped, Method: POST, Format: JSON + * @param string ip IP address + * @param string mac MAC (Ethernet) address + * @param string ostype OS type (Linux, Windows, macOS) + * @param string osversion OS version + * @return Null string if OK, else error message. + */ +$app->post('/ogagent/stopped', + function() use ($app) { + $osType = $osVersion = "none"; + try { + // Reading POST parameters in JSON format. + $input = json_decode($app->request()->getBody()); + $ip = htmlspecialchars($input->ip); + $mac = htmlspecialchars($input->mac); + if (isset($input->ostype)) $osType = htmlspecialchars($input->ostype); + if (isset($input->osversion)) $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion)); + // Check sender agent type and IP address consistency (same as parameter value). + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) { + throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + // May check if client is included in the server database? + // Default processing: log activity. + writeLog("OGAgent stopped: ip=$ip, mac=$mac, os=$osType:$osVersion."); + // Response. + $response = ""; + jsonResponse(200, $response); + } catch (Exception $e) { + // Communication error. + $response["message"] = $e->getMessage(); + writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); + jsonResponse(400, $response); + } + } +); + +/** + * @brief OGAgent notifies that an user logs in. + * @note Route: /ogagent/loggedin, Method: POST, Format: JSON + * @param string ip IP address + * @param string user username + * @param string language session language + * @param string ostype OS type (Linux, Windows, macOS) + * @param string osversion OS version + * @return Null string if OK, else error message. + */ +$app->post('/ogagent/loggedin', + function() use ($app) { + global $cmd; + $redirto = Array(); + $result = Array(); + + try { + // Reading POST parameters in JSON format. + $input = json_decode($app->request()->getBody()); + $ip = htmlspecialchars($input->ip); + $user = htmlspecialchars($input->user); + $language = isset($input->language) ? substr($input->language, 0, strpos($input->language, "_")) : ""; + if (isset($input->ostype)) $osType = htmlspecialchars($input->ostype); + if (isset($input->osversion)) $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion)); + // Check sender IP address consistency (same as parameter value). + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) { + throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + // Check if client is included in the server database. + $cmd->CreaParametro("@ip", $ip, 0); + $cmd->texto = << NOW() AS reserved + FROM remotepc + RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador + WHERE ordenadores.ip=@ip + LIMIT 1; +EOD; + $rs=new Recordset; + $rs->Comando=&$cmd; + if ($rs->Abrir()) { + // Read query data. + $rs->Primero(); + $id = $rs->campos['idordenador']; + $redirto[0]['url'] = $rs->campos['urllogin']; + $reserved = $rs->campos['reserved']; + $rs->Cerrar(); + if (!is_null($id)) { + // Log activity, respond to client and continue processing. + writeLog("User logged in: ip=$ip, user=$user, lang=$language, os=$osType:$osVersion."); + $response = ""; + jsonResponseNow(200, $response); + } else { + throw new Exception("Client is not in the database: ip=$ip, user=$user"); + } + // Redirect notification to UDS server, if needed. + if ($reserved == 1 and !is_null($redirto[0]['url'])) { + $redirto[0]['get'] = $app->request()->getBody(); + $result = multiRequest($redirto); + // ... (check response) + //if ($result[0]['code'] != 200) { + // ... + // Updating user's session language for messages. + $cmd->texto = <<Ejecutar(); + } + } else { + throw new Exception("Database error"); + } + } catch (Exception $e) { + // Communication error. + $response["message"] = $e->getMessage(); + writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); + jsonResponse(400, $response); + } + } +); + +/** + * @brief OGAgent notifies that an user logs out. + * @note Route: /ogagent/loggedout, Method: POST, Format: JSON + * @param string ip IP address + * @param string user username + * @return Null string if OK, else error message. + */ +$app->post('/ogagent/loggedout', + function() use ($app) { + global $cmd; + $redirto = Array(); + $result = Array(); + + try { + // Reading POST parameters in JSON format. + $input = json_decode($app->request()->getBody()); + $ip = htmlspecialchars($input->ip); + $user = htmlspecialchars($input->user); + // Check sender agent type and IP address consistency (same as parameter value). + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) { + throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + // Check if client is included in the server database. + $cmd->CreaParametro("@ip", $ip, 0); + $cmd->texto = << NOW() AS reserved + FROM remotepc + RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador + WHERE ordenadores.ip=@ip + LIMIT 1; +EOD; + $rs=new Recordset; + $rs->Comando=&$cmd; + if ($rs->Abrir()) { + // Read query data. + $rs->Primero(); + $id = $rs->campos['idordenador']; + $redirto[0]['url'] = $rs->campos['urllogout']; + $reserved = $rs->campos['reserved']; + $rs->Cerrar(); + if (!is_null($id)) { + // Log activity, respond to client and continue processing. + writeLog("User logged out: ip=$ip, user=$user."); + $response = ""; + jsonResponseNow(200, $response); + } else { + throw new Exception("Client is not in the database: ip=$ip, user=$user"); + } + // Redirect notification to UDS server, if needed. + if ($reserved == 1 and !is_null($redirto[0]['url'])) { + $redirto[0]['get'] = $app->request()->getBody(); + $result = multiRequest($redirto); + // ... (check response) + //if ($result[0]['code'] != 200) { + // ... + } + } else { + throw new Exception("Database error"); + } + } catch (Exception $e) { + // Communication error. + $response["message"] = $e->getMessage(); + writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); + jsonResponse(400, $response); + } + } +); + +?> diff --git a/admin/WebConsole/rest/opengnsys-api.yml b/admin/WebConsole/rest/opengnsys-api.yml new file mode 100644 index 00000000..0c9575a2 --- /dev/null +++ b/admin/WebConsole/rest/opengnsys-api.yml @@ -0,0 +1,1300 @@ +swagger: '2.0' + +info: + version: "1.1.0" + title: OpenGnsys REST API definition + description: | + Information about the OpenGnsys REST API functions (including Server and + Repository Manager). + contact: + name: OpenGnsys Project + url: https://opengnsys.es/ + license: + name: Creative Commons 4.0 International + url: http://creativecommons.org/licenses/by/4.0/ +basePath: /opengnsys/rest +schemes: + - https +consumes: + - application/json +produces: + - application/json +securityDefinitions: + apikey: + type: apiKey + name: Authorization + in: header +# Paths description. +paths: + /login: + post: + description: Check user login and returns his/her API key. + parameters: + - in: body + name: authdata + description: JSON authentication data + required: true + schema: + type: object + properties: + username: + type: string + password: + type: string + format: password + responses: + "200": + description: Successful login + schema: + type: object + properties: + userid: + type: integer + description: user identificator + format: int32 + apikey: + description: API key to include in ``Authorization`` header + type: string + "400": + description: Missing parameters + schema: + type: object + properties: + message: + type: string + "500": + description: Authentication error + schema: + type: object + properties: + message: + type: string + tags: + - server + - user + /info: + get: + description: Gets OpenGnsys Server information + responses: + "200": + description: Successful response + schema: + type: object + properties: + project: + description: project name (OpenGnsys) + type: string + version: + description: project version + type: string + release: + description: project release + type: string + services: + description: actived services + type: array + items: + type: string + enum: [ 'server', 'repository', 'tracker' ] + oglive: + description: installed ogLive clients + type: array + items: + type: object + properties: + distribution: + description: base distribution + type: string + kernel: + description: kernel version + type: string + architecture: + description: kernel architecture (32-bit or 64-bit) + type: string + enum: [ "i386", "amd64" ] + revision: + description: OpenGnsys revision + type: string + directory: + description: installation directory + type: string + iso: + description: ISO file + type: string + required: [ distribution, kernel, architecture, revision, directory, iso ] + required: [ project, version, release, services ] + tags: + - server + - repository + /status: + get: + description: Gets OpenGnsys Server status information + responses: + "200": + description: Successful response + schema: + type: object + properties: + memInfo: + description: memory information + properties: + total: + description: total amount of memory + type: integer + format: int64 + used: + description: amount of used memory + type: integer + format: int64 + required: [ total, used ] + cpu: + description: CPU information + properties: + model: + description: processor model + type: string + usage: + description: average of processor load + type: number + format: float + required: [ model, usage ] + required: [ memInfo, cpu ] + tags: + - server + /ous: + get: + description: Gets all `OU` objects. + responses: + "200": + description: Successful response + schema: + type: array + items: + type: object + properties: + id: + type: integer + description: Organization Unit identificator + format: int32 + minimum: 1 + name: + type: string + description: Organization Unit name + required: [ id, name ] + tags: + - server + - ou + /ous/{ouid}: + get: + description: Get an `OU` object. + parameters: + - $ref: "#/parameters/ouParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + type: integer + description: OU identificator + name: + type: string + description: OU name + description: + type: string + description: OU description + required: [ id, name, description ] + security: + - apikey: [] + tags: + - server + - ou + /ous/{ouid}/groups: + get: + description: Get all group of labs defined in an `OU` object. + parameters: + - $ref: "#/parameters/ouParam" + responses: + "200": + description: Successful response + schema: + type: array + items: + type: object + properties: + id: + description: group identificator + type: integer + format: int32 + name: + description: group name + type: string + type: + description: group type + type: integer + comments: + description: extra comments + type: string + parent: + description: parent group + type: object + properties: + id: + description: parent group identificator + type: integer + format: int32 + required: [ id, name, comments ] + security: + - apikey: [] + tags: + - server + - ou + /ous/{ouid}/labs: + get: + description: Get all `lab` objects defined in an `OU`. + parameters: + - $ref: "#/parameters/ouParam" + responses: + "200": + description: Successful response + schema: + type: array + items: + type: object + properties: + id: + type: integer + description: laboratory identificator + format: int32 + name: + type: string + description: laboratory name + inremotepc: + type: boolean + description: laboratory usable in Remote PC Project flag + group: + type: object + properties: + id: + description: group identificator + type: integer + format: int32 + ou: + type: object + properties: + id: + description: OU identificator + type: integer + format: int32 + required: [ id, name, inremotepc, ou ] + security: + - apikey: [] + tags: + - server + - lab + /ous/{ouid}/labs/{labid}: + get: + description: Get a `lab` object. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + description: laboratory identificator + type: integer + format: int32 + name: + description: laboratory name + type: string + location: + description: laboratory location + type: string + description: + description: laboratory description + type: string + inremotepc: + description: check if this lab can be included in Remote PC Project + type: boolean + capacity: + description: maximum number of people in the lab + type: integer + format: int32 + defclients: + description: number of defined clients in the lab + type: integer + format: int32 + projector: + description: check if this lab has a projector + type: boolean + board: + description: check if this lab has an electronic board + type: boolean + routerip: + description: lab router IP address + type: string + netmask: + description: network mask to use in the lab + type: string + ntp: + description: NTP server IP address + type: string + dns: + description: DNS server IP address + type: string + proxyurl: + description: Proxy server URL + type: string + mcastmode: + description: Multicast protocol mode (full-duplex, half-duplex). + type: string + enum: [ "full-duplex", "half-duplex" ] + default: "full-duplex" + mcastip: + description: Multicast IP address + type: string + mcastport: + description: Multicast port + type: integer + format: int32 + mcastspeed: + description: Multicast speed (in Mbps) + type: integer + format: int32 + p2pmode: + description: Bittorrent connection type ("peer", "leecher". "seeder"). + type: string + p2ptime: + description: Bittorrent connection extra time (in s.) + type: integer + format: int32 + picture: + description: Lab's picture file + type: string + required: [ id, name, location, description, inremotepc, capacity, defclients, projector, board, routerip, netmask, mcastmode, mcastip, mcastport, mcastspeed, p2pmode, p2ptime, picture ] + security: + - apikey: [] + tags: + - server + - lab + /ous/{ouid}/labs/{labid}/clients: + get: + description: Get all `client` objects defined in an `lab`. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + responses: + "200": + description: Successful response + schema: + type: array + items: + $ref: "#/definitions/SelectedClientModel" + security: + - apikey: [] + tags: + - server + - client + /ous/{ouid}/labs/{labid}/clients/status: + get: + description: Get execution status of all clients definied in a `lab` + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + responses: + "200": + description: Successful response + schema: + type: array + items: + $ref: "#/definitions/StatusModel" + security: + - apikey: [] + tags: + - server + - client + /ous/{ouid}/labs/{labid}/clients/{clientid}: + get: + description: Get a `client` object. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + - $ref: "#/parameters/clientParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + description: client id + type: integer + format: int32 + name: + description: client name + type: string + serialno: + description: client serial number + type: string + netiface: + description: main network interface + type: string + netdriver: + description: client MAC address (kernel module) + type: string + mac: + description: client MAC address + type: string + ip: + description: client IP address + type: string + netmask: + description: subnet mask address + type: string + routerip: + description: network router IP address + type: string + repo: + description: repository identification + type: object + properties: + id: + type: integer + format: int32 + validation: + description: boot validation flag + type: boolean + boottype: + description: boot template type + type: string + picture: + description: client's picture file + type: string + required: [ id, name, serialno, netiface, netdriver, mac, ip, netmask, routerip, repo, validation, picture ] + security: + - apikey: [] + tags: + - server + - client + /ous/{ouid}/labs/{labid}/clients/{clientid}/hardware: + get: + description: Get the hardware definition of a `client` object. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + - $ref: "#/parameters/clientParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + description: client id + type: integer + format: int32 + name: + description: client name + type: string + hardware: + description: hardware components + type: array + items: + type: object + properties: + type: + description: hardware component type + type: string + description: + description: hardware component description + type: string + required: [ type, description ] + required: [ id, name, hardware ] + security: + - apikey: [] + tags: + - server + - client + /ous/{ouid}/labs/{labid}/clients/{clientid}/diskcfg: + get: + description: Get disks configuration of a `client` + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + - $ref: "#/parameters/clientParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + description: client id + type: integer + format: int32 + name: + description: client name + type: string + diskcfg: + description: | + array of disk configuration data, including general disk information and + partition/filesystem information (if not specified in paratmeter + description, it is only valid in partition configuration). + type: array + items: + type: object + properties: + disk: + description: disk number + type: integer + format: int32 + minimum: 1 + size: + description: disk or partition size + type: integer + format: int64 + parttable: + description: partition table type (only in disk configuration) + type: string + enum: [ "MSDOS", "GPT", "LVM", "ZVOL" ] + partition: + description: partition number (only in partition configuration) + type: integer + format: int32 + minimum: 1 + parttype: + description: partition type (only in partition configuration) + type: string + filesystem: + description: filesystem type (only in partition configuration) + type: string + usage: + description: percentage of data usage in a formated filesystem (only in partition configuration) + type: integer + format: int32 + os: + description: installed operating system (only in partition configuration) + type: string + image: + description: restaured image data, if needed (only in partition configuration) + type: object + properties: + id: + type: integer + format: int32 + deploydate: + description: image restauration/deploying date (only in partition configuration) + type: string + format: date-time + updated: + description: flag to check if the restaured image is updated (only in partition configuration) + type: boolean + required: [ id, name, diskcfg ] + security: + - apikey: [] + tags: + - server + - client + /ous/{ouid}/labs/{labid}/clients/{clientid}/status: + get: + description: Get execution status of a `client` + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + - $ref: "#/parameters/clientParam" + responses: + "200": + description: Successful response + schema: + $ref: "#/definitions/StatusModel" + security: + - apikey: [] + tags: + - server + - client + /ous/{ouid}/labs/{labid}/clients/{clientid}/events: + post: + description: Store UDS server URLs to resend some events recieved from OGAgent. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + - $ref: "#/parameters/clientParam" + - name: data + in: body + description: Operation data + required: true + schema: + type: object + properties: + urlLogin: + description: URL to resend a login event. + type: string + urlLogout: + description: URL to resend a logout event. + type: string + required: [ urlLogin, urlLogout ] + responses: + "200": + description: Successful response + "400": + description: Error message + schema: + type: object + properties: + message: + type: string + security: + - apikey: [] + tags: + - server + - client + - remotepc + /ous/{ouid}/labs/{labid}/clients/{clientid}/session: + post: + description: Record session data for a client. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + - $ref: "#/parameters/clientParam" + - name: data + in: body + description: Session parameters + required: true + schema: + type: object + properties: + logoutAt: + description: Time to send a logout operation to the client + type: string + format: date-time + responses: + "200": + description: Successful response + security: + - apikey: [] + tags: + - server + - client + - remotepc + /ous/{ouid}/labs/{labid}/clients/{clientid}/unreserve: + delete: + description: Unreserve a client, clear its session data and send a poweroff operation. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/labParam" + - $ref: "#/parameters/clientParam" + responses: + "200": + description: Successful response + security: + - apikey: [] + tags: + - server + - client + - remotepc + /ous/{ouid}/repos: + get: + description: Get all `repo` objects defined in an `OU`. + parameters: + - $ref: "#/parameters/ouParam" + responses: + "200": + description: Successful response + schema: + type: array + items: + type: object + properties: + id: + type: integer + format: int32 + name: + type: string + ou: + type: object + properties: + id: + type: integer + format: int32 + required: [ id, name, ou ] + security: + - apikey: [] + tags: + - server + - repo + /ous/{ouid}/repos/{repoid}: + get: + description: Get a `repo` object. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/repoParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + description: repository id + type: integer + format: int32 + name: + description: repository name + type: string + description: + description: repository description + type: string + ip: + description: repository IP address + type: string + required: [ id, name, description, ip ] + security: + - apikey: [] + tags: + - server + - repo + /ous/{ouid}/images: + get: + description: Get all `image` objects defined in an `OU`. + parameters: + - $ref: "#/parameters/ouParam" + responses: + "200": + description: Successful response + schema: + type: array + items: + type: object + properties: + id: + type: integer + format: int32 + name: + type: string + inremotepc: + type: boolean + ou: + type: object + properties: + id: + type: integer + format: int32 + required: [ id, name, inremotepc, ou ] + security: + - apikey: [] + tags: + - server + - image + /ous/{ouid}/images/{imageid}: + get: + description: Get an `image` object. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/imageParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + description: image id + type: integer + format: int32 + name: + description: image name + type: string + description: + description: image description + type: string + comments: + description: extra comments + type: string + inremotepc: + description: image usable in Remote PC Project flag + type: boolean + repo: + description: repository identification + type: object + properties: + id: + type: integer + format: int32 + type: + description: image type (``monolithic``, ``basic``, ``incremental``) + type: string + enum: [ "monolithic", "basic", "incremental" ] + default: "monolithic" + baseimg: + description: base image for an incremental image (if ``type`` is ``incremental``) + type: string + client: + description: model client's data + type: object + properties: + id: + description: model client's id. + type: integer + format: int32 + disk: + description: source disk number + type: integer + format: int32 + partition: + description: source partition number + type: integer + format: int32 + required: [ id, disk, partition ] + creationdate: + description: image creation date + type: string + format: date-time + release: + description: image creation release + type: string + os: + description: installed operating system + type: string + required: [ id, name, description, comments, inremotepc, repo, type ] + security: + - apikey: [] + tags: + - server + - image + /ous/{ouid}/images/{imageid}/software: + get: + description: Get software inventory store into an `image` + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/imageParam" + responses: + "200": + description: Successful response + schema: + type: object + properties: + id: + description: image id + type: integer + format: int32 + name: + description: image name + type: string + software: + description: software installed + type: object + properties: + os: + description: operating system + type: string + applications: + type: array + items: + description: list of applications (name and version) + type: string + required: [ id, name, software ] + security: + - apikey: [] + tags: + - server + - image + /ous/{ouid}/images/{imageid}/reserve: + post: + description: | + Reserve a client with an installed image and send a boot/reboot operation. + If `labid` is specified, then choose a `client` defined in this lab. + parameters: + - $ref: "#/parameters/ouParam" + - $ref: "#/parameters/imageParam" + - in: body + name: data + description: Operation data + schema: + type: object + properties: + labid: + description: lab id filter (optional) + type: integer + format: int32 + minimum: 1 + maxtime: + description: maximum reservation time, in h. (optional, 24 h. by default) + type: integer + format: int32 + minimum: 1 + default: 24 + responses: + "200": + description: Reserve a client to boot using an operating system image. + schema: + $ref: "#/definitions/SelectedClientModel" + security: + - apikey: [] + tags: + - server + - image + - remotepc + /repository/images: + get: + description: Get information about images stored in a repository + responses: + "200": + description: Successful response + schema: + type: object + properties: + directory: + description: repository directory + type: string + images: + description: information about repository-global images + type: array + items: + $ref: "#/definitions/ImageModel" + ous: + description: OUs defined + type: array + items: + type: object + properties: + subdir: + description: OU subdirectory + type: string + images: + description: information about OU-based images + type: array + items: + $ref: "#/definitions/ImageModel" + disk: + description: repository disk information + type: object + properties: + total: + description: total disk space + type: string + used: + description: disk space used by files + type: string + free: + description: amount of free disk space + type: string + percent: + description: percentage of used space + type: string + required: [ total, used, free, percent ] + required: [ directory, images, ous, disk ] + security: + - apikey: [] + tags: + - repository + - image + /repository/image/{ouname}/{imagename}: + get: + description: Get information about an specific image stored in the repository + parameters: + - in: path + name: ouname + description: OU name (optional) + required: false + type: string + - in: path + name: imagename + description: image name + required: true + type: string + responses: + "200": + description: Successful response + schema: + $ref: "#/definitions/ImageModel" + security: + - apikey: [] + tags: + - repository + - image + /repository/poweron: + post: + description: send Wake-On-Lan notification to many clients + parameters: + - in: body + name: data + description: Operation data + required: true + schema: + type: object + properties: + macs: + type: array + items: + description: MAC (Ethernet) address + type: string + responses: + "200": + description: Successful response + schema: + type: object + properties: + output: + type: string + security: + - apikey: [] + tags: + - repository + - client + /ogagent/started: + post: + description: Process push notification when OGAgent is started + parameters: + - in: body + name: data + description: Operation data + required: true + schema: + type: object + properties: + ip: + type: string + mac: + type: string + ostype: + type: string + osversion: + type: string + secret: + type: string + responses: + "200": + description: Successful operation + "400": + description: An error has occurred + tags: + - server + - agent + /ogagent/stopped: + post: + description: Process push notification when OGAgent is stopped + parameters: + - in: body + name: data + description: Operation data + required: true + schema: + type: object + properties: + ip: + type: string + mac: + type: string + ostype: + type: string + osversion: + type: string + responses: + "200": + description: Successful operation + "400": + description: An error has occurred + tags: + - server + - agent + /ogagent/loggedin: + post: + description: Process push notification when an user logged in + parameters: + - in: body + name: data + description: Operation data + required: true + schema: + type: object + properties: + ip: + type: string + user: + type: string + language: + type: string + ostype: + type: string + osversion: + type: string + responses: + "200": + description: Successful operation + "400": + description: An error has occurred + tags: + - server + - agent + /ogagent/loggedout: + post: + description: Process push notification when an user is logged in + parameters: + - in: body + name: data + description: Operation data + required: true + schema: + type: object + properties: + ip: + type: string + user: + type: string + responses: + "200": + description: Successful operation + "400": + description: An error has occurred + tags: + - server + - agent +parameters: + ouParam: + name: ouid + in: path + description: OU identificator + required: true + type: integer + minimum: 1 + labParam: + name: labid + in: path + description: Lab identificator + required: true + type: integer + minimum: 1 + clientParam: + name: clientid + in: path + description: Client identificator + required: true + type: integer + minimum: 1 + repoParam: + name: repoid + in: path + description: repository identificator + required: true + type: integer + minimum: 1 + imageParam: + name: imageid + in: path + description: image definition identificator + required: true + type: integer + minimum: 1 +definitions: + StatusModel: + type: object + properties: + id: + description: client id + type: integer + format: int32 + minimum: 1 + ip: + description: client IP address + type: string + status: + description: execution status + type: string + enum: [ "off", "oglive", "busy", "linux", "windows", "macos", "unknown" ] + loggedin: + description: flag to check if an user is logged in + type: boolean + required: [ id, ip, status ] + SelectedClientModel: + type: object + properties: + id: + description: client id + type: integer + format: int32 + minimum: 1 + name: + description: client name + type: string + mac: + description: client MAC address + type: string + ip: + description: client IP address + type: string + lab: + description: client's lab + type: object + properties: + id: + description: lab id + type: integer + format: int32 + minimum: 1 + required: [ id ] + ou: + description: client's OU + type: object + properties: + id: + description: OU id + type: integer + format: int32 + minimum: 1 + required: [ id ] + required: [ id, name, mac, ip, lab, ou ] + ImageModel: + type: object + properties: + name: + description: image name (file name without extension) + type: string + type: + description: image type (file extension or `dir` for directory image) + type: string + clientname: + description: source client name + type: string + clonator: + description: clonation program + type: string + compressor: + description: compression program + type: string + filesystem: + description: filesystem type + type: string + datasize: + description: data size (bytes) + type: integer + format: int64 + size: + description: image size (bytes) + type: integer + format: int64 + modified: + description: image modification date + type: string + format: date-time + mode: + description: image access permissions (four octal digits) + type: string + backedup: + description: image backed up flag (check if `.ant` file exists) + type: boolean + default: false + backupsize: + description: image backup size (bytes) + type: integer + format: int64 + locked: + description: image locked flag (check if `.lock` file exists) + type: boolean + default: false + required: [ name, type, clientname, clonator, compressor, filesystem, datasize, size, modified, mode, backedup, locked ] + diff --git a/admin/WebConsole/rest/remotepc.php b/admin/WebConsole/rest/remotepc.php new file mode 100644 index 00000000..98166391 --- /dev/null +++ b/admin/WebConsole/rest/remotepc.php @@ -0,0 +1,553 @@ +post('/ous/:ouid/images/:imageid/reserve(/)', 'validateApiKey', + function($ouid, $imageid) use ($app) { + global $cmd; + global $AMBITO_ORDENADORES; + global $EJECUCION_COMANDO; + global $ACCION_INICIADA; + global $ACCION_FINALIZADA; + global $ACCION_SINRESULTADO; + global $ACCION_FALLIDA; + global $userid; + $response = Array(); + $ogagent = Array(); + + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Init."); + // Checking parameters. + try { + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) { + throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + if (!checkIds($ouid, $imageid)) { + throw new Exception("Ids. must be positive integers"); + } + // Reading POST parameters in JSON format. + $input = json_decode($app->request()->getBody()); + // Default: no lab. filter. + if (isset($input->labid)) { + $labid = $input->labid != "0" ? $input->labid : '%'; + } else { + $labid = '%'; + } + $maxtime = isset($input->maxtime) ? $input->maxtime : 24; // Default: 24 h. + $opts = Array('options' => Array('min_range' => 1)); // Check for int>0 + if (filter_var($labid, FILTER_VALIDATE_INT, $opts) === false and $labid !== '%') { + throw new Exception("Lab id. must be positive integer"); + } + if (filter_var($maxtime, FILTER_VALIDATE_INT, $opts) === false) { + throw new Exception("Time must be positive integer (in hours)"); + } + } catch (Exception $e) { + // Communication error. + $response["message"] = $e->getMessage(); + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"]."."); + jsonResponse(400, $response); + $app->stop(); + } + + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: labid=$labid, maxtime=$maxtime"); + // Choose older not-reserved client with image installed and get ogAdmServer data. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error opening recordset. + // Check if user is admin and client exists. + $rs->Primero(); + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idordenador"])) { + // Read query data. + $serverip = $rs->campos["ipserveradm"]; + $serverport = $rs->campos["portserveradm"]; + $clntid = $rs->campos["idordenador"]; + $clntname = $rs->campos["nombreordenador"]; + $clntip = $rs->campos["ip"]; + $clntmac = $rs->campos["mac"]; + $agentkey = $rs->campos["agentkey"]; + $disk = $rs->campos["numdisk"]; + $part = $rs->campos["numpar"]; + $labid = $rs->campos["idaula"]; + $ouid = $rs->campos["idcentro"]; + // Check client's status. + $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/status"; + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent status, url=".$ogagent[$clntip]['url']."."); + $result = multiRequest($ogagent); + if (empty($result[$clntip]['data'])) { + // Client is off, send a boot command to ogAdmServer. + // TODO: if client is busy????? + $reqframe = "nfn=Arrancar\r". + "ido=$clntid\r". + "iph=$clntip\r". + "mac=$clntmac\r". + "mar=1\r"; + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). "Send Boot command to ogAdmClient, ido=$clntid,iph=$clntip,mac=$clntmac."); + sendCommand($serverip, $serverport, $reqframe, $values); + } else { + // Client is on, send a rieboot command to its OGAgent. + $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/reboot"; + $ogagent[$clntip]['header'] = Array("Authorization: ".$agentkey); + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent reboot, url=".$ogagent[$clntip]['url']."."); + $result = multiRequest($ogagent); + // ... (check response) + //if ($result[$clntip]['code'] != 200) { + // ... + } + // DB Transaction: mark choosed client as reserved and + // create an init session command into client's actions queue. + $cmd->texto = "START TRANSACTION;"; + $cmd->Ejecutar(); + $timestamp = time(); + $cmd->texto = <<Ejecutar(); + $cmd->texto = <<Ejecutar(); + // Create event to remove reservation on timeout (15 min.). + $timeout = "15 MINUTE"; + $cmd->texto = <<Ejecutar(); + if ($t1 and $t2 and $t3) { + // Commit transaction on success. + $cmd->texto = "COMMIT;"; + $cmd->Ejecutar(); + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": DB tables and events updated, clntid=$clntid."); + // Send init session command if client is booted on ogLive. + $reqframe = "nfn=IniciarSesion\r". + "ido=$clntid\r". + "iph=$clntip\r". + "dsk=$disk\r". + "par=$part\r"; + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Send Init Session command to ogAdmClient, ido=$clntid,iph=$clntip,dsk=$disk,par=$part."); + sendCommand($serverip, $serverport, $reqframe, $values); + // Compose JSON response. + $response['id'] = (int)$clntid; + $response['name'] = $clntname; + $response['ip'] = $clntip; + $response['mac'] = $clntmac; + $response['lab']['id'] = $labid; + $response['ou']['id'] = (int)$ouid; + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Response, ".var_export($response,true)."."); + jsonResponse(200, $response); + } else { + // Roll-back transaction on DB error. + $cmd->texto = "ROLLBACK;"; + $cmd->Ejecutar(); + // Error message. + $response["message"] = "Database error: $t1, $t2, $t3"; + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"]."."); + jsonResponse(400, $response); + } + } else { + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": UNASSIGNED"); + } + $rs->Cerrar(); + $app->stop(); + } +); + + +/** + * @brief Store UDS server URLs to resend some events recieved from OGAgent. + * @note Route: /ous/:ouid/labs/:labid/clients/:clntid/events, Method: POST + * @param string urlLogin URL to redirect login notification. + * @param string urlLogout URL to redirect logout notification. + * @warning Events parameters will be stored in a new "remotepc" table. + */ +$app->post('/ous/:ouid/labs/:labid/clients/:clntid/events', 'validateApiKey', + function($ouid, $labid, $clntid) use ($app) { + global $cmd; + global $userid; + $response = Array(); + + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Init."); + // Checking parameters. + try { + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) { + throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + if (!checkIds($ouid, $labid, $clntid)) { + throw new Exception("Ids. must be positive integers"); + } + // Reading JSON parameters. + $input = json_decode($app->request()->getBody()); + $urlLogin = htmlspecialchars($input->urlLogin); + $urlLogout = htmlspecialchars($input->urlLogout); + if (filter_var($urlLogin, FILTER_VALIDATE_URL) === false) { + throw new Exception("Must be a valid URL for login notification"); + } + if (filter_var($urlLogout, FILTER_VALIDATE_URL) === false) { + throw new Exception("Must be a valid URL for logout notification"); + } + } catch (Exception $e) { + // Error message. + $response["message"] = $e->getMessage(); + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"]."."); + jsonResponse(400, $response); + $app->stop(); + } + + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: urlLogin=$urlLogin, urlLogout=$urlLogout"); + // Select client data for UDS compatibility. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error opening recordset. + // Check if user is admin and client exists. + $rs->Primero(); + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idordenador"])) { + // Check if client is reserved. + if (! is_null($rs->campos["reserved"])) { + // Updating DB if client is reserved. + $cmd->CreaParametro("@urllogin", $urlLogin, 0); + $cmd->CreaParametro("@urllogout", $urlLogout, 0); + $cmd->texto = <<Ejecutar()) { + // Confirm operation. + $response = ""; + jsonResponse(200, $response); + } else { + // Error message. + $response["message"] = "Database error"; + jsonResponse(400, $response); + } + } else { + // Error message. + $response["message"] = "Client is not reserved"; + jsonResponse(400, $response); + } + } + $rs->Cerrar(); + $app->stop(); + } +); + + +/* + * @brief Store session time (in sec). + * @note Route: /ous/:ouid/labs/:labid/clients/:clntid/session, Method: POST + * @param int deadLine maximum time session (in seconds) + * @warning Parameters will be stored in a new "remotepc" table. + */ +$app->post('/ous/:ouid/labs/:labid/clients/:clntid/session', 'validateApiKey', + function($ouid, $labid, $clntid) use ($app) { + global $cmd; + global $userid; + $response = Array(); + + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Init."); + // Checking parameters. + try { + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) { + throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + if (!checkIds($ouid, $labid, $clntid)) { + throw new Exception("Ids. must be positive integers"); + } + // Reading JSON parameters. + $input = json_decode($app->request()->getBody()); + $deadLine = $input->deadLine; + if (filter_var($deadLine, FILTER_VALIDATE_INT) === false) { + throw new Exception("Deadline must be integer"); + } + if ($deadLine <= 0) { + throw new Exception("Resource unavailable"); + } + } catch (Exception $e) { + // Error message. + $response["message"] = $e->getMessage(); + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"]."."); + jsonResponse(400, $response); + $app->stop(); + } + + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: deadLine=$deadLine"); + // Get client's data. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error opening recordset. + // Check if user is admin and client exists. + $rs->Primero(); + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idordenador"])) { + // Check if client is reserved. + if (! is_null($rs->campos["urllogin"])) { + // Read query data. + $clntid = $rs->campos["idordenador"]; + # Removing previous commands from OGAgent operations queue. + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Updating database."); + $cmd->texto = <<Ejecutar(); + # Add new commands to OGAgent operations queue. + $cmd->texto = "INSERT INTO ogagent_queue (clientid, exectime, operation) VALUES"; + if ($deadLine > 600) { + # Add reminder 10 min. before deadline. + $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 10 MINUTE, 'popup-10'),"; + } + if ($deadLine > 300) { + # Add reminder 5 min. before deadline. + $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 5 MINUTE, 'popup-5'),"; + } + # Add power off command at deadline time. + $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND, 'poweroff');"; + if ($cmd->Ejecutar()) { + // Confirm operation. + $response = ""; + jsonResponse(200, $response); + } else { + // Error message. + $response["message"] = "Database error"; + jsonResponse(400, $response); + } + } else { + // Error message. + $response["message"] = "Client is not reserved"; + jsonResponse(400, $response); + } + } else { + // Error message. + $response["message"] = "Client does not exist"; + jsonResponse(404, $response); + } + $rs->Cerrar(); + } +); + + +/** + * @brief Store UDS server URLs to resend some events recieved from OGAgent. + * @brief Unreserve a client and send a poweroff operation. + * @note Route: /ous/:ouid/labs/:labid/clients/:clntid/unreserve, Method: DELETE + */ +$app->delete('/ous/:ouid/labs/:labid/clients/:clntid/unreserve', 'validateApiKey', + function($ouid, $labid, $clntid) use ($app) { + global $cmd; + global $userid; + global $ACCION_INICIADA; + $response = Array(); + $ogagent = Array(); + + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Init."); + // Checking parameters. + try { + if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) { + throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); + } + if (!checkIds($ouid, $labid, $clntid)) { + throw new Exception("Ids. must be positive integers"); + } + } catch (Exception $e) { + // Error message. + $response["message"] = $e->getMessage(); + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"]."."); + jsonResponse(400, $response); + $app->stop(); + } + + // Select client data for UDS compatibility. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error opening recordset. + // Check if user is admin and client exists. + $rs->Primero(); + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idordenador"])) { + // Check if client is reserved. + if (! is_null($rs->campos["reserved"])) { + // Read query data. + $clntip = $rs->campos["ip"]; + $agentkey = $rs->campos["agentkey"]; + // DB Transaction: set reservation time to the past and + // remove pending boot commands from client's and agent's queues. + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": Updating database."); + $cmd->texto = "START TRANSACTION;"; + $cmd->Ejecutar(); + $cmd->texto = <<Ejecutar(); + $cmd->texto = <<Ejecutar(); + $cmd->texto = <<Ejecutar(); + $cmd->texto = "COMMIT;"; + $cmd->Ejecutar(); + // Send a poweroff command to client's OGAgent. + $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/poweroff"; + $ogagent[$clntip]['header'] = Array("Authorization: ".$agentkey); + if ($app->settings['debug']) + writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent poweroff, url=".$ogagent[$clntip]['url']."."); + $result = multiRequest($ogagent); + // ... (check response) + //if ($result[$clntip]['code'] != 200) { + // ... + // Confirm operation. + $response = ""; + jsonResponse(200, $response); + } else { + // Error message. + $response["message"] = "Client is not reserved"; + jsonResponse(400, $response); + } + } else { + // Error message. + $response["message"] = "Client does not exist"; + jsonResponse(404, $response); + } + $rs->Cerrar(); + } +); + +?> diff --git a/admin/WebConsole/rest/repository.php b/admin/WebConsole/rest/repository.php new file mode 100644 index 00000000..7ac6e88e --- /dev/null +++ b/admin/WebConsole/rest/repository.php @@ -0,0 +1,215 @@ +stop(); + } + } else { + // Cannot access configuration file. + $response['message'] = "An error occurred, please try again"; + jsonResponse(500, $response); + $app->stop(); + } + } else { + // Error: missing API key. + $response['message'] = 'Missing Repository API key'; + jsonResponse(400, $response); + $app->stop(); + } +} + +function commandExist($cmd) { + $returnVal = shell_exec("which $cmd"); + return (empty($returnVal) ? false : true); +} + + +// Define REST routes. + + +/** + * @brief List all images in the repository + * @note Route: /repository/images, Method: GET + * @param no + * @return JSON object with directory, images array, ous array and disk data. + */ +$app->get('/repository/images(/)', 'validateRepositoryApiKey', + function() use ($app) { + $response = array(); + // Read repository information file. + $cfgFile = '/opt/opengnsys/etc/repoinfo.json'; + $response = json_decode(@file_get_contents($cfgFile), true); + // Check if directory exists. + $imgPath = @$response['directory']; + if (is_dir($imgPath)) { + // Complete global image information. + for ($i=0; $istop(); + } +); + + +/** + * @brief List image data + * @note Route: /repository/image/:imagename, Method: GET + * @param no + * @return JSON object with image data. + */ +$app->get('/repository/image(/:ouname)/:imagename(/)', 'validateRepositoryApiKey', + function($ouname="/", $imagename) use ($app) { + $images = array(); + $response = array(); + // Search image name in repository information file. + $cfgFile = '/opt/opengnsys/etc/repoinfo.json'; + $json = json_decode(@file_get_contents($cfgFile), true); + $imgPath = @$json['directory']; + if (empty($ouname) or $ouname == "/") { + // Search in global directory. + $images = @$json['images']; + } else { + // Search in OU directory. + for ($i=0; $istop(); + } +); + + +/** + * @brief Power on a pc or group of pcs with the MAC specified in POST parameters + * @note Route: /poweron, Method: POST + * @param macs OU id. + * @return JSON string ok if the power on command was sent + */ +$app->post('/repository/poweron', 'validateRepositoryApiKey', + function() use($app) { + // Debe venir el parametro macs en el post (objeto JSON con array de MACs) + $data = json_decode($app->request()->getBody()); + if(empty($data->macs)){ + // Print error message. + $response['message'] = 'Required param macs not found'; + jsonResponse(400, $response); + } + else{ + $strMacs = ""; + foreach($data->macs as $mac){ + $strMacs .= " ".$mac; + } + // Ejecutar comando wakeonlan, debe estar disponible en el sistema operativo + if(commandExist("wakeonlan")){ + $response["output"] = "Executing wakeonlan ".trim($strMacs)."\n"; + $response["output"] .= shell_exec("wakeonlan ".trim($strMacs)); + // Comprobar si el comando se ejecutórrectamente + jsonResponse(200, $response); + } + else{ + // Print error message. + $response['message'] = 'Wakeonlan command not found in this repository'; + jsonResponse(404, $response); + } + } + } +); + +?> diff --git a/admin/WebConsole/rest/server.php b/admin/WebConsole/rest/server.php new file mode 100644 index 00000000..76a2f908 --- /dev/null +++ b/admin/WebConsole/rest/server.php @@ -0,0 +1,1041 @@ +campos["group_group_id"]) { + array_push($group["classroomGroups"],array("id" => $rs->campos["group_id"], + "name" => $rs->campos["nombregrupoordenador"], + "comments" => $rs->campos["comentarios"], + "classroomGroups" => array())); + } + else if(count($group["classroomGroups"]) > 0){ + addClassroomGroup($group["classroomGroups"], $rs); + } + /**/ + }); +} + +/** + * @fn getStatus(ouid, labid, [clntid]) + * @brief Returns client execution status or status of all lab's clients. + * @param ouid OU id. + * @param labid Lab. id. + * @param clntid Client id. (optional) + * @return string JSON object or array of objects including status data. + */ +function getStatus($ouid, $labid, $clntid=0) { + global $userid; + global $cmd; + global $LONCABECERA; + global $LONHEXPRM; + $app = \Slim\Slim::getInstance(); + $clientid = $clientip = ""; + $urls = Array(); + // Status mapping. + $status = Array('OFF'=>"off", + 'INI'=>"initializing", + 'OPG'=>"oglive", + 'BSY'=>"busy", + 'LNX'=>"linux", + 'OSX'=>"macos", + 'WIN'=>"windows", + 'UNK'=>"unknown"); + // Parameters. + $ouid = htmlspecialchars($ouid); + $labid = htmlspecialchars($labid); + $single = is_numeric(explode("/", $app->request->getResourceUri())[6]); + + // Database query. + $cmd->texto = <<texto .= <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and asset exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and (($single and checkParameter($rs->campos["idordenador"])) or (! $single and checkParameter($rs->campos["idaula"])))) { + // First, try to connect to ogAdmCleint service. + $serverip = $rs->campos["ipserveradm"]; + $serverport = $rs->campos["portserveradm"]; + while (!$rs->EOF) { + $id[$rs->campos["ip"]] = $rs->campos["idordenador"]; + $stat[$rs->campos["ip"]] = $status['OFF']; + $rs->Siguiente(); + } + // Connect to reset client's status. + $clientid = implode(",", $id); + $clientip = implode(";", array_keys($id)); + $reqframe = "nfn=Sondeo\r". + "ido=$clientid\r". + "iph=$clientip\r"; + $result = sendCommand($serverip, $serverport, $reqframe, $values); + // Connect to fetch client's status. + // Asuming client is off by default. + $values["tso"]="OFF"; + // Iterate to check client's status. + // Exit if status!=OFF or end iterations (status=OFF). + $maxIter = 30; + for ($i=1; $i<$maxIter and preg_match('/OFF/', $values["tso"]); $i++) { + // Connect to check status. + $reqframe = "nfn=respuestaSondeo\r". + "ido=$clientid\r". + "iph=$clientip\r"; + $result = sendCommand($serverip, $serverport, $reqframe, $values); + // Wait until next checking (0.1 ms). + usleep(100000); + } + // Parse status response. + if ($result) { + // Check status type. + if (checkParameter($values["tso"])) { + foreach (explode(";", $values["tso"]) as $data) { + if (!empty($data)) { + list($clip, $clst) = explode("/", $data); + if ($clst != "OFF") { + // Update current status. + $stat[$clip] = $status[$clst]; + } + } + } + } + // Prepare request to new OGAgent for OSes. + foreach ($stat as $ip => $st) { + if ($st == "off") { + $urls[$ip] = "https://$ip:8000/opengnsys/status"; + } + } + // Send request to OGAgents. + if (isset($urls)) { + $result = multiRequest($urls); + } + // Parse responses. + reset($urls); + foreach ($result as $res) { + if (!empty($res['data'])) { + // Get status and session data. + $ip = key($urls); + $data = json_decode($res['data']); + if (@isset($status[$data->status])) { + $stat[$ip] = $status[$data->status]; + $logged[$ip] = $data->loggedin; + } else { + $stat[$ip] = $status['UNK']; + } + } + unset($urls[$ip]); + } + // Compose JSON response. + if ($single) { + // Single response. + $response['id'] = (int)reset($id); + $response['ip'] = key($id); + $response['status'] = $stat[$ip]; + empty($logged[$ip]) || $response['loggedin'] = $logged[$ip]; + } else { + // Multiple responses. + foreach ($stat as $ip => $st) { + $tmp = Array(); + $tmp['id'] = (int)$id[$ip]; + $tmp['ip'] = $ip; + $tmp['status'] = $stat[$ip]; + empty($logged[$ip]) || $tmp['loggedin'] = $logged[$ip]; + array_push($response, $tmp); + } + } + jsonResponse(200, $response); + } else { + // Access error. + $response['message'] = "Cannot access to OpenGnsys server"; + jsonResponse(500, $response); + } + } + $rs->Cerrar(); +} + + +// REST routes. + +/** + * @brief user login. + * @note Route: /login, Method: POST + * @param string username User name. + * @param string password User password. + * @return string JSON response with user id. and API key. + * @note User's API key is stored in a new field of "usuarios" table. + */ +$app->post('/login', + function() use ($app) { + global $cmd; + global $userid; + + $response = Array(); + // Reading JSON parameters. + try { + $input = json_decode($app->request()->getBody()); + $user = htmlspecialchars($input->username); + $pass = htmlspecialchars($input->password); + } catch (Exception $e) { + // Error message. + $response["message"] = $e->getMessage(); + jsonResponse(400, $response); + $app->stop(); + } + + // Checking parameters. + if (! empty($user) and ! empty($pass)) { + // Database query. + $cmd->texto = "SELECT idusuario, apikey + FROM usuarios + WHERE usuario='$user' AND pasguor=SHA2('$pass',224)"; + $rs=new Recordset; + $rs->Comando=&$cmd; + if ($rs->Abrir()) { + $rs->Primero(); + if (!$rs->EOF){ + // JSON response. + $userid=$rs->campos["idusuario"]; + $apikey=$rs->campos["apikey"]; + $response['userid'] = $userid; + $response['apikey'] = $apikey; + jsonResponse(200, $response); + } else { + // Credentials error. + $response['message'] = 'Login failed. Incorrect credentials'; + jsonResponse(401, $response); + $app->stop(); + } + $rs->Cerrar(); + } else { + // Access error. + $response['message'] = "An error occurred. Please try again"; + jsonResponse(500, $response); + $app->stop(); + } + } else { + # Error: missing some input parameter. + $response['message'] = 'Missing username or password'; + jsonResponse(400, $response); + $app->stop(); + } + } +); + +/** + * @brief List all defined Organizational Units + * @note Route: /ous, Method: GET + * @param no + * @return JSON array with id. and name for every defined OU + */ +$app->get('/ous(/)', function() { + global $cmd; + + $cmd->texto = "SELECT * FROM centros"; + $rs=new Recordset; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $response = Array(); + $rs->Primero(); + while (!$rs->EOF) { + $tmp = Array(); + $tmp['id'] = (int)$rs->campos["idcentro"]; + $tmp['name'] = $rs->campos["nombrecentro"]; + array_push($response, $tmp); + $rs->Siguiente(); + } + $rs->Cerrar(); + jsonResponse(200, $response); + } +); + +/** + * @brief Get Organizational Unit data + * @note Route: /ous/id, Method: GET + * @param id OU id. + * @return JSON string with OU's parameters + */ +$app->get('/ous/:ouid(/)', 'validateApiKey', + function($ouid) { + global $cmd; + global $userid; + + $ouid = htmlspecialchars($ouid); + // Show OU information if user is OU's admin. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + if (checkAdmin($rs->campos["idadministradorcentro"]) and + checkParameter($rs->campos["idcentro"])) { + $response['id'] = (int)$ouid; + $response['name'] = $rs->campos["nombrecentro"]; + $response['description'] = $rs->campos["comentarios"]; + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief List group of labs in an Organizational Unit + * @note Route: /ous/id/groups, Method: GET + * @param id OU id. + * @return JSON array of OU groups + */ +$app->get('/ous/:ouid/groups(/)', 'validateApiKey', function($ouid) { + global $cmd; + global $userid; + + $ouid = htmlspecialchars($ouid); + // List group of labs if user is OU's admin. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin. + if (checkAdmin($rs->campos["idadministradorcentro"])) { + $response = Array(); + // Read data. + if (! is_null($rs->campos["idcentro"])) { + while (!$rs->EOF) { + $tmp = Array(); + $tmp['id'] = (int)$rs->campos["idgrupo"]; + $tmp['name'] = $rs->campos["nombregrupo"]; + $tmp['type'] = $rs->campos["tipo"]; + $tmp['comments'] = $rs->campos["comentarios"]; + if($rs->campos["grupoid"] != 0){ + $tmp['parent']['id'] = (int)$rs->campos["grupoid"]; + } + array_push($response, $tmp); + $rs->Siguiente(); + } + } + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief List all labs defined in an OU + * @note Route: /ous/id/labs, Method: GET + * @param id OU id. + * @return JSON array of all UO's labs data + */ +$app->get('/ous/:ouid/labs(/)', 'validateApiKey', + function($ouid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error opening recordset. + // Check if user is an UO admin. + $rs->Primero(); + if (checkAdmin($rs->campos["idadministradorcentro"])) { + $response = Array(); + if (! is_null($rs->campos["idcentro"])) { + while (!$rs->EOF) { + // En los resultados las aulas vienen repetidas tantas veces como grupos tengan, solo dejamos uno + $classroomIndex = -1; + $found=false; + $index = 0; + while(!$found && $index < count($response)){ + if(isset($response[$index]["id"]) && $response[$index]["id"] == $rs->campos["idaula"]){ + $classroomIndex = $index; + $found = true; + } + $index++; + } + if(!$found){ + $tmp = Array(); + $tmp['id'] = (int)$rs->campos["idaula"]; + $tmp['name'] = $rs->campos["nombreaula"]; + $tmp['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true; + $tmp['group']['id'] = (int)$rs->campos["grupoid"]; + $tmp['ou']['id'] = (int)$ouid; + array_push($response, $tmp); + } + else{ + // Le añadimos el grupo en cuestion siempre que no sea un subgrupo + if($rs->campos["group_group_id"] == 0){ + array_push($response[$classroomIndex]['classroomGroups'], + array("id" => (int)$rs->campos["group_id"], + "name" => $rs->campos["nombregrupoordenador"], + "comments" => $rs->campos["comentarios"], + "classroomGroups" => array())); + } + else { + // Buscamos el grupo donde añadir el grupo + addClassroomGroup($response[$classroomIndex]['classroomGroups'], $rs); + } + } + $rs->Siguiente(); + } + } + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief Get lab data + * @note Route: /ous/id1/labs/id2, Method: GET + * @param id1 OU id. + * @param id2 lab id. + * @return JSON string with lab parameters + */ +$app->get('/ous/:ouid/labs/:labid(/)', 'validateApiKey', + function($ouid, $labid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $labid = htmlspecialchars($labid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and lab exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idaula"])) { + $response['id'] = (int)$rs->campos["idaula"]; + $response['name'] = $rs->campos["nombreaula"]; + $response['location'] = $rs->campos["ubicacion"]; + $response['description'] = $rs->campos["comentarios"]; + $response['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true; + $response['capacity'] = (int)$rs->campos["puestos"]; + $response['defclients'] = (int)$rs->campos["defclients"]; + $response['projector'] = $rs->campos["cagnon"]==0 ? false: true; + $response['board'] = $rs->campos["pizarra"]==0 ? false: true; + $response['routerip'] = $rs->campos["router"]; + $response['netmask'] = $rs->campos["netmask"]; + $response['ntp'] = $rs->campos["ntp"]; + $response['dns'] = $rs->campos["dns"]; + $response['proxyurl'] = $rs->campos["proxy"]; + switch ($rs->campos["modomul"]) { + case 1: $response['mcastmode'] = "half-duplex"; break; + case 2: $response['mcastmode'] = "full-duplex"; break; + default: $response['mcastmode'] = $rs->campos["modomul"]; + } + $response['mcastip'] = $rs->campos["ipmul"]; + $response['mcastport'] = $rs->campos["pormul"]; + $response['mcastspeed'] = $rs->campos["velmul"]; + $response['p2pmode'] = $rs->campos["modp2p"]; + $response['p2ptime'] = $rs->campos["timep2p"]; + $response['picture'] = $rs->campos["urlfoto"]; + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + + +/** + * @brief List all clients defined in a lab + * @note Route: /ous/id1/labs/id2/clients, Method: GET + * @param id1 OU id. + * @param id2 lab id. + * @return JSON data with lab id. and array of lab parameters + */ +$app->get('/ous/:ouid/labs/:labid/clients(/)', 'validateApiKey', + function($ouid, $labid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $labid = htmlspecialchars($labid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and lab exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["labid"])) { + $response = Array(); + while (!$rs->EOF) { + if (!is_null($rs->campos["idordenador"])) { + $tmp = Array(); + $tmp['id'] = (int)$rs->campos["idordenador"]; + $tmp['name'] = $rs->campos["nombreordenador"]; + $tmp['ip'] = $rs->campos["ip"]; + $tmp['mac'] = $rs->campos["mac"]; + $tmp['ou']['id'] = (int)$ouid; + $tmp['lab']['id'] = (int)$labid; + array_push($response, $tmp); + } + $rs->Siguiente(); + } + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief Get execution status of all clients defined in a lab + * @note Route: /ous/id1/labs/id2clients/id3/status, Method: GET + * @param id1 OU id. + * @param id2 lab id. + * @return JSON string with array of all client status defined in a lab + */ +$app->get('/ous/:ouid/labs/:labid/clients/status(/)', 'validateApiKey', 'getStatus'); + +/** + * @brief Get client data + * @note Route: /ous/id1/labs/id2clients/id3, Method: GET + * @param id1 OU id. + * @param id2 lab id. + * @param id3 client id. + * @return JSON string with hardware parameters + */ +$app->get('/ous/:ouid/labs/:labid/clients/:clntid(/)', 'validateApiKey', + function($ouid, $labid, $clntid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $labid = htmlspecialchars($labid); + $clntid = htmlspecialchars($clntid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin, lab exists and client exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idaula"]) and checkParameter($rs->campos["idordenador"])) { + // Read data. + $response['id'] = (int)$rs->campos["idordenador"]; + $response['name'] = $rs->campos["nombreordenador"]; + $response['serialno'] = $rs->campos["numserie"]; + $response['netiface'] = $rs->campos["netiface"]; + $response['netdriver'] = $rs->campos["netdriver"]; + $response['mac'] = $rs->campos["mac"]; + $response['ip'] = $rs->campos["ip"]; + $response['netmask'] = $rs->campos["mascara"]; + $response['routerip'] = $rs->campos["router"]; + $response['repo']['id'] = (int)$rs->campos["idrepositorio"]; + //$response['hardprofile']['id'] = $rs->campos["idperfilhard"]; + //$response['menu']['id'] = $rs->campos["idmenu"]; + $response['validation'] = $rs->campos["validacion"]==0 ? false: true; + $response['boottype'] = $rs->campos["arranque"]; + $response['picture'] = $rs->campos["fotoord"]; + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief Get client's harware configuration data + * @note Route: /ous/id1/labs/id2clients/id3/hardware, Method: GET + * @param id1 OU id. + * @param id2 lab id. + * @param id3 client id. + * @return JSON string with cleint parameters + */ +$app->get('/ous/:ouid/labs/:labid/clients/:clntid/hardware(/)', 'validateApiKey', + function($ouid, $labid, $clntid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $labid = htmlspecialchars($labid); + $clntid = htmlspecialchars($clntid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and client exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idordenador"])) { + // Read data. + $response['id'] = (int)$rs->campos["idordenador"]; + $response['name'] = $rs->campos["nombreordenador"]; + $response['hardware'] = Array(); + while (!$rs->EOF) { + if (!is_null($rs->campos["nemonico"])) { + $tmp = Array(); + $tmp['type'] = $rs->campos["nemonico"]; + $tmp['description'] = $rs->campos["descripcion"]; + array_push($response['hardware'], $tmp); + } + $rs->Siguiente(); + } + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief Get client's disk configuration data + * @note Route: /ous/id1/labs/id2clients/id3/diskcfg, Method: GET + * @param id1 OU id. + * @param id2 lab id. + * @param id3 client id. + * @return JSON string with disk parameters + */ +$app->get('/ous/:ouid/labs/:labid/clients/:clntid/diskcfg(/)', 'validateApiKey', + function($ouid, $labid, $clntid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $labid = htmlspecialchars($labid); + $clntid = htmlspecialchars($clntid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and client exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["clientid"])) { + // Read data. + $response['id'] = (int)$rs->campos["clientid"]; + $response['name'] = $rs->campos["nombreordenador"]; + $response['diskcfg'] = Array(); + while (!$rs->EOF) { + // Skip header. + if ($rs->campos["numdisk"] == 0) { + $rs->Siguiente(); + continue; + } + $tmp = Array(); + // Common data. + $tmp['disk'] = (int)$rs->campos["numdisk"]; + $tmp['size'] = (int)$rs->campos["tamano"]; + if ($rs->campos["numpar"] == 0) { + // Disk data. + switch ($rs->campos["codpar"]) { + case 1: $tmp['parttable'] = "MSDOS"; break; + case 2: $tmp['parttable'] = "GPT"; break; + case 3: $tmp['parttable'] = "LVM"; break; + case 4: $tmp['parttable'] = "ZPOOL"; break; + default: $tmp['parttable'] = $rs->campos["codpar"]; + } + } else { + // Partition data. + $tmp['partition'] = (int)$rs->campos["numpar"]; + $tmp['parttype'] = $rs->campos["tipopar"]; + $tmp['filesystem'] = $rs->campos["nemonico"]; + $tmp['usage'] = (int)$rs->campos["uso"]; + if ($rs->campos["nombreso"] != null) { + $tmp['os'] = $rs->campos["nombreso"]; + if ($rs->campos["idimagen"] > 0) { + // Restored image data. + $tmp['image']['id'] = (int)$rs->campos["idimagen"]; + $tmp['image']['deploydate'] = $rs->campos["fechadespliegue"]; + // Check if image is updated. + $tmp['image']['updated'] = ($rs->campos["difimagen"]>0 ? "false" : "true"); + } + } + //$tmp['cachedata'] = $rs->campos["cache"]; + } + array_push($response['diskcfg'], $tmp); + $rs->Siguiente(); + } + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief Get client's execution status + * @note Route: /ous/id1/labs/id2clients/id3/status, Method: GET + * @param id1 OU id. + * @param id2 lab id. + * @param id3 client id. + * @return JSON string with client status + */ +$app->get('/ous/:ouid/labs/:labid/clients/:clntid/status(/)', 'validateApiKey', 'getStatus'); + +/** + * @brief List all image repositories defined in an OU + * @note Route: /ous/id/repos, Method: GET + * @param id OU id. + * @return JSON array of all UO's repo data + */ +$app->get('/ous/:ouid/repos(/)', 'validateApiKey', + function($ouid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["ouid"])) { + $response = Array(); + while (!$rs->EOF) { + if (! is_null($rs->campos["idcentro"])) { + $tmp = Array(); + $tmp['id'] = (int)$rs->campos["idrepositorio"]; + $tmp['name'] = $rs->campos["nombrerepositorio"]; + $tmp['ou']['id'] = (int)$ouid; + array_push($response, $tmp); + } + $rs->Siguiente(); + } + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief Get image repository data + * @note Route: /ous/id1/repos/id2, Method: GET + * @param id1 OU id. + * @param id2 repo id. + * @return JSON string with repo parameters + */ +$app->get('/ous/:ouid/repos/:repoid(/)', 'validateApiKey', + function($ouid, $repoid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $repoid = htmlspecialchars($repoid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and repo exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idrepositorio"])) { + // Read data. + $response['id'] = (int)$rs->campos["idrepositorio"]; + $response['name'] = $rs->campos["nombrerepositorio"]; + $response['description'] = $rs->campos["comentarios"]; + $response['ip'] = $rs->campos["ip"]; + //$response['port'] = $rs->campos["puertorepo"]; + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +/** + * @brief List all images defined in an OU + * @note Route: /ous/id/images, Method: GET + * @param id OU id. + * @return JSON array of all UO's image data + */ +$app->get('/ous/:ouid/images(/)', 'validateApiKey', + function($ouid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["ouid"])) { + $response = Array(); + while (!$rs->EOF) { + if (! is_null($rs->campos["idcentro"])) { + $tmp = Array(); + $tmp['id'] = (int)$rs->campos["idimagen"]; + $tmp['name'] = $rs->campos["nombreca"]; + $tmp['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true; + $tmp['ou']['id'] = (int)$ouid; + array_push($response, $tmp); + } + $rs->Siguiente(); + } + jsonResponse(200, $response); + } + } +); + +/** + * @brief Get image data + * @note Route: /ous/id1/images/id2, Method: GET + * @param id1 OU id. + * @param id2 image id. + * @return JSON string with image parameters + */ +$app->get('/ous/:ouid/images/:imgid(/)', 'validateApiKey', + function($ouid, $imgid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $imgid = htmlspecialchars($imgid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and repo exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idimagen"])) { + // Read data. + $response['id'] = (int)$rs->campos["idimagen"]; + $response['name'] = $rs->campos["nombreca"]; + $response['description'] = $rs->campos["descripcion"]; + $response['comments'] = $rs->campos["comentarios"]; + $response['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true; + $response['repo']['id'] = (int)$rs->campos["idrepositorio"]; + switch ($rs->campos["tipo"]) { + // Image type. + case 1: $response['type'] = "monolithic"; break; + case 2: $response['type'] = "base"; break; + case 3: $response['type'] = "incremental"; + $response['baseimg'] = $rs->campos["imagenid"]; + $response['path'] = $rs->campos["ruta"]; + break; + default: $response['type'] = $rs->campos["tipo"]; + } + if ($rs->campos["idordenador"] != 0) { + // Source client data. + $response['client']['id'] = (int)$rs->campos["idordenador"]; + $response['client']['disk'] = (int)$rs->campos["numdisk"]; + $response['client']['partition'] = (int)$rs->campos["numpar"]; + $response['creationdate'] = $rs->campos["fechacreacion"]; + $response['release'] = (int)$rs->campos["revision"]; + $response['os'] = $rs->campos["os"]; + } + jsonResponse(200, $response); + } + $rs->Cerrar(); + } +); + +// Lista de softeare instalado en una imagen. +$app->get('/ous/:ouid/images/:imgid/software(/)', 'validateApiKey', + function($ouid, $imgid) { + global $userid; + global $cmd; + + $ouid = htmlspecialchars($ouid); + $imgid = htmlspecialchars($imgid); + // Database query. + $cmd->texto = <<Comando=&$cmd; + if (!$rs->Abrir()) return(false); // Error oppening recordset. + $rs->Primero(); + // Check if user is an UO admin and repo exists. + if (checkAdmin($rs->campos["idadministradorcentro"]) and checkParameter($rs->campos["idimagen"])) { + $response['id'] = (int)$rs->campos["idimagen"]; + $response['name'] = $rs->campos["nombreca"]; + if (is_null($rs->campos["nombreso"])) { + // Null object. + $response['software'] = Array(); + jsonResponse(200, $response, JSON_FORCE_OBJECT); + } else { + // Read data. + $response['software']['os'] = $rs->campos["nombreso"]; + //$response['software']['type'] = ...; // OS type + $response['software']['applications'] = Array(); + while (!$rs->EOF) { + // Ignoring empty fields. + if (!is_null($rs->campos["descripcion"])) { + array_push($response['software']['application'], $rs->campos["descripcion"]); + } + $rs->Siguiente(); + } + jsonResponse(200, $response); + } + } + $rs->Cerrar(); + } +); + +?> diff --git a/admin/WebConsole/validacion/html/close.php b/admin/WebConsole/validacion/html/close.php index 11a3c2e8..a6b197b6 100644 --- a/admin/WebConsole/validacion/html/close.php +++ b/admin/WebConsole/validacion/html/close.php @@ -1,4 +1,4 @@ - diff --git a/admin/WebConsole/validacion/html/login_prueba.php b/admin/WebConsole/validacion/html/login_prueba.php index 78b3c5ae..d7073b5e 100644 --- a/admin/WebConsole/validacion/html/login_prueba.php +++ b/admin/WebConsole/validacion/html/login_prueba.php @@ -1,4 +1,4 @@ - @@ -6,7 +6,7 @@ $path_parts = pathinfo(__FILE__); -OpenGnSys :::: Inicio de equipo - Men de opciones +OpenGnsys :::: Inicio de equipo - Menú de opciones -



'; diff --git a/admin/WebConsole/varios/perfilcomponente_hard.php b/admin/WebConsole/varios/perfilcomponente_hard.php index 97b05368..e1a8f4ae 100644 --- a/admin/WebConsole/varios/perfilcomponente_hard.php +++ b/admin/WebConsole/varios/perfilcomponente_hard.php @@ -1,4 +1,4 @@ - -'?> +'?>

- - -


-  

+ + +


+  


-

+

- + - texto='SELECT hardwares.idhardware,hardwares.descripcion,tipohardwares.descripcion as hdescripcion,tipohardwares.urlimg,tipohardwares.pci FROM hardwares INNER JOIN perfileshard_hardwares ON hardwares.idhardware=perfileshard_hardwares.idhardware INNER JOIN tipohardwares ON hardwares.idtipohardware=tipohardwares.idtipohardware WHERE perfileshard_hardwares.idperfilhard='.$idperfilhard.' ORDER BY tipohardwares.idtipohardware,hardwares.descripcion'; + $cmd->texto='SELECT hardwares.idhardware, hardwares.descripcion,'. + ' tipohardwares.descripcion AS hdescripcion, tipohardwares.urlimg'. + ' FROM hardwares'. + ' INNER JOIN perfileshard_hardwares ON hardwares.idhardware=perfileshard_hardwares.idhardware'. + ' INNER JOIN tipohardwares ON hardwares.idtipohardware=tipohardwares.idtipohardware'. + ' WHERE perfileshard_hardwares.idperfilhard='.$idperfilhard. + ' ORDER BY tipohardwares.idtipohardware, hardwares.descripcion'; $rs->Comando=&$cmd; if ($rs->Abrir()){ @@ -68,7 +74,12 @@ if (!$cmd) } } $rs->Cerrar(); - $cmd->texto='SELECT hardwares.idhardware,hardwares.descripcion,tipohardwares.descripcion as hdescripcion,tipohardwares.urlimg,tipohardwares.pci FROM hardwares INNER JOIN tipohardwares ON hardwares.idtipohardware=tipohardwares.idtipohardware '.$strex.' AND hardwares.idcentro='.$idcentro.' ORDER BY tipohardwares.idtipohardware,hardwares.descripcion'; + $cmd->texto='SELECT hardwares.idhardware, hardwares.descripcion,'. + ' tipohardwares.descripcion AS hdescripcion, tipohardwares.urlimg,'. + ' FROM hardwares'. + ' INNER JOIN tipohardwares ON hardwares.idtipohardware=tipohardwares.idtipohardware '. + $strex.' AND hardwares.idcentro='.$idcentro. + ' ORDER BY tipohardwares.idtipohardware, hardwares.descripcion'; $rs->Comando=&$cmd; if ($rs->Abrir()){ $rs->Primero(); @@ -88,7 +99,7 @@ if (!$cmd)

- +
diff --git a/admin/WebConsole/varios/perfilcomponente_soft.php b/admin/WebConsole/varios/perfilcomponente_soft.php index 9aa381b7..58a90725 100644 --- a/admin/WebConsole/varios/perfilcomponente_soft.php +++ b/admin/WebConsole/varios/perfilcomponente_soft.php @@ -1,4 +1,4 @@ - -'?> +'?> - - -


-  

+ + +


+  


-

+

  T
- + - texto='SELECT softwares.idsoftware,softwares.descripcion,tiposoftwares.descripcion as hdescripcion,tiposoftwares.urlimg FROM softwares INNER JOIN perfilessoft_softwares ON softwares.idsoftware=perfilessoft_softwares.idsoftware INNER JOIN tiposoftwares ON softwares.idtiposoftware=tiposoftwares.idtiposoftware WHERE perfilessoft_softwares.idperfilsoft='.$idperfilsoft.' ORDER BY tiposoftwares.idtiposoftware,softwares.descripcion'; + $cmd->texto='SELECT softwares.idsoftware,softwares.descripcion,tiposoftwares.descripcion as hdescripcion,tiposoftwares.urlimg, nombreso FROM softwares INNER JOIN perfilessoft_softwares ON softwares.idsoftware=perfilessoft_softwares.idsoftware INNER JOIN tiposoftwares ON softwares.idtiposoftware=tiposoftwares.idtiposoftware INNER JOIN perfilessoft USING (idperfilsoft) LEFT OUTER JOIN nombresos USING (idnombreso) WHERE perfilessoft_softwares.idperfilsoft='.$idperfilsoft.' ORDER BY tiposoftwares.idtiposoftware,softwares.descripcion'; $rs->Comando=&$cmd; if ($rs->Abrir()){ $rs->Primero(); + if (!$nombreso && $rs->campos["nombreso"] != "") { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + $nombreso=true; + } $A_W=" WHERE "; $strex=""; while (!$rs->EOF){ @@ -86,7 +95,7 @@ if (!$cmd)

- +
diff --git a/admin/WebConsole/varios/procedimientoscomandos.php b/admin/WebConsole/varios/procedimientoscomandos.php index 89ab0ea6..f908e349 100644 --- a/admin/WebConsole/varios/procedimientoscomandos.php +++ b/admin/WebConsole/varios/procedimientoscomandos.php @@ -1,4 +1,4 @@ - -'?> +'?> - -

 
-  

-

+ +

 
+  

+

  T
'. $rs->campos[ '.$rs->campos["nombreso"].'
- - + + - texto='SELECT procedimientos_acciones.*, comandos.descripcion,comandos.visuparametros FROM procedimientos_acciones @@ -83,11 +83,11 @@ if (!$cmd) ?>
   A

-

.

+

.

- - '?> + '?> -

 
- 

+

 
+ 

- +
@@ -109,28 +109,28 @@ $mialmanaque= new Almanaque("tabla_meses"); - +
- onclick="suspender_programacion(,,))"> - + onclick="suspender_programacion(,,))"> +
 
- Annos(($annodesde-4),($annodesde+4)); // Años?> + Annos(($annodesde-3),($annodesde+3)); // Años?>   - Meses(); // Meses del año?> + Meses(); // Meses del año?>  
- MesAnno($mesacutal,$anoactual); // Calendario del mes?> @@ -147,17 +147,17 @@ $mialmanaque= new Almanaque("tabla_meses"); @@ -172,8 +172,8 @@ $mialmanaque= new Almanaque("tabla_meses");
- ".$mialmanaque->Horas(); // Horas?> - ".$mialmanaque->Horas(); // Horas?> + HorasReserva("1","tabla_horasini","ampmini","minutosini"); // Horas desde; echo $mialmanaque->HorasReserva("2","tabla_horasfin","ampmfin","minutosfin"); // Horas hasta; } @@ -195,7 +195,7 @@ $mialmanaque= new Almanaque("tabla_meses"); - + + onclick="modifica_programacion(,,)" align=center height="17" width="83">Modificar
  
- ' ; @@ -232,14 +232,14 @@ $mialmanaque= new Almanaque("tabla_meses"); Añadir
Modificar
diff --git a/admin/WebConsole/varios/tareascomandos.php b/admin/WebConsole/varios/tareascomandos.php index 878e7cbe..6f124b96 100644 --- a/admin/WebConsole/varios/tareascomandos.php +++ b/admin/WebConsole/varios/tareascomandos.php @@ -1,4 +1,4 @@ - -'?> +'?> - -

 
-  

-

+ +

 
+  

+

- - + + - texto='SELECT tareas_acciones.*, comandos.descripcion,comandos.visuparametros FROM tareas_acciones @@ -87,12 +87,12 @@ if (!$cmd)

- . + .
-/dev/null; #2. Ejecutar el instalador: @@ -43,7 +43,6 @@ Notas para ejecución del instalador en Ubuntu 12.10: - pc / qwerty / Spanish / Standard / Standard, UTF-8, Combined - Latin; Slavic Cyrillic; Greek, Fixed, 16 - Descripción de la estrucutra de boot-tools ------------------------------------------ diff --git a/client/boot-tools/boottoolsfunctions.lib b/client/boot-tools/boottoolsfunctions.lib index d0ede9cd..308c5a77 100755 --- a/client/boot-tools/boottoolsfunctions.lib +++ b/client/boot-tools/boottoolsfunctions.lib @@ -4,7 +4,7 @@ #@brief Librería o clase Boot-Tools #@class Boot-Tools #@brief Funciones para generar un sistema operativo cliente para opengnsys -#@version 1.0.5 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ @@ -23,8 +23,12 @@ export BTSVNOG2=/tmp/opengnsys_installer/opengnsys2 export BTTARGETDIR=/var/lib/tftpboot/ogclient/ export BTROOTFSIMG=${BTTARGETDIR}ogclient.img export BTROOTFSMNT=${BTTARGETDIR}ogclientmount -# tamaño maximo limitado por schroot 2GB -export BTVIRTUALDISKSIZE=2000 +if [ "$OSARCH" = "i386" ]; then + # tamaño maximo limitado por schroot 2GB para 32 bits + export BTVIRTUALDISKSIZE=2000 +else + export BTVIRTUALDISKSIZE="3G" +fi export BTROOTFSIMGLABEL=ogClient export LOG_FILE=/tmp/boot-tools_installation.log @@ -55,6 +59,13 @@ case "${1,,}" in OSARCH="i386" OSHTTP="http://es.archive.ubuntu.com/ubuntu/" ;; + wheezy) # ogLive basado en Debian 7.3. + OSDISTRIB="debian" + OSCODENAME="wheezy" + OSRELEASE="3.2.0-4-i386" + OSARCH="i386" + OSHTTP="http://ftp.es.debian.org/debian/" + ;; quantal) # ogLive 1.0.5-rc2 basado en Ubuntu 12.10 con Kernel descargado. OSDISTRIB="ubuntu" OSCODENAME="quantal" @@ -69,13 +80,6 @@ case "${1,,}" in OSARCH="i386" OSHTTP="http://es.archive.ubuntu.com/ubuntu/" ;; - wheezy) # ogLive basado en Debian 7.3. - OSDISTRIB="debian" - OSCODENAME="wheezy" - OSRELEASE="3.2.0-4-i386" - OSARCH="i386" - OSHTTP="http://ftp.es.debian.org/debian/" - ;; trusty) # ogLive 1.0.5-rc4 basado en Ubuntu 14.04. OSDISTRIB="ubuntu" OSCODENAME="trusty" @@ -83,23 +87,53 @@ case "${1,,}" in OSARCH="i386" OSHTTP="http://es.archive.ubuntu.com/ubuntu/" ;; - host | *) # ogLive basado en la distribución del servidor. + vivid) # ogLive 1.1.0-rc2 basado en Ubuntu 15.04. + OSDISTRIB="ubuntu" + OSCODENAME="vivid" + OSRELEASE="3.19.0-49-generic" + OSARCH="i386" + OSHTTP="http://es.archive.ubuntu.com/ubuntu/" + ;; + wily) # ogLive 1.1.0-rc1 basado en Ubuntu 15.10. + OSDISTRIB="ubuntu" + OSCODENAME="wily" + OSRELEASE="4.2.0-35-generic" + OSARCH="i386" + OSHTTP="http://es.archive.ubuntu.com/ubuntu/" + ;; + xenial|xenial-4.4) # ogLive 1.1.0-rc4 basado en Ubuntu 16.04 y Kernel 4.4. + OSDISTRIB="ubuntu" + OSCODENAME="xenial" + OSRELEASE="4.4.0-34-generic" + OSARCH="i386" + OSHTTP="http://es.archive.ubuntu.com/ubuntu/" + ;; + xenial-4.8) # ogLive 1.1.0-rc5 basado en Ubuntu 16.04 y Kernel 4.8. + OSDISTRIB="ubuntu" + OSCODENAME="xenial" + OSRELEASE="4.8.0-39-generic" + OSARCH="amd64" + OSHTTP="http://es.archive.ubuntu.com/ubuntu/" + ;; + host) # ogLive basado en la distribución del servidor. OSDISTRIB=$(lsb_release -is) OSCODENAME=$(lsb_release -cs) - OSRELEASE=$(uname -a | awk '{print $3}') - #uname -a | grep x86_64 > /dev/null && OSARCH="amd64" || OSARCH="i386" - OSARCH="i386" + OSRELEASE=$(uname -r) + OSARCH=$(dpkg --print-architecture) export OSHTTP="http://es.archive.ubuntu.com/ubuntu/" ;; + *) # Parámetro desconocido + echo "Parámetro no válido." + exit 1 + ;; esac -SVNURL="http://opengnsys.es/svn/trunk/client" +SVNURL="https://opengnsys.es/svn/trunk/client" VERSIONSVN=$(LANG=C svn info $SVNURL | awk '/Rev:/ {print "r"$4}') -NAMEISOCLIENT="$VERSIONBOOTTOOLS-$OSCODENAME-$OSRELEASE-$VERSIONSVN" +NAMEISOCLIENT="$VERSIONBOOTTOOLS-$OSCODENAME-$OSRELEASE-$OSARCH-$VERSIONSVN" NAMEHOSTCLIENT="$VERSIONBOOTTOOLS-$OSCODENAME-$VERSIONSVN" export OSDISTRIB OSCODENAME OSRELEASE OSARCH OSHTTP export TYPECLIENT VERSIONSVN NAMEISOCLIENT NAMEHOSTCLIENT ### El fichero de configuración debe sustituir a estos 3 ficheros (borrar las 3 líneas siguientes). -echo "$VERSIONSVN" > /tmp/versionsvn.txt echo "$NAMEISOCLIENT" > /tmp/opengnsys_info_rootfs echo "$NAMEHOSTCLIENT" > /tmp/opengnsys_chroot # Generar fichero de configuración. @@ -151,10 +185,12 @@ fi chown -R root:opengnsys $BTTARGETDIR #echo "$FUNCNAME(): Creando el disco virtual con tamaño máximo de $BTVIRTUALDISKSIZE MB" -dd if=/dev/zero of=$BTROOTFSIMG bs=1048576 count=$BTVIRTUALDISKSIZE - #qemu-img create $BTROOTFSIMG 3G +if [ "$OSARCH" = "i386" ]; then + dd if=/dev/zero of=$BTROOTFSIMG bs=1048576 count=$BTVIRTUALDISKSIZE #dd if=/dev/zero of=$BTROOTFSIMG bs=1k count=$OGCLIENTSIZEKB # necesita 500MB - +else + qemu-img create $BTROOTFSIMG $BTVIRTUALDISKSIZE +fi if [ $? -ne 0 ] then errorAndLog "$FUNCNAME(): Creando el disco virtual con tamaño maxima $BTVIRTUALDISKSIZE MB : ERROR" @@ -367,16 +403,22 @@ btogGetVar #Preparamos los gestores de arranque mkdir -p /tmp/iso/isolinux cp -av /usr/lib/syslinux/* /tmp/iso/isolinux/ -cp -av /usr/share/gpxe/* /tmp/iso/isolinux/ +if [ -d /usr/share/gpxe ]; then + cp -av /usr/share/gpxe/* /tmp/iso/isolinux + PXE=gpxe +elif [ -d /usr/lib/ipxe ]; then + cp -av /usr/lib/ipxe/* /tmp/iso/isolinux + PXE=ipxe +fi -# Si existe isolinux/gpxe.iso, montarlo para extraer isolinux.bin. -if [ -f /tmp/iso/isolinux/gpxe.iso ]; then +# Si existe el fichero ISO, montarlo para extraer isolinux.bin. +if [ -f /tmp/iso/isolinux/$PXE.iso ]; then mkdir -p /tmp/iso/isolinux/mount - mount -o loop /tmp/iso/isolinux/gpxe.iso /tmp/iso/isolinux/mount + mount -o loop /tmp/iso/isolinux/$PXE.iso /tmp/iso/isolinux/mount cp -va /tmp/iso/isolinux/mount/* /tmp/iso/isolinux umount /tmp/iso/isolinux/mount rmdir /tmp/iso/isolinux/mount - rm -f /tmp/iso/isolinux/gpxe.iso + rm -f /tmp/iso/isolinux/$PXE.iso fi cat << FIN > /tmp/iso/isolinux/isolinux.cfg @@ -414,22 +456,22 @@ append - label 5 MENU LABEL Network boot via gPXE lkrn -KERNEL gpxe.lkrn +KERNEL $PXE.lkrn label 6 MENU LABEL Network boot via gPXE usb -KERNEL gpxe.usb +KERNEL $PXE.usb label 7 MENU LABEL Network boot via gPXE pxe -KERNEL gpxe.pxe +KERNEL $PXE.pxe label 8 MENU LABEL Network boot via gPXE iso -KERNEL gpxe.iso +KERNEL $PXE.iso label 9 -MENU LABEL gpxe +MENU LABEL pxe KERNEL /clonezilla/live/vmlinuz1 APPEND initrd=/clonezilla/live/initrd1.img boot=live union=aufs noswap vga=788 ip=frommedia FIN diff --git a/client/boot-tools/boottoolsgenerator.sh b/client/boot-tools/boottoolsgenerator.sh index c6738e26..4c19de07 100755 --- a/client/boot-tools/boottoolsgenerator.sh +++ b/client/boot-tools/boottoolsgenerator.sh @@ -1,6 +1,6 @@ #!/bin/bash #@file boottoolsgenerator.sh -#@brief Script generación del sistema opertativo cliente OpenGnSys +#@brief Script generación del sistema opertativo cliente OpenGnsys #@warning #@version 0.9 - Prototipo de sistema operativo multiarranque de opengnsys. #@author Antonio J. Doblas Viso. Universidad de Malaga. @@ -11,11 +11,11 @@ #*/ #mkdir -p /tmp/opengnsys_installer/opengnsys - #svn export http://opengnsys.es/svn/branches/version1.0/client /tmp/opengnsys_installer/opengnsys + #svn export https://opengnsys.es/svn/trunk/client /tmp/opengnsys_installer/opengnsys #Variables -TYPECLIENT="host" +TYPECLIENT="${1:-host}" WORKDIR=/tmp/opengnsys_installer INSTALL_TARGET=/opt/opengnsys PROGRAMDIR=$(readlink -e $(dirname "$0")) @@ -42,12 +42,15 @@ source $PROGRAMDIR/boottoolsfunctions.lib echo "FASE 1 - Asignación de variables" #obtenemos las variables necesarias y la información del host. btogGetVar -echoAndLog "OpenGnSys CLIENT installation begins at $(date)" +echoAndLog "OpenGnsys CLIENT installation begins at $(date)" btogGetOsInfo $TYPECLIENT ########################################################################## echo "FASE 2 - Instalación de software adicional." -cat /etc/apt/sources.list | grep "http://free.nchc.org.tw/drbl-core" || echo "deb http://free.nchc.org.tw/drbl-core drbl stable " >> /etc/apt/sources.list -apt-get update; apt-get -y --force-yes install debootstrap subversion schroot squashfs-tools syslinux genisoimage gpxe qemu lsof +grep "http://free.nchc.org.tw/drbl-core" /etc/apt/sources.list || echo "deb http://free.nchc.org.tw/drbl-core drbl stable" >> /etc/apt/sources.list +apt-get update +[ -n "$(apt-cache search gpxe)" ] && PXEPKG="gpxe" +[ -n "$(apt-cache search ipxe)" ] && PXEPKG="ipxe" +apt-get -y --force-yes install debootstrap subversion schroot squashfs-tools syslinux genisoimage $PXEPKG qemu lsof ###################################################################3 echo "FASE 3 - Creación del Sistema raiz RootFS (Segundo Sistema archivos (img)) " echo "Fase 3.1 Generar y formatear el disco virtual. Generar el dispositivo loop." @@ -68,9 +71,11 @@ fi echo "FASE 4 - Configurar acceso schroot al Segundo Sistema de archivos (img)" cat /etc/schroot/schroot.conf | grep $BTROOTFSIMG || btogSetFsAccess ########################################################################### -echo "FASE 5 - Incorporando ficheros OpenGnSys el sistema raiz rootfs " +echo "FASE 5 - Incorporando ficheros OpenGnsys al sistema raíz rootfs " cp -a ${BTSVNBOOTTOOLS}/includes/usr/bin/* /tmp chmod +x /tmp/boot-tools/*.sh +# Incluir revisión. +sed -i "1 s/$/ $VERSIONSVN/" ${BTSVNBOOTTOOLS}/includes/etc/initramfs-tools/scripts/VERSION.txt # En Ubuntu 13.04+ es necesario matar proceso de "udev" antes de desmontar. umount $BTROOTFSMNT 2>/dev/null || (kill -9 $(lsof -t $BTROOTFSMNT); umount $BTROOTFSMNT 2>/dev/null) schroot -p -c IMGogclient -- /tmp/boot-tools/boottoolsFsOpengnsys.sh @@ -112,5 +117,5 @@ echo "Fase 8.3 Generar la ISO" btogIsoGenerator ######################################################################3 ######################################################################## -echoAndLog "OpenGnSys installation finished at $(date)" +echoAndLog "OpenGnsys installation finished at $(date)" diff --git a/client/boot-tools/includes/etc/apt/sources.list.ubuntu b/client/boot-tools/includes/etc/apt/sources.list.ubuntu index 3cd91c34..b2071d35 100644 --- a/client/boot-tools/includes/etc/apt/sources.list.ubuntu +++ b/client/boot-tools/includes/etc/apt/sources.list.ubuntu @@ -51,9 +51,9 @@ deb-src http://security.ubuntu.com/ubuntu OSCODENAME-security multiverse deb http://archive.ubuntu.com/ubuntu OSCODENAME main deb http://free.nchc.org.tw/drbl-core drbl stable deb http://free.nchc.org.tw/ubuntu OSCODENAME-security main restricted universe multiverse -deb http://ppa.launchpad.net/freenx-team/ubuntu/ OSCODENAME main -deb http://ppa.launchpad.net/randomaction/ppa/ubuntu OSCODENAME main -deb-src http://ppa.launchpad.net/randomaction/ppa/ubuntu OSCODENAME main +#deb http://ppa.launchpad.net/freenx-team/ubuntu/ OSCODENAME main +#deb http://ppa.launchpad.net/randomaction/ppa/ubuntu OSCODENAME main +#deb-src http://ppa.launchpad.net/randomaction/ppa/ubuntu OSCODENAME main # Ubuntu-ZFS deb http://ppa.launchpad.net/zfs-native/stable/ubuntu OSCODENAME main deb-src http://ppa.launchpad.net/zfs-native/stable/ubuntu OSCODENAME main diff --git a/client/boot-tools/includes/etc/initramfs-tools/modules b/client/boot-tools/includes/etc/initramfs-tools/modules index 4955ba4d..8300452a 100644 --- a/client/boot-tools/includes/etc/initramfs-tools/modules +++ b/client/boot-tools/includes/etc/initramfs-tools/modules @@ -9,17 +9,18 @@ # raid1 # sd_mod -# video Kernel 3.2 video. -vga16b -vesafb -fbcon +# Kernel 3.2 video. +#vga16b +#vesafb +#fbcon -# video Kernel 3.7 video. -#uvesafb +# Kernel 3.7+ video. +uvesafb #generales usbcore uhci_hcd ehci_hcd usbhid -mac-hid \ No newline at end of file +usbmouse +mac-hid diff --git a/client/boot-tools/includes/etc/initramfs-tools/scripts/VERSION.txt b/client/boot-tools/includes/etc/initramfs-tools/scripts/VERSION.txt new file mode 100644 index 00000000..7fd91a34 --- /dev/null +++ b/client/boot-tools/includes/etc/initramfs-tools/scripts/VERSION.txt @@ -0,0 +1 @@ +OpenGnsys Client 1.1.0-rc5 diff --git a/client/boot-tools/includes/etc/initramfs-tools/scripts/ogfunctions b/client/boot-tools/includes/etc/initramfs-tools/scripts/ogfunctions index 991ec890..d46ab875 100644 --- a/client/boot-tools/includes/etc/initramfs-tools/scripts/ogfunctions +++ b/client/boot-tools/includes/etc/initramfs-tools/scripts/ogfunctions @@ -1,21 +1,52 @@ #/** #@file ogfunctions.lib -#@brief Librería o clase para la gestion del sistema operativo de los clientes OpenGnSys. +#@brief Librería o clase para la gestion del sistema operativo de los clientes OpenGnsys. #@class client -#@version 1.0.5 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ ## #/** -# ogExportKernelParameters +# ogGetNetworkDevice +#@brief Devuelve el nombre de dispositivo de red correpondiente al índice indicado. +#@param int_devindex índice de dispositivo de red. +#@return str_devname nombre de dispositivo de red. +#@note Índice 0 debe corresponder a interfaz "lo" y a partir de 1 para las reales. +#@version 1.1.0 - Primera versión de la función. +#@author Ramón Gómez, ETSII Universidad de Sevilla +#@date 2016/04/20 +#*/ ## +ogGetNetworkDevice () +{ +# Mantener retrocompatibilidad con interfaces antiguas tipo eth. +case "$1" in + eth0) ind=1 ;; + eth1) ind=2 ;; + eth2) ind=3 ;; + *) ind="$1" ;; +esac +# Buscar el dispositivo del índice. +dev="" +for f in /sys/class/net/*/uevent; do + source $f + let aux=$IFINDEX-1 + [ "$ind" = "$INTERFACE" -o "$ind" = $aux ] && dev="$INTERFACE" +done +[ -n "$dev" ] && echo "$dev" +} + + +#/** +# ogExportKernelParameters #@brief Exporta los parametros pasados al kernel -#@param -#@return #@exception OG_ERR_FORMAT Formato incorrecto. -#@version 0.7 - -#@author Antonio J. Doblas. Universidad de Malaga. +#@version 0.7 - Primera versión de la función. +#@author Antonio J. Doblas. Universidad de Malaga. #@date 2010/05/24 +#@version 1.1.0 - Sustituir índice de interfaz de red por su dispositivo. +#@author Ramón Gómez, ETSII Universidad de Sevilla +#@date 2016/04/20 #*/ ## ogExportKernelParameters () { @@ -24,6 +55,14 @@ ogExportKernelParameters () do echo $i | grep "=" > /dev/null && export $i done + # Sustituir índice de interfaz de red por su dispositivo. + DEVIND=$(echo "$ip" | cut -f6 -d:) + if [ -n "$DEVIND" ]; then + PRE=$(echo "$ip" | cut -f1-5 -d:) + POST=$(echo "$ip" | cut -f7- -d:) + DEVICE=$(ogGetNetworkDevice $DEVIND) + [ -n "$DEVICE" ] && export ip="$PRE:$DEVICE:${POST:-none}" + fi return 0 } @@ -43,20 +82,28 @@ ogChangeVideoResolution () { # Variables locales. local DRIVER MODE -# Obtener driver y resolución. -DRIVER="$(echo $video|cut -f1 -d:)" -MODE="$(echo $video|cut -f2 -d:)" -case "$DRIVER" in - # Cambiar resolución para driver "uvesafb". - uvesafb) - grep ":$(echo $MODE|cut -f1 -d-)p" /sys/class/graphics/fb0/modes | head -1 > /sys/class/graphics/fb0/mode 2>&1 || MODE="640x480-16" - echo "$(echo $MODE|cut -f2 -d-)" > /sys/class/graphics/fb0/bits_per_pixel 2>&1 - echo "Screen mode: $(cat /sys/class/graphics/fb0/mode),$(cat /sys/class/graphics/fb0/bits_per_pixel)bpp." - ;; - # Resolución por defecto para el resto de casos. - *) echo "Unknown video driver, using default mode." - ;; -esac +# Mostrar resolución y driver por defecto si solo hay una opción disponible. +if [ $(grep -c "" /sys/class/graphics/fb0/modes) -eq 1 ]; then + echo "Default screen mode: $(cat /sys/class/graphics/fb0/modes),$(cat /sys/class/graphics/fb0/bits_per_pixel)bpp$(lsmod|awk '$1=="video" && $3>0 {printf " (%s)",$4}')." +else + # Obtener driver y resolución. + DRIVER="$(echo $video|cut -f1 -d:)" + MODE="$(echo $video|cut -f2 -d:)" + case "$DRIVER" in + # Cambiar resolución para driver "uvesafb". + uvesafb) + # Obtener modo por defecto si parámetro "video=uvesafb:D". + [ "$MODE" == "D" ] && MODE=$(awk -F: '$1=="D" {print $2; nextfile}' /sys/class/graphics/fb0/modes) + # Cambiar resolución según valor del parámetro "video". + grep ":$(echo ${MODE/p/}|cut -f1 -d-)p" /sys/class/graphics/fb0/modes | head -1 > /sys/class/graphics/fb0/mode 2>&1 + echo "$(echo $MODE|cut -f2 -d-)" > /sys/class/graphics/fb0/bits_per_pixel 2>&1 + echo "Screen mode: $(cat /sys/class/graphics/fb0/mode),$(cat /sys/class/graphics/fb0/bits_per_pixel)bpp." + ;; + # Resolución por defecto para el resto de casos. + *) echo "Unknown video driver, using default mode." + ;; + esac +fi } @@ -74,20 +121,23 @@ ogExportVarEnvironment () { export CFGINITRD="/tmp/initrd.cfg" OGPROTOCOL="${ogprotocol:-smb}" + [ "$ogunit" != "" ] && OGUNIT="/$ogunit" # OPTIONS Para samba y local (a nfs no le afecta) export OPTIONS=" -o user=opengnsys,pass=og" + DEFOGLIVE="ogclient" + export OGLIVEDIR="${oglivedir:-$DEFOGLIVE}" && echo "OGLIVEDIR=$OGLIVEDIR" >> $CFGINITRD case "$OGPROTOCOL" in nfs|NFS) export SRCOGLIVE="/var/lib/tftpboot" && echo "SRCOGLIVE=$SRCOGLIVE" >> $CFGINITRD export SRCOGSHARE="/opt/opengnsys/client" && echo "SRCOGSHARE=$SRCOGSHARE" >> $CFGINITRD export SRCOGLOG="/opt/opengnsys/log/clients" && echo "SRCOGLOG=$SRCOGLOG" >> $CFGINITRD - export SRCOGIMAGES="/opt/opengnsys/images" && echo "SRCOGIMAGES=$SRCOGIMAGES" >> $CFGINITRD + export SRCOGIMAGES="/opt/opengnsys/images$OGUNIT" && echo "SRCOGIMAGES=$SRCOGIMAGES" >> $CFGINITRD ;; smb|SMB|cifs|CIFS|samba|SAMBA) export SRCOGLIVE="tftpboot" && echo "SRCOGLIVE=$SRCOGLIVE" >> $CFGINITRD export SRCOGSHARE="ogclient" && echo "SRCOGSHARE=$SRCOGSHARE" >> $CFGINITRD export SRCOGLOG="oglog" && echo "SRCOGLOG=$SRCOGLOG" >> $CFGINITRD - export SRCOGIMAGES="ogimages" && echo "SRCOGIMAGES=$SRCOGIMAGES" >> $CFGINITRD + export SRCOGIMAGES="ogimages$OGUNIT" && echo "SRCOGIMAGES=$SRCOGIMAGES" >> $CFGINITRD ;; local|LOCAL) # Ponemos variables SRC compatibles con smb y nfs. @@ -203,7 +253,12 @@ ogPostConfigureFS() fi #configuramos el uso del servicio http proxy (parámetro del Kernel "ogproxy=URL_Proxy") - [ -n "${ogproxy}" ] && export http_proxy="$ogproxy" + if [ -n "${ogproxy}" ]; then + export http_proxy="$ogproxy" + export https_proxy="$ogproxy" + export ftp_proxy="$ogproxy" + export ftps_proxy="$ogproxy" + fi # configuramos el /etc/networks #read -e NETIP NETDEFAULT <<<$(route -n | grep eth0 | awk -F" " '{print $1}') @@ -253,9 +308,10 @@ ogPostConfigureFS() fi fi - #Montamos un directorio temporal para el apt-get - mount tmpfs /var/cache/apt/archives -t tmpfs -o size=15M - mkdir -p /var/cache/apt/archives/partial + #Montamos un directorio temporal para permitir instalacion de softare desde el comando apt-get (parametor kernel "ogtmpfs=50" valor en megas + ogtmpfs="${ogtmpfs:-15}" + mount tmpfs /var/cache/apt/archives -t tmpfs -o size=${ogtmpfs}M + mkdir -p /var/cache/apt/archives/partial } @@ -312,52 +368,62 @@ ogGetROOTSERVER () # ogUpdateInitrd -#@brief Actualiza el intird de la cache desde el servidor. Si el arranque ha disdo desde cache, compueba desde el servidor nueva version del initird. +#@brief Actualiza el initrd de la cache desde el servidor. Si el arranque ha sido desde cache, comprueba desde el servidor nueva version del initird. #@param1 #@return #@exception OG_ERR_FORMAT Formato incorrecto. #@version 0.9 #@author Antonio J. Doblas. Universidad de Malaga. #@date 2011/05/24 +#@version 1.1.0 - Permite varios ogLive dentro de subdirectorios +#@author Irina Gómez. ETSII Universidad de Sevilla +#@date 2017/04/27 +#@version 1.1.0 - Se permite varios ogLives en la CACHE +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2017/05/31 #*/ ## ogUpdateInitrd () { + local OGLIVEDIR + OGLIVEDIR=${oglivedir:-"ogclient"} cd /tmp mkdir /tmp/cache - TYPE=$(blkid | grep CACHE | awk -F"TYPE=" '{print $2}' | tr -d \") + TYPE=$(blkid -po export $(blkid -L CACHE) 2>/dev/null | awk -F= '$1=="TYPE" { print $2}') + # Salir si no se detecta caché. + [ -z "$TYPE" ] && return mount -t $TYPE LABEL=CACHE /tmp/cache || return - mkdir /tmp/cache/boot + mkdir -p /tmp/cache/boot/$OGLIVEDIR # comparamos los del server - busybox tftp -g -r ogvmlinuz.sum $ROOTSERVER - busybox tftp -g -r oginitrd.img.sum $ROOTSERVER + busybox tftp -g -r $OGLIVEDIR/ogvmlinuz.sum $ROOTSERVER + busybox tftp -g -r $OGLIVEDIR/oginitrd.img.sum $ROOTSERVER SERVERVMLINUZ=`cat ogvmlinuz.sum` SERVERINITRD=`cat oginitrd.img.sum` #comparamos los de la cache - CACHEVMLINUZ=`cat /tmp/cache/boot/ogvmlinuz.sum` - CACHEINITRD=`cat /tmp/cache/boot/oginitrd.img.sum` + CACHEVMLINUZ=`cat /tmp/cache/boot/$OGLIVEDIR/ogvmlinuz.sum` + CACHEINITRD=`cat /tmp/cache/boot/$OGLIVEDIR/oginitrd.img.sum` echo "MD5 on SERVER: $SERVERVMLINUZ $SERVERINITRD" - echo "MD5 on CACHE: $CACHEVMLINUZ $CACHEINITRD" + echo "MD5 on CACHE: $CACHEVMLINUZ $CACHEINITRD" - cd /tmp/cache/boot + cd /tmp/cache/boot/$OGLIVEDIR || mkdir -p /tmp/cache/boot/$OGLIVEDIR if [ "$CACHEVMLINUZ" != "$SERVERVMLINUZ" ] then echo "ogvmlinuz updating" - busybox tftp -g -r ogvmlinuz $ROOTSERVER - busybox tftp -g -r ogvmlinuz.sum $ROOTSERVER + busybox tftp -g -r $OGLIVEDIR/ogvmlinuz $ROOTSERVER + busybox tftp -g -r $OGLIVEDIR/ogvmlinuz.sum $ROOTSERVER DOREBOOT=true fi if [ "$CACHEINITRD" != "$SERVERINITRD" ] then echo "oginitrd updating" - busybox tftp -g -r oginitrd.img $ROOTSERVER - busybox tftp -g -r oginitrd.img.sum $ROOTSERVER + busybox tftp -g -r $OGLIVEDIR/oginitrd.img $ROOTSERVER + busybox tftp -g -r $OGLIVEDIR/oginitrd.img.sum $ROOTSERVER DOREBOOT=true fi @@ -408,7 +474,11 @@ ogConnect () # TODO: buscar condicion para NFS fi ;; + *) + return 1 + ;; esac + return $? } @@ -457,21 +527,27 @@ ogConnectOgLive () ogMergeLive() { #Si existe en el punto de acceso del del oglive el fichero ogclient.sqfs -if [ -f $DSTOGLIVE/ogclient/ogclient.sqfs ] +if [ ! -d $DSTOGLIVE/$OGLIVEDIR ]; then + echo "Usando ogLive por defecto." + export OGLIVEDIR=$DEFOGLIVE +fi +if [ -f $DSTOGLIVE/$OGLIVEDIR/ogclient.sqfs ] then cat /proc/mounts > /tmp/mtab.preunion if [ "$og2nd" == "img" ] then #Montamos el ROOTFS tipo img, para desarrolladores #TODO: comprobar que se tiene acceso de escritura - losetup /dev/loop0 $DSTOGLIVE/ogclient/ogclient.img -o 32256 + losetup /dev/loop0 $DSTOGLIVE/$OGLIVEDIR/ogclient.img -o 32256 mount /dev/loop0 $OGLIVEROOTFS else ## Montamos el ROOTFS tipo squashfs - mount $DSTOGLIVE/ogclient/ogclient.sqfs $OGLIVEROOTFS -t squashfs -o loop + mount $DSTOGLIVE/$OGLIVEDIR/ogclient.sqfs $OGLIVEROOTFS -t squashfs -o loop fi # Realizamos la union entre el ogliveram(initrd) y el ogliverootfs(ogclient.sqfs) - for i in etc var lib bin sbin usr root boot; do +# Nota: el orden es muy importante para evitar errores de montaje. + [ -d $DSTOGLIVE/lib32 ] && LIBS=lib32 + for i in bin sbin lib $LIBS etc var usr root boot; do ogUnionLiveDir $i done cat /tmp/mtab.preunion > /etc/mtab @@ -503,7 +579,7 @@ ogUnionLiveDir() U1STDIR="${OGLIVERAMFS}${TMPDIR}=RW" U2NDDIR="${OGLIVEROOTFS}${TMPDIR}=RO" UNIONDIR=${OGLIVEUNIONFS}${TMPDIR} - mkdir -p $UNIONDIR + mkdir -p $UNIONDIR $TMPDIR $UBIN $FUSE_OPT $UNION_OPT ${U1STDIR}:${U2NDDIR} $UNIONDIR mount --bind $UNIONDIR $TMPDIR } @@ -580,16 +656,17 @@ else ;; ""|on|any) # Bring up device - DEVICE=eth0 + DEVICE=1 ;; dhcp|bootp|rarp|both) - DEVICE=eth0 + DEVICE=1 ;; *) DEVICE=`echo $IP | cut -f6 -d:` ;; esac fi +DEVICE=$(ogGetNetworkDevice $DEVICE) if [ -z "${DEVICE}" ]; then echo "variable DEVICE con valor $DEVICE no encontrada, llamamos de nuevo a ogconfigure_networking" ogConfigureNetworking diff --git a/client/boot-tools/includes/etc/initramfs-tools/scripts/oginit b/client/boot-tools/includes/etc/initramfs-tools/scripts/oginit index 6f8a30b8..2c88fdc8 100755 --- a/client/boot-tools/includes/etc/initramfs-tools/scripts/oginit +++ b/client/boot-tools/includes/etc/initramfs-tools/scripts/oginit @@ -1,7 +1,7 @@ # OpenGnsys oginit -*- shell-script -*- #@file oginit -#@brief Guion modificador inicio initrd para OpenGnSys +#@brief Guion modificador inicio initrd para OpenGnsys #@warning #@version 0.1 - basado en ROOTfs - rootfs over nfs - #@author Antonio J. Doblas Viso. Universidad de Málaga @@ -37,12 +37,12 @@ mountroot () { [ -f /scripts/VERSION.txt ] && OGVERSION=$(cat /scripts/VERSION.txt) - OGVERSION=${OGVERSION:-"OpenGnSys Client"} + OGVERSION=${OGVERSION:-"OpenGnsys Client"} echo; echo; echo "$OGVERSION"; echo; echo - [ "$quiet" != "y" ] && log_begin_msg "Running OpenGnsys /scripts/og-top" - run_scripts /scripts/og-top - [ "$quiet" != "y" ] && log_end_msg + #[ "$quiet" != "y" ] && log_begin_msg "Running OpenGnsys /scripts/og-top" + #run_scripts /scripts/og-top + #[ "$quiet" != "y" ] && log_end_msg # If the root device hasn't shown up yet, give it a little while # to deal with removable devices @@ -59,7 +59,7 @@ mountroot () ogExportKernelParameters # Cambiar resolución de vídeo para kernels que usan el parámetro "video". [ -n "$video" ] && ogChangeVideoResolution - log_success_msg "Checking OpenGnSys Environmnet" + log_success_msg "Checking OpenGnsys Environmnet" ogExportVarEnvironment [ "$ogdebug" == "true" ] && ogYesNo --timeout 5 --default no "Stop before configure ramfs structure for OG: y/N " @@ -110,6 +110,10 @@ mountroot () [ "$ogdebug" == "true" ] && ogYesNo --timeout 5 --default no "Stop before connect with client dir SHARE -engine,scripts,interface, -share- on $OGSERVERSHARE : y/N " [ $? == 0 ] && sh || echo " " ogConnect $OGSERVERSHARE $OGPROTOCOL $SRCOGSHARE $DSTOGSHARE + if [ $? -ne 0 -a "$SRCOGSHARE" != "$DEFOGSHARE" ]; then + ogConnect $OGSERVERSHARE $OGPROTOCOL $DEFOGSHARE $DSTOGSHARE && SRCOGSHARE=$DEFOGSHARE + fi + unset DEFOGSHARE [ "$ogdebug" == "true" ] && ogYesNo --timeout 5 --default no "Stop before connect with client dir LOG STORAGE on $OGSERVERLOG : y/N " [ $? == 0 ] && sh || echo " " diff --git a/client/boot-tools/includes/etc/modprobe.d/blacklist-framebuffer.conf b/client/boot-tools/includes/etc/modprobe.d/blacklist-framebuffer.conf index 8b047e4e..51a9ac64 100644 --- a/client/boot-tools/includes/etc/modprobe.d/blacklist-framebuffer.conf +++ b/client/boot-tools/includes/etc/modprobe.d/blacklist-framebuffer.conf @@ -10,6 +10,7 @@ blacklist cyblafb blacklist gx1fb blacklist hgafb blacklist i810fb +blacklist i915_bpo blacklist intelfb blacklist kyrofb blacklist lxfb @@ -17,6 +18,7 @@ blacklist matroxfb_base blacklist neofb blacklist nvidiafb blacklist pm2fb +blacklist radeon blacklist rivafb blacklist s1d13xxxfb blacklist savagefb @@ -24,7 +26,6 @@ blacklist sisfb blacklist sstfb blacklist tdfxfb blacklist tridentfb -#blacklist vesafb blacklist vfb blacklist viafb blacklist vt8623fb diff --git a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsBootGraphics.sh b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsBootGraphics.sh index edd0dc00..67d738bc 100755 --- a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsBootGraphics.sh +++ b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsBootGraphics.sh @@ -1,8 +1,5 @@ #!/bin/bash -#TODO Comprobar si esta los source. -#svn checkout http://www.opengnsys.es/svn/branches/version1.0/client /tmp/opengnsys_installer/opengnsys/client/; -#svn checkout http://www.opengnsys.es/svn/branches/version2/ /tmp/opengnsys_installer/opengnsys2 find /tmp/opengnsys_installer/ -name .svn -type d -exec rm -fr {} \; 2>/dev/null; #plymouth @@ -16,4 +13,4 @@ update-alternatives --set default.plymouth /lib/plymouth/themes/opengnsys/opengn mkdir -p /etc/initramfs-tools/conf.d echo "FRAMEBUFFER=y" > /etc/initramfs-tools/conf.d/splash -history -c \ No newline at end of file +history -c diff --git a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsFsOpengnsys.sh b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsFsOpengnsys.sh index 8998de28..0e42a7ed 100755 --- a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsFsOpengnsys.sh +++ b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsFsOpengnsys.sh @@ -1,14 +1,5 @@ #!/bin/bash -#TODO Comprobar si esta los source. -#svn checkout http://www.opengnsys.es/svn/branches/version1.0/client /tmp/opengnsys_installer/opengnsys/client/; -#svn checkout http://www.opengnsys.es/svn/branches/version2/ /tmp/opengnsys_installer/opengnsys2 -#find /tmp/opengnsys_installer/ -name .svn -type d -exec rm -fr {} \; 2>/dev/null; -#apt-get -y --force-yes install subversion -#export SVNURL="http://opengnsys.es/svn/branches/version1.0/client/" -#VERSIONSVN=$(LANG=C svn info $SVNURL | awk '/Revision:/ {print "r"$2}') - -#VERSIONSVN=$(cat /tmp/versionsvn.txt) VERSIONBOOTTOOLS="ogLive" NAMEISOCLIENTFILE="/tmp/opengnsys_info_rootfs" @@ -24,10 +15,8 @@ OGCLIENTCFG=${OGCLIENTCFG:-/tmp/ogclient.cfg} [ -f $OGCLIENTCFG ] && source $OGCLIENTCFG OSDISTRIB=${OSDISTRIB:-$(lsb_release -is)} OSCODENAME=${OSCODENAME:-$(lsb_release -cs)} -OSRELEASE=${OSRELEASE:-$(uname -a | awk '{print $3}')} -if [ -z "$OSARCH" ]; then - uname -a | grep x86_64 > /dev/null && OSARCH="amd64" || OSARCH="i386" -fi +OSRELEASE=${OSRELEASE:-$(uname -r)} +OSARCH=${OSARCH:-$(dpkg --print-architecture)} OSHTTP=${OSHTTP:-"http://es.archive.ubuntu.com/ubuntu/"} echo "$OSDISTRIB:$OSCODENAME:$OSRELEASE:$OSARCH:$OSHTTP" @@ -37,8 +26,8 @@ LERROR=TRUE echo "$FUNCNAME: Iniciando la personalización con datos del SVN " -# parseamos el apt.source de la distribución -sed -e "s/OSCODENAME/$OSCODENAME/g" ${SVNCLIENTDIR}/includes/etc/apt/sources.list.$OSDISTRIB > ${SVNCLIENTDIR}/includes/etc/apt/sources.list +# parseamos el apt.source de la distribución (en minúsculas) +sed -e "s/OSCODENAME/$OSCODENAME/g" ${SVNCLIENTDIR}/includes/etc/apt/sources.list.${OSDISTRIB,,} > ${SVNCLIENTDIR}/includes/etc/apt/sources.list if [ $? -ne 0 ] then echo "$FUNCNAME(): Parsing apt.sources : ERROR" diff --git a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareCompile.sh b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareCompile.sh index 637d2a66..b74946e6 100755 --- a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareCompile.sh +++ b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareCompile.sh @@ -13,49 +13,17 @@ export LANG=C source /opt/opengnsys/lib/engine/bin/ToolsGNU.c &>/dev/null pushd /tmp -echo "ctorrent " -which ctorrent || ctorrent install &>/dev/null - -echo "udp-sender " -which udp-sender || udpcast install &>/dev/null - echo "ms-sys " which ms-sys || ms-sys install &>/dev/null - echo "spartlnx" which spartlnx.run || $(wget http://damien.guibouret.free.fr/savepart.zip &>/dev/null; unzip -o savepart.zip -d /sbin/) -#echo "xvesa" -gdebi -n /var/cache/apt/archivesOG/xvesa.deb - -#echo "partclone" -#gdebi -n /var/cache/apt/archivesOG/partclone_0.2.38_i386.deb - -#echo "comenzamos con el busybox" -#echo "busybox-static 1.17.1 en rootfs" -apt-get remove -y busybox-static -gdebi -n /var/cache/apt/archivesOG/busybox-static_1.17.1-10ubuntu1_i386.deb -cp /bin/busybox /bin/busyboxOLD -/bin/busyboxOLD -echo "busybox-static 1.18.5 en initrd" +echo "busybox" apt-get install -y busybox-static cp /bin/busybox /bin/busyboxNEW /bin/busyboxNEW -echo " en scripts reboot y poweroff hacer llamada a busyboxOLD reboot|poweroff " - -#gpt -#echo "gptfdisk" -#apt-get install -y uuid-dev libicu-dev libpopt-dev libpopt0 ncurses-base libncurses5-dev -#wget -O download.tgz http://sourceforge.net/projects/gptfdisk/files/gptfdisk/0.8.5/gptfdisk-0.8.5.tar.gz/download -O gptfdisk-0.8.5.tar.gz -#tar xzvf gptfdisk-0.8.5.tar.gz -#cd gptfdisk-0.8.5 -#make -#cp -va sgdisk gdisk fixparts cgdisk /sbin -#cd .. -#rm -fr gptfdisk-0.8.5* - # Mach-O loader for Linux echo "maloader" wget https://github.com/shinh/maloader/archive/master.zip diff --git a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareInstall.sh b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareInstall.sh index 70207cae..267b646b 100755 --- a/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareInstall.sh +++ b/client/boot-tools/includes/usr/bin/boot-tools/boottoolsSoftwareInstall.sh @@ -14,8 +14,13 @@ ln -s /bin/true /sbin/initctl #apt-get update; apt-get install --no-install-recommends dbus; dbus-uuidgen > /var/lib/dbus/machine-id; dpkg-divert --local --rename --add /sbin/initctl; ln -s /bin/true /sbin/initctl #cp /tmp/sources.list /etc/apt/sources.list -#Limpiamos y actualizamos los repositorios apt +#Limpiamos y actualizamos los repositorios apt (incluir siempre paquetes de 32 bits) apt-get clean +OSARCH=${OSARCH:-$(dpkg --print-architecture)} +if [ "$OSARCH" != "i386" ]; then + dpkg --add-architecture i386 + PKGS32="lib32gcc1 lib32stdc++6 lib32z1 libc6-i386" +fi apt-get update apt-get upgrade -y @@ -29,10 +34,7 @@ echo "/dev/sda1 / ext4 rw,errors=remount-ro 0 0" > /etc/mtab # Deteccion de la versión y kernel a usar OGCLIENTCFG=${OGCLIENTCFG:-/tmp/ogclient.cfg} [ -f $OGCLIENTCFG ] && source $OGCLIENTCFG -OSRELEASE=${OSRELEASE:-$(uname -a | awk '{print $3}')} -if [ -z "$OSARCH" ]; then - uname -a | grep x86_64 > /dev/null && OSARCH="amd64" || OSARCH="i386" -fi +OSRELEASE=${OSRELEASE:-$(uname -r)} # inicio de la instalacion if [ "$OSRELEASE" == "3.7.6-030706-generic" ]; then # Descargar e instalar Kernel 3.7. @@ -44,23 +46,25 @@ if [ "$OSRELEASE" == "3.7.6-030706-generic" ]; then wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.7.6-raring/linux-headers-3.7.6-030706-generic_3.7.6-030706.201302040006_$OSARCH.deb wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.7.6-raring/linux-headers-3.7.6-030706_3.7.6-030706.201302040006_all.deb dpkg -i *.deb + apt-get -y --force-yes install dkms popd rm -fr /tmp/kernel else # Instalar Kernel del repositorio de paquetes. - apt-get -y --force-yes install linux-image-${OSRELEASE} linux-headers-${OSRELEASE} + apt-get -y --force-yes install linux-image-${OSRELEASE} linux-headers-${OSRELEASE} dkms apt-get -y --force-yes install linux-image-extra-${OSRELEASE} 2>/dev/null fi - -#Eliminamos cualquier busybox previo: antes del busybox -#apt-get -y --force-yes remove busybox -#apt-get -y --force-yes remove busybox-static - -#estos paquetes ofrecen interaccion. -# si es actualización, ya existe el fichero /etc/ssh/ssh_config -apt-get -y install sshfs -apt-get -y install console-data +# Valores para paquetes interactivos. +cat << EOT | debconf-set-selections -- +console-setup console-setup/charmap47 select UTF-8 +console-setup console-setup/codeset47 select . Combined - Latin; Slavic Cyrillic; Greek +console-setup console-setup/fontface47 select TerminusBold +console-setup console-setup/fontsize-fb47 select 8x16 +davfs2 davfs2/suid_file boolean false +kexec-tools kexec-tools/load_kexec boolean true +EOT +apt-get -y install sshfs console-data kexec-tools davfs2 $PKGS32 #comenzamos con la instalación de los paquetes a instalar. for group in `find /usr/bin/boot-tools/listpackages/ -name sw.*` @@ -69,9 +73,6 @@ do for package in ` awk /^install/'{print $2}' $group ` do echo -n $package - #ADV - #TEST - #apt-get -y --force-yes install --no-install-recommends $package &>/dev/null apt-get -y --force-yes install $package &>/dev/null RETVAL=$? if [ $RETVAL == 0 ] @@ -79,12 +80,26 @@ do echo " : OK - Paquete instalado correctamente (codigo interno de apt-get $RETVAL)" else echo " : Error Paquete $package del grupo $group (codigo interno de apt-get $RETVAL) " - echo "Pulse pause para continuar" + echo "Pulse [Intro] para continuar" read fi done done +# Instalar módulos que algunos paquetes puedan tener pendientes de compilar. +echo "Instalando módulos adicionales con DKMS" +while read -e mod vers; do + echo -n "Intalando módulo $mod v$vers" + dkms install -m $mod -v $vers &>/dev/null + RETVAL=$? + if [ $RETVAL == 0 ]; then + echo " : OK - Módulo instalado correctamente (codigo interno de dkms $RETVAL)" + else + echo " : Error módulo $mod (codigo interno de dkms $RETVAL) " + echo "Pulse [Intro] para continuar" + read + fi +done < <(dkms status 2>/dev/null | awk -F, '$3~/added/ {print $1,$2}') #Activamos el hook del oginitrd.img mv /etc/initramfs-tools/oghooks /etc/initramfs-tools/hooks/ diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Xwindow b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Xwindow index 85858cb1..2f383b94 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Xwindow +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Xwindow @@ -4,10 +4,9 @@ #install xorg #install lxde #+80M roxterm y gparted -install roxterm -install gparted +#install roxterm +#install gparted #xvesa en compilacion #install openbox #install midori -# VESA Kernel 3.7 -#install v86d +install v86d # VESA Kernel 3.7+ diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Zinitrd b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Zinitrd deleted file mode 100644 index 7569b9c5..00000000 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.Zinitrd +++ /dev/null @@ -1,3 +0,0 @@ -#sw.zinitrd -#install busybox-static -#install bash-static diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.basic b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.basic index 7708c146..fc869c80 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.basic +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.basic @@ -13,8 +13,12 @@ install gawk install subversion install python-openssl install python -install php5-cli +#install php5-cli # ogLive anterior a Ubuntu 16.04 +install php-cli # ogLive a partir de Ubuntu 16.04 install dmidecode install realpath install rpm install sqlite3 +install os-prober +install moreutils +install jq diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.cloning b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.cloning index b4c8c76d..ca47629a 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.cloning +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.cloning @@ -1,14 +1,11 @@ #sw.cloning -install drbl-partimage install fsarchiver install pv -install kexec-tools install pxe-kexec install mbuffer install parted install gdisk install drbl-chntpw -#install chntpw install clonezilla install registry-tools install reglookup diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compile b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compile index 8b1d1001..cc547477 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compile +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compile @@ -1,10 +1,11 @@ install build-essential -install libattr* +#install libattr* # Satura el tamaño del archivo en Ubuntu 15.04 +install libattr1 +install libattr1-dev +install uuid-dev install attr install make install m4 install gettext install libmhash-dev -install gdebi-core -install gawk diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compresor b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compresor index 113e885e..196cbce5 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compresor +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.compresor @@ -4,9 +4,8 @@ install zip install unzip install gzip install lzop -install drbl-lzop install pigz install pbzip2 install lbzip2 install rzip -install p7zip-full \ No newline at end of file +install p7zip-full diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.local b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.local index ab9aca8b..f0942193 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.local +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.local @@ -1,8 +1,9 @@ #sw.filesystem.local install squashfs-tools install unionfs-fuse -install drbl-ntfsprogs +#install drbl-ntfsprogs # Eliminado install ntfs-3g +install ntfs-config install dosfstools install fatresize install exfat-utils @@ -20,11 +21,12 @@ install hfsplus install hfsprogs install hfsutils install nilfs-tools -install ufsutils install vmfs-tools -install ubuntu-zfs -# Solo en ogLive basado en Ubuntu 14.04 -#install android-tools-adb -#install android-tools-fastboot -#install android-tools-fsutils -#install f2fs-tools +#install ufsutils # ogLive anterior a Ubuntu 14.04 +#install zfsutils # ogLive anterior a Ubuntu 16.04 +install zfsutils-linux # ogLive a partir de Ubuntu 16.04 +# Solo en ogLive basado en Ubuntu 14.04 o posterior +install android-tools-adb +install android-tools-fastboot +install android-tools-fsutils +install f2fs-tools diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.remote b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.remote index f0890b6b..b38a150e 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.remote +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.filesystem.remote @@ -1,9 +1,8 @@ #sw.filesystem.remote -install nfs-common +#install nfs-common # Provoca error de instalación en Ubuntu 15.04 install sshfs install cifs-utils install smbclient -install davfs2 install open-iscsi install openssh-server install bittornado diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.networking b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.networking index d8efd04e..42d44e85 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.networking +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.networking @@ -1,5 +1,6 @@ #sw.networking install netpipes +install curl install wget install tftp install dnsutils @@ -7,8 +8,10 @@ install trickle install lighttpd install ethtool install ssmping -install mii-diag install tcpdump install nmap install arping -install iptraf \ No newline at end of file +#install iptraf +install ntpdate +install ctorrent +install udpcast diff --git a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.testing b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.testing index c3d3b86f..15aae730 100644 --- a/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.testing +++ b/client/boot-tools/includes/usr/bin/boot-tools/listpackages/sw.testing @@ -4,14 +4,17 @@ install schroot #install grub install xmlstarlet install efibootmgr +############# Requisitos para el cliente 1.1.0 en pruebas compatible con Remote-PC +install libxss1 +install python-prctl +install python-six +install python-requests ############## #install discover #install laptop-detect -install os-prober #install casper #install lupin-casper #install xinit -#install openbox #install obconf #install xserver-xorg #install x11-xserver-utils @@ -42,34 +45,20 @@ install os-prober #install nitrogen #install ttf-ubuntu-font-family #install time -#install hdparm #install openssh-client #install synaptic #install libglib-perl #install libgtk2-perl #install libxml-simple-perl -#install rsync #install smartmontools #install gnome-disk-utility #install policykit-1-gnome #install policykit-desktop-privileges #install baobab #install lshw-gtk -#install testdisk #install usb-creator-gtk #install wodim #install curlftpfs -#install nmap -#install cifs-utils #install libnotify-bin #install cryptsetup -#install reiserfsprogs -#install dosfstools -#install ntfsprogs -#install ntfs-3g -#install hfsutils -#install reiser4progs -#install jfsutils -#install smbclient -#install wget #install system-config-lvm diff --git a/client/boot-tools/includes/var/cache/apt/archivesOG/busybox-static_1.17.1-10ubuntu1_i386.deb b/client/boot-tools/includes/var/cache/apt/archivesOG/busybox-static_1.17.1-10ubuntu1_i386.deb deleted file mode 100644 index c72adfba..00000000 Binary files a/client/boot-tools/includes/var/cache/apt/archivesOG/busybox-static_1.17.1-10ubuntu1_i386.deb and /dev/null differ diff --git a/client/boot-tools/includes/var/cache/apt/archivesOG/busybox_1.17.1-10ubuntu1_i386.deb b/client/boot-tools/includes/var/cache/apt/archivesOG/busybox_1.17.1-10ubuntu1_i386.deb deleted file mode 100644 index 53679b05..00000000 Binary files a/client/boot-tools/includes/var/cache/apt/archivesOG/busybox_1.17.1-10ubuntu1_i386.deb and /dev/null differ diff --git a/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.38_i386.deb b/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.38_i386.deb deleted file mode 100644 index 6159c766..00000000 Binary files a/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.38_i386.deb and /dev/null differ diff --git a/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.7-1drbl_i386.deb b/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.7-1drbl_i386.deb deleted file mode 100755 index 870b021f..00000000 Binary files a/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.7-1drbl_i386.deb and /dev/null differ diff --git a/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.8_i386.deb b/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.8_i386.deb deleted file mode 100755 index 9dbe2e9e..00000000 Binary files a/client/boot-tools/includes/var/cache/apt/archivesOG/partclone_0.2.8_i386.deb and /dev/null differ diff --git a/client/boot-tools/includes/var/cache/apt/archivesOG/xvesa.deb b/client/boot-tools/includes/var/cache/apt/archivesOG/xvesa.deb deleted file mode 100644 index 72433e76..00000000 Binary files a/client/boot-tools/includes/var/cache/apt/archivesOG/xvesa.deb and /dev/null differ diff --git a/client/boot-tools/includes/var/lib/locales/supported.d/local b/client/boot-tools/includes/var/lib/locales/supported.d/local index be3f2a41..c20da27e 100644 --- a/client/boot-tools/includes/var/lib/locales/supported.d/local +++ b/client/boot-tools/includes/var/lib/locales/supported.d/local @@ -2,4 +2,6 @@ es_ES ISO-8859-1 es_ES@euro ISO-8859-15 es_ES.UTF-8 UTF-8 es_ES.UTF-8@euro UTF-8 -en_US.UTF-8 UTF-8 \ No newline at end of file +en_US.UTF-8 UTF-8 +en_GB.UTF-8 UTF-8 +ca_ES.UTF-8 UTF-8 diff --git a/client/boot-tools/kernelParameterOG.es.txt b/client/boot-tools/kernelParameterOG.es.txt index 7f8a15b2..736a38f0 100644 --- a/client/boot-tools/kernelParameterOG.es.txt +++ b/client/boot-tools/kernelParameterOG.es.txt @@ -1,5 +1,5 @@ Ver información completa en: - http://www.opengnsys.es/wiki/InitrdClienteSecondFileSystem + https://opengnsys.es/trac/wiki/InitrdClienteSecondFileSystem diff --git a/client/browser/browser.pro b/client/browser/browser.pro index f1174fb6..01978c71 100644 --- a/client/browser/browser.pro +++ b/client/browser/browser.pro @@ -1,5 +1,5 @@ TEMPLATE = subdirs -SUBDIRS = qtermwidget src +SUBDIRS = qtermwidget digitalclock src OPTIONS += ordered CONFIG += qt warn_on release diff --git a/client/browser/digitalclock/digitalclock.cpp b/client/browser/digitalclock/digitalclock.cpp new file mode 100644 index 00000000..4b65b6b7 --- /dev/null +++ b/client/browser/digitalclock/digitalclock.cpp @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "digitalclock.h" + +//! [0] +DigitalClock::DigitalClock(QWidget *parent) + : QLCDNumber(parent) +{ + setSegmentStyle(Filled); + + QTimer *timer = new QTimer(this); + connect(timer, SIGNAL(timeout()), this, SLOT(showTime())); + timer->start(1000); + + showTime(); + + setWindowTitle(tr("Digital Clock")); + resize(150, 60); +} +//! [0] + +//! [1] +void DigitalClock::showTime() +//! [1] //! [2] +{ + QTime time = QTime::currentTime(); + QString text = time.toString("hh:mm"); + if ((time.second() % 2) == 0) + text[2] = ' '; + display(text); +} +//! [2] diff --git a/client/browser/digitalclock/digitalclock.h b/client/browser/digitalclock/digitalclock.h new file mode 100644 index 00000000..f891335e --- /dev/null +++ b/client/browser/digitalclock/digitalclock.h @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DIGITALCLOCK_H +#define DIGITALCLOCK_H + +#include + +//! [0] +class DigitalClock : public QLCDNumber +{ + Q_OBJECT + +public: + DigitalClock(QWidget *parent = 0); + +private slots: + void showTime(); +}; +//! [0] + +#endif diff --git a/client/browser/digitalclock/digitalclock.pro b/client/browser/digitalclock/digitalclock.pro new file mode 100644 index 00000000..6d2d283a --- /dev/null +++ b/client/browser/digitalclock/digitalclock.pro @@ -0,0 +1,23 @@ +TEMPLATE = lib +DESTDIR = .. + +TARGET = digitalclock + +CONFIG += qt release warn_on build_all staticlib + +QT += core gui + +MOC_DIR = ../.moc + +OBJECTS_DIR = ../.objs +TARGET = digitalclock + +DEFINES += HAVE_POSIX_OPENPT +#or DEFINES += HAVE_GETPT + +HEADERS = digitalclock.h + +SOURCES = digitalclock.cpp + + + diff --git a/client/browser/po/ca.po b/client/browser/po/ca.po new file mode 100644 index 00000000..8e5e0b7c --- /dev/null +++ b/client/browser/po/ca.po @@ -0,0 +1,110 @@ +# OpenGnsys Client Browser messeages file. +# Copyright (C) 2016 +# This file is distributed under the same license as the browser package. +# Ramón M. Gómez , 2016. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: OpenGnsys Client Browser 1.1.0\n" +"Report-Msgid-Bugs-To: https://opengnsys.es\n" +"POT-Creation-Date: 2017-05-11 11:51+0000\n" +"PO-Revision-Date: 2016-05-03 10:25+0200\n" +"Last-Translator: Ramón M. Gómez \n" +"Language-Team: CATALAN \n" +"Language: ca\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: ../src/main.cpp:20 +#, c-format +msgid "Uso: %s -qws http://sitioweb.com/\n" +msgstr "Ús: %s -qws http://web.com/\n" + +#: ../src/mainwindow.cpp:55 +msgid "&Nueva Terminal" +msgstr "&Nova Terminal" + +#: ../src/mainwindow.cpp:60 +msgid "Salida" +msgstr "Sortida" + +#: ../src/mainwindow.cpp:97 +msgid "Proyecto OpenGnsys" +msgstr "Projecte OpenGnsys" + +#: ../src/mainwindow.cpp:145 +msgid "El fichero de log no ha podido ser abierto: " +msgstr "" + +#: ../src/mainwindow.cpp:174 +msgid "Hay otro proceso en ejecución. Por favor espere." +msgstr "" + +#: ../src/mainwindow.cpp:189 ../src/mainwindow.cpp:228 +msgid "AVISO" +msgstr "AVIS" + +#: ../src/mainwindow.cpp:191 +msgid "" +"La siguiente acción puede modificar datos o tardar varios minutos. El " +"equipo no podrá ser utilizado durante su ejecución." +msgstr "" + +#: ../src/mainwindow.cpp:192 +msgid "Ejecutar" +msgstr "Executar" + +#: ../src/mainwindow.cpp:193 +msgid "Cancelar" +msgstr "Cancel-lar" + +#: ../src/mainwindow.cpp:211 +#, c-format +msgid "%p% Cargando" +msgstr "%p% Carregat" + +#: ../src/mainwindow.cpp:230 +msgid "La página no se puede cargar." +msgstr "" + +#: ../src/mainwindow.cpp:232 +msgid "Recargar" +msgstr "Recarregar" + +#: ../src/mainwindow.cpp:233 +msgid "Abortar" +msgstr "Avortar" + +#: ../src/mainwindow.cpp:264 +msgid "Lanzado satisfactoriamente." +msgstr "" + +#: ../src/mainwindow.cpp:298 +msgid "Proceso acabado correctamente. Valor de retorno: " +msgstr "" + +#: ../src/mainwindow.cpp:302 +msgid "El proceso ha fallado inesperadamente. Salida: " +msgstr "" + +#: ../src/mainwindow.cpp:313 +msgid "Imposible lanzar el proceso." +msgstr "" + +#: ../src/mainwindow.cpp:316 +msgid "Error de escritura en el proceso." +msgstr "" + +#: ../src/mainwindow.cpp:319 +msgid "Error de lectura del proceso." +msgstr "" + +#: ../src/mainwindow.cpp:327 +msgid "Error desconocido." +msgstr "" + +#: ../src/mainwindow.cpp:460 +msgid "Lanzando el comando: " +msgstr "" diff --git a/client/browser/po/en.po b/client/browser/po/en.po new file mode 100644 index 00000000..68ab13c5 --- /dev/null +++ b/client/browser/po/en.po @@ -0,0 +1,112 @@ +# OpenGnsys Client Browser messeages file. +# Copyright (C) 2016 +# This file is distributed under the same license as the browser package. +# Ramón M. Gómez , 2016. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: OpenGnsys Client Browser 1.1.0\n" +"Report-Msgid-Bugs-To: https://opengnsys.es\n" +"POT-Creation-Date: 2017-05-11 11:51+0000\n" +"PO-Revision-Date: 2016-05-03 10:16+0200\n" +"Last-Translator: Ramón M. Gómez \n" +"Language-Team: ENGLISH \n" +"Language: en\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: ../src/main.cpp:20 +#, c-format +msgid "Uso: %s -qws http://sitioweb.com/\n" +msgstr "Usage: %s -qws http://website.com/\n" + +#: ../src/mainwindow.cpp:55 +msgid "&Nueva Terminal" +msgstr "&New Terminal" + +#: ../src/mainwindow.cpp:60 +msgid "Salida" +msgstr "Output" + +#: ../src/mainwindow.cpp:97 +msgid "Proyecto OpenGnsys" +msgstr "OpenGnsys Project" + +#: ../src/mainwindow.cpp:145 +msgid "El fichero de log no ha podido ser abierto: " +msgstr "The log file could not be opened: " + +#: ../src/mainwindow.cpp:174 +msgid "Hay otro proceso en ejecución. Por favor espere." +msgstr "There is another process running. Please wait." + +#: ../src/mainwindow.cpp:189 ../src/mainwindow.cpp:228 +msgid "AVISO" +msgstr "WARNING" + +#: ../src/mainwindow.cpp:191 +msgid "" +"La siguiente acción puede modificar datos o tardar varios minutos. El " +"equipo no podrá ser utilizado durante su ejecución." +msgstr "" +"Following action can modify some data or take several minutes. This computer " +"may not be used during execution." + +#: ../src/mainwindow.cpp:192 +msgid "Ejecutar" +msgstr "Run" + +#: ../src/mainwindow.cpp:193 +msgid "Cancelar" +msgstr "Cancel" + +#: ../src/mainwindow.cpp:211 +#, c-format +msgid "%p% Cargando" +msgstr "%p% Loaded" + +#: ../src/mainwindow.cpp:230 +msgid "La página no se puede cargar." +msgstr "Page can not be loaded." + +#: ../src/mainwindow.cpp:232 +msgid "Recargar" +msgstr "Reload" + +#: ../src/mainwindow.cpp:233 +msgid "Abortar" +msgstr "Abort" + +#: ../src/mainwindow.cpp:264 +msgid "Lanzado satisfactoriamente." +msgstr "Successfully launched." + +#: ../src/mainwindow.cpp:298 +msgid "Proceso acabado correctamente. Valor de retorno: " +msgstr "Process completed successfully. Return value: " + +#: ../src/mainwindow.cpp:302 +msgid "El proceso ha fallado inesperadamente. Salida: " +msgstr "The process crashed unexpectedly. Return value: " + +#: ../src/mainwindow.cpp:313 +msgid "Imposible lanzar el proceso." +msgstr "Unable to launch the process." + +#: ../src/mainwindow.cpp:316 +msgid "Error de escritura en el proceso." +msgstr "Error writing to the process." + +#: ../src/mainwindow.cpp:319 +msgid "Error de lectura del proceso." +msgstr "Error reading from the process." + +#: ../src/mainwindow.cpp:327 +msgid "Error desconocido." +msgstr "Unknown error." + +#: ../src/mainwindow.cpp:460 +msgid "Lanzando el comando: " +msgstr "Launching command: " diff --git a/client/browser/src/main.cpp b/client/browser/src/main.cpp index dd3ac6ed..2104e652 100644 --- a/client/browser/src/main.cpp +++ b/client/browser/src/main.cpp @@ -2,18 +2,28 @@ #include #include "mainwindow.h" #include +// Internacionalización con GNU Gettext. +#include +#define TEXTDOMAIN "browser" +#define LOCALEDIR "/opt/opengnsys/lib/locale" +#define CHARSET "UTF-8" int main(int argc, char *argv[]) { + // Preparar internacionalización. + setlocale (LC_ALL, ""); + bindtextdomain (TEXTDOMAIN, LOCALEDIR); + textdomain (TEXTDOMAIN); + if(argc<=1) { - printf("Usage: %s http://siteweb.com/\n",argv[0]); + printf(gettext("Uso: %s -qws http://sitioweb.com/\n"),argv[0]); return -1; } - // Codificación UTF-8. - QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); - QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); - QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); + // Codificación de caracteres. + QTextCodec::setCodecForTr(QTextCodec::codecForName(CHARSET)); + QTextCodec::setCodecForCStrings(QTextCodec::codecForName(CHARSET)); + QTextCodec::setCodecForLocale(QTextCodec::codecForName(CHARSET)); QApplication a(argc, argv); MainWindow w; diff --git a/client/browser/src/mainwindow.cpp b/client/browser/src/mainwindow.cpp index a1f9eaf2..2e799c5e 100644 --- a/client/browser/src/mainwindow.cpp +++ b/client/browser/src/mainwindow.cpp @@ -16,8 +16,10 @@ #include #include #include +#include #include "qtermwidget.h" +#include "digitalclock.h" #define BUFFERSIZE 2048 #define REGEXP_STRING "^\\[(\\d+)\\]" @@ -32,7 +34,7 @@ MainWindow::MainWindow(QWidget *parent) // Graphic showFullScreen(); - setWindowTitle(tr("OpenGnSys Browser")); + setWindowTitle(tr("OpenGnsys Browser")); setCentralWidget(m_web); @@ -50,19 +52,19 @@ MainWindow::MainWindow(QWidget *parent) // TabWidget m_tabs=new QTabWidget(dock); - QPushButton *button=new QPushButton(tr("&Nueva Terminal")); + QPushButton *button=new QPushButton(tr(gettext("&Nueva Terminal"))); button->setFocusPolicy(Qt::TabFocus); m_tabs->setCornerWidget(button); m_tabs->setFocusPolicy(Qt::NoFocus); - m_tabs->addTab(m_output,tr("Salida")); + m_tabs->addTab(m_output,tr(gettext("Salida"))); slotCreateTerminal(); - // Las pestanyas al dock + // Assign tabs to dock dock->setWidget(m_tabs); - // Y el dock al mainwindow - if(m_env.contains("boot") && m_env["boot"] == "admin") + // Assign tabs dock to the mainwindow if admin mode is active + if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") addDockWidget(Qt::BottomDockWidgetArea,dock); // Top Dock @@ -75,19 +77,36 @@ MainWindow::MainWindow(QWidget *parent) // WebBar m_webBar=new QLineEdit(dock); - // WebBar al dock + // WebBar to dock dock->setWidget(m_webBar); - // dock al mainwindow - if(m_env.contains("boot") && m_env["boot"] == "admin") + // Assign top dock to the mainwindow if admin mode is active + if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") addDockWidget(Qt::TopDockWidgetArea,dock); // Status bar QStatusBar* st=statusBar(); st->setSizeGripEnabled(false); + // OpenGnsys logo (or alternate text) + m_logo=new QLabel(); + QPixmap logo; + if(logo.load("/opt/opengnsys/lib/pictures/oglogo.png")) + m_logo->setPixmap(logo); + else + m_logo->setText("OG"); + m_logo->setToolTip(tr(gettext("Proyecto OpenGnsys"))+"\nhttps://opengnsys.es"); + // Progress bar m_progressBar=new QProgressBar(this); - m_progressBar->setMinimum(0); - m_progressBar->setMaximum(100); + m_progressBar->setRange(0,100); + // Connection speed + QString speed=readSpeed(); + m_speedInfo=new QLabel(speed); + m_speedInfo->setAlignment(Qt::AlignCenter); + if(m_env.contains("DEFAULTSPEED") && m_env["DEFAULTSPEED"]!="") + if(speed.compare(m_env["DEFAULTSPEED"])!=0) + m_speedInfo->setStyleSheet("background-color: darkred; color: white; font-weight: bold;"); + // Clock + m_clock=new DigitalClock(this); m_web->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); @@ -97,8 +116,7 @@ MainWindow::MainWindow(QWidget *parent) connect(m_web,SIGNAL(loadStarted()),this,SLOT(slotWebLoadStarted())); connect(m_web,SIGNAL(loadFinished(bool)),this,SLOT(slotWebLoadFinished(bool))); connect(m_web,SIGNAL(loadProgress(int)),this,SLOT(slotWebLoadProgress(int))); - connect(m_web,SIGNAL(urlChanged(const QUrl&)),this, - SLOT(slotUrlChanged(const QUrl&))); + connect(m_web,SIGNAL(urlChanged(const QUrl&)),this,SLOT(slotUrlChanged(const QUrl&))); // Ignore SSL errors. connect(m_web->page()->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*, const QList &)), this, @@ -120,20 +138,19 @@ MainWindow::MainWindow(QWidget *parent) connect(button,SIGNAL(clicked()),this,SLOT(slotCreateTerminal())); connect(m_webBar,SIGNAL(returnPressed()),this,SLOT(slotWebBarReturnPressed())); + // Open the log file for append if(m_env.contains("OGLOGFILE") && m_env["OGLOGFILE"]!="") { - QFile* file=new QFile(m_env["OGLOGFILE"]); - if(!file->open(QIODevice::WriteOnly | QIODevice::Text | - QIODevice::Append)) - { - delete file; - print(tr("El fichero de log no ha podido ser abierto: ")+m_env["OGLOGFILE"]+"."); - } - else - { - m_logfile=file; - m_logstream=new QTextStream(m_logfile); - } + QFile* m_logfile=new QFile(m_env["OGLOGFILE"]); + if(!m_logfile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) + { + delete m_logfile; + print(tr(gettext("El fichero de log no ha podido ser abierto: "))+m_env["OGLOGFILE"]+"."); + } + else + { + m_logstream=new QTextStream(m_logfile); + } } QStringList arguments=QCoreApplication::arguments(); @@ -154,29 +171,29 @@ MainWindow::~MainWindow() void MainWindow::slotLinkHandle(const QUrl &url) { - // Si ya hay un proceso ejectuandose + // Check if it's executing another process if(m_process->state()!=QProcess::NotRunning) { - print(tr("Hay otro proceso en ejecucin. Por favor espere.")); + print(tr(gettext("Hay otro proceso en ejecución. Por favor espere."))); return; } QString urlString = url.toString(); if(urlString.startsWith(COMMAND)) { - // Si es link de tipo COMMAND, ejecutar. + // For COMMAND link, execute executeCommand(urlString.remove(0,QString(COMMAND).length())); } else if(urlString.startsWith(COMMAND_WITH_CONFIRMATION)) { - // Si es link de tipo COMMAND_WITH_CONFIRMATION, pedir confirmacin de ejecutar. + // For COMMAND_WITH_CONFIRMATION link, show confirmation box and execute, if accepted QMessageBox msgBox; msgBox.setIcon(QMessageBox::Question); - msgBox.setWindowTitle(tr("AVISO")); + msgBox.setWindowTitle(tr(gettext("AVISO"))); msgBox.setTextFormat(Qt::RichText); - msgBox.setText(tr("La siguiente acción puede modificar datos o tardar varios minutos. El equipo no podrá ser utilizado durante su ejecución.")); - QPushButton *execButton = msgBox.addButton(tr("Ejecutar"), QMessageBox::ActionRole); - msgBox.addButton(tr("Cancelar"), QMessageBox::RejectRole); + msgBox.setText(tr(gettext("La siguiente acción puede modificar datos o tardar varios minutos. El equipo no podrá ser utilizado durante su ejecución."))); + QPushButton *execButton = msgBox.addButton(tr(gettext("Ejecutar")), QMessageBox::ActionRole); + msgBox.addButton(tr(gettext("Cancelar")), QMessageBox::RejectRole); msgBox.setDefaultButton(execButton); msgBox.exec(); if (msgBox.clickedButton() == execButton) @@ -186,7 +203,7 @@ void MainWindow::slotLinkHandle(const QUrl &url) } else { - // Si es otro link, cargar pgina web. + // For other link, load webpage m_web->load(url); } } @@ -194,7 +211,7 @@ void MainWindow::slotLinkHandle(const QUrl &url) void MainWindow::slotWebLoadStarted() { startProgressBar(); - m_progressBar->setFormat("%p% Cargando"); + m_progressBar->setFormat(gettext("%p% Cargando")); } void MainWindow::slotWebLoadProgress(int progress) @@ -211,12 +228,12 @@ void MainWindow::slotWebLoadFinished(bool ok) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Question); - msgBox.setWindowTitle(tr("AVISO")); + msgBox.setWindowTitle(tr(gettext("AVISO"))); msgBox.setTextFormat(Qt::RichText); - msgBox.setText(tr("La página no se puede cargar.")); + msgBox.setText(tr(gettext("La página no se puede cargar."))); - QPushButton *reloadButton = msgBox.addButton(tr("Recargar"), QMessageBox::ActionRole); - msgBox.addButton(tr("Abortar"), QMessageBox::RejectRole); + QPushButton *reloadButton = msgBox.addButton(tr(gettext("Recargar")), QMessageBox::ActionRole); + msgBox.addButton(tr(gettext("Abortar")), QMessageBox::RejectRole); msgBox.exec(); @@ -247,7 +264,7 @@ void MainWindow::slotSslErrors(QNetworkReply* reply) void MainWindow::slotProcessStarted() { - print(tr("Lanzado satisfactoriamente.")); + m_output->insertPlainText(tr(gettext("Lanzado satisfactoriamente."))); startProgressBar(); } @@ -281,11 +298,11 @@ void MainWindow::slotProcessFinished(int code,QProcess::ExitStatus status) { if(status==QProcess::NormalExit) { - print(tr("Proceso acabado correctamente. Valor de retorno: ")+QString::number(code)); + print(tr(gettext("Proceso acabado correctamente. Valor de retorno: "))+QString::number(code)); } else { - print(tr("El proceso ha fallado inesperadamente. Salida: "+code)); + print(tr(gettext("El proceso ha fallado inesperadamente. Salida: ")+code)); } finishProgressBar(); } @@ -296,13 +313,13 @@ void MainWindow::slotProcessError(QProcess::ProcessError error) switch(error) { case QProcess::FailedToStart: - print(tr("Imposible lanzar el proceso.")); + print(tr(gettext("Imposible lanzar el proceso."))); break; case QProcess::WriteError: - print(tr("Error de escritura en el proceso.")); + print(tr(gettext("Error de escritura en el proceso."))); break; case QProcess::ReadError: - print(tr("Error de lectura del proceso.")); + print(tr(gettext("Error de lectura del proceso."))); break; // No capturo crashed porque la pillo por finished case QProcess::Crashed: @@ -310,7 +327,7 @@ void MainWindow::slotProcessError(QProcess::ProcessError error) break; case QProcess::UnknownError: default: - print(tr("Error desconocido.")); + print(tr(gettext("Error desconocido."))); break; } finishProgressBar(); @@ -391,7 +408,10 @@ void MainWindow::print(QString s) if(!s.endsWith("\n")) s+="\n"; if(m_logstream) + { *m_logstream<flush(); + } if(m_output) m_output->insertPlainText(s); } @@ -411,20 +431,23 @@ void MainWindow::captureOutputForStatusBar(QString output) } } +// Init status bar void MainWindow::startProgressBar() { QStatusBar* st=statusBar(); st->clearMessage(); - st->addWidget(m_progressBar,100); + st->addWidget(m_logo); + st->addWidget(m_progressBar,90); + st->addWidget(m_speedInfo,5); + st->addWidget(m_clock,5); m_progressBar->show(); + m_clock->show(); m_web->setEnabled(false); } void MainWindow::finishProgressBar() { - QStatusBar* st=statusBar(); - st->removeWidget(m_progressBar); - st->showMessage(tr("Listo")); + m_progressBar->reset(); m_web->setEnabled(true); } @@ -434,12 +457,30 @@ void MainWindow::executeCommand(QString &string) QStringList list=string.split(" ",QString::SkipEmptyParts); QString program=list.takeFirst(); m_process->setReadChannel(QProcess::StandardOutput); - // Le ponemos el mismo entorno que tiene el browser ahora mismo + // Assign the same Browser's environment to the process m_process->setEnvironment(QProcess::systemEnvironment()); m_process->start(program,list); - m_output->insertPlainText(tr("Lanzando el comando: ")); + print(tr(gettext("Lanzando el comando: "))); m_output->setTextColor(QColor(Qt::darkGreen)); print(program+" "+list.join(" ")); m_output->setTextColor(QColor(Qt::black)); startProgressBar(); } + +// Returns communication speed +QString MainWindow::readSpeed() { + if(m_env.contains("OGLOGFILE")) + { + QString infoFile=m_env["OGLOGFILE"].replace(".log", ".info.html"); + QString command="grep -hoe \"[0-9]*Mb/s\" "+infoFile+" 2>/dev/null"; + QProcess process; + process.start(command); + process.waitForFinished(); + QString speed(process.readAllStandardOutput()); + return speed.simplified(); + } + else + { + return QString(""); + } +} diff --git a/client/browser/src/mainwindow.h b/client/browser/src/mainwindow.h index 1bcb0c57..e4e02fa3 100644 --- a/client/browser/src/mainwindow.h +++ b/client/browser/src/mainwindow.h @@ -3,8 +3,7 @@ #define COMMAND "command:" #define COMMAND_WITH_CONFIRMATION "commandwithconfirmation:" -#define ENVIRONMENT "OGLOGFILE,boot" -//#define ENVIRONMENT "OGIP,OGSERVER,OGLOG" +#define ENVIRONMENT "OGLOGFILE,ogactiveadmin,DEFAULTSPEED" #include #include @@ -12,6 +11,7 @@ #include #include #include +#include "digitalclock.h" class QWebView; class QTextEdit; @@ -25,6 +25,7 @@ class QTextStream; class QTermWidget; class QProgressBar; class QLineEdit; +class QLabel; class MainWindow : public QMainWindow { @@ -65,12 +66,16 @@ class MainWindow : public QMainWindow void startProgressBar(); void finishProgressBar(); void executeCommand(QString &string); + QString readSpeed(); protected: QWebView *m_web; QTextEdit *m_output; + QLabel *m_logo; QProgressBar *m_progressBar; + QLabel *m_speedInfo; + DigitalClock *m_clock; QTabWidget *m_tabs; QLineEdit *m_webBar; diff --git a/client/browser/src/src.pro b/client/browser/src/src.pro index 9621ff9f..ed5cc824 100644 --- a/client/browser/src/src.pro +++ b/client/browser/src/src.pro @@ -19,10 +19,10 @@ MOC_DIR = ../.moc OBJECTS_DIR = ../.objs TARGET = browser -LIBS += -L.. -lqtermwidget +LIBS += -L.. -lqtermwidget -ldigitalclock SOURCES = main.cpp mainwindow.cpp HEADERS = mainwindow.h -INCLUDEPATH = ../qtermwidget/src +INCLUDEPATH = ../qtermwidget/src ../digitalclock diff --git a/client/engine/Boot.lib b/client/engine/Boot.lib index 0e6f525f..2cda9095 100755 --- a/client/engine/Boot.lib +++ b/client/engine/Boot.lib @@ -4,21 +4,23 @@ #@brief Librería o clase Boot #@class Boot #@brief Funciones para arranque y post-configuración de sistemas de archivos. -#@version 1.0.6 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ #/** -# ogBoot int_ndisk int_npartition +# ogBoot int_ndisk int_nfilesys [str_kernel str_initrd str_krnlparams] #@brief Inicia el proceso de arranque de un sistema de archivos. #@param int_ndisk nº de orden del disco -#@param int_npartition nº de orden de la partición +#@param int_nfilesys nº de orden del sistema de archivos +#@param str_krnlparams parámetros de arranque del kernel (opcional) #@return (activar el sistema de archivos). #@exception OG_ERR_FORMAT Formato incorrecto. #@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo. #@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar. #@exception OG_ERR_NOTOS La partición no tiene instalado un sistema operativo. +#@note En Linux, si no se indican los parámetros de arranque se detectan de la opción por defecto del cargador GRUB. #@note En Linux, debe arrancarse la partición del directorio \c /boot #@version 0.1 - Integración para OpenGnSys. - EAC: HDboot; BootLinuxEX en Boot.lib #@author Antonio J. Doblas Viso, Universidad de Malaga @@ -32,6 +34,9 @@ #@version 1.0.6 - Selección a partir de tipo de sistema operativo (en vez de S.F.) y arrancar Linux con /boot separado. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2015-06-05 +#@version 1.1.0 - Nuevo parámetro opcional con opciones de arranque del Kernel. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2015-07-15 #*/ ## function ogBoot () { @@ -40,12 +45,12 @@ local PART TYPE MNTDIR PARAMS KERNEL INITRD APPEND FILE LOADER f # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \ - "$FUNCNAME 1 1" + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys [str_kernel str_initrd str_kernelparams]" \ + "$FUNCNAME 1 1" "$FUNCNAME 1 2 \"/boot/vmlinuz /boot/initrd.img root=/dev/sda2 ro\"" return fi -# Error si no se reciben 2 parámetros. -[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? +# Error si no se reciben 2 o 3 parámetros. +[ $# == 2 ] || [ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $? # Detectar tipo de sistema de archivos y montarlo. PART=$(ogDiskToDev $1 $2) || return $? @@ -55,12 +60,12 @@ MNTDIR=$(ogMount $1 $2) || return $? case "$TYPE" in Linux|Android) - # Obtiene los parámetros de arranque para Linux. - PARAMS=$(ogLinuxBootParameters $1 $2) + # Si no se indican, obtiene los parámetros de arranque para Linux. + PARAMS="${3:-$(ogLinuxBootParameters $1 $2 2>/dev/null)}" # Si no existe, buscar sistema de archivo /boot en /etc/fstab. if [ -z "$PARAMS" -a -e $MNTDIR/etc/fstab ]; then # Localizar S.F. /boot en /etc/fstab del S.F. actual. - PART=$(ogDevToDisk $(awk '$2=="/boot" {print $1}' $MNTDIR/etc/fstab)) + PART=$(ogDevToDisk $(awk '$1!="#" && $2=="/boot" {print $1}' $MNTDIR/etc/fstab)) # Montar S.F. de /boot. MNTDIR=$(ogMount $PART) || return $? # Buscar los datos de arranque. @@ -92,9 +97,9 @@ case "$TYPE" in dd if=/dev/zero of=${MNTDIR}/ogboot.me bs=1024 count=3 dd if=/dev/zero of=${MNTDIR}/ogboot.firstboot bs=1024 count=3 dd if=/dev/zero of=${MNTDIR}/ogboot.secondboot bs=1024 count=3 - if [ -z "$(ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleannboot')" ]; then - ogAddRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' - ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' "cmd /c del c:\ogboot.*" + if [ -z "$(ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleannboot')" ]; then + ogAddRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' + ogSetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Windows\CurrentVersion\Run\ogcleanboot' "cmd /c del c:\ogboot.*" fi # Activar la partición. ogSetPartitionActive $1 $2 @@ -119,10 +124,10 @@ esac #/** -# ogGetWindowsName int_ndisk int_npartition +# ogGetWindowsName int_ndisk int_nfilesys #@brief Muestra el nombre del equipo en el registro de Windows. #@param int_ndisk nº de orden del disco -#@param int_npartition nº de orden de la partición +#@param int_nfilesys nº de orden del sistema de archivos #@return str_name - nombre del equipo #@exception OG_ERR_FORMAT Formato incorrecto. #@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo. @@ -196,7 +201,7 @@ MNTDIR=$(ogMount $1 $2) || return $? # Fichero de configuración de GRUB. CONFDIR=$MNTDIR # Sistema de archivos de arranque (/boot). [ -d $MNTDIR/boot ] && CONFDIR=$MNTDIR/boot # Sist. archivos raíz con directorio boot. -for f in $MNTDIR/{,grubPARTITION/}{,boot/}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg,grub.cfg.backup.og}; do +for f in $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do [ -r $f ] && CONFFILE=$f done [ -n "$CONFFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "grub.cfg" || return $? @@ -212,6 +217,7 @@ awk 'BEGIN {cont=-1;} if (def ~ /saved_entry/) def=0; } $1~/^(title|menuentry)$/ {cont++} + $1~/^set$/ && $2~/^root=.\(hd'$[1-1]',(msdos|gpt)'$2'\).$/ { if (def==0) def=cont; } $1~/^(kernel|linux(16|efi)?)$/ { if (def==cont) { kern=$2; sub($1,""); sub($1,""); sub(/^[ \t]*/,""); app=$0 @@ -456,12 +462,15 @@ rm -f $FILE #@version 1.0.5 - Soporte para Windows 8 y Windows 8.1. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2014-01-28 +#@version 1.1.0 - Soporte para Windows 10. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-01-19 #*/ ## function ogWindowsBootParameters () { # Variables locales. -local PART DISK FILE VERSION WINVER MOUNT +local PART DISK FILE WINVER MOUNT # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -480,31 +489,16 @@ let DISK=$1-1 PART=$2 FILE=/tmp/temp$$ -VERSION=$(ogGetOsVersion $1 $2) +# Obtener versión de Windows. +WINVER=$(ogGetOsVersion $1 $2 | awk -F"[: ]" '$1=="Windows" {if ($3=="Server") print $2,$3,$4; else print $2,$3;}') +[ -z "$WINVER" ] && return $(ogRaiseError $OG_ERR_NOTOS "Windows"; echo $?) -if echo "$VERSION" | grep "Windows 10" -then - WINVER="Windows 10" -elif echo "$VERSION" | grep "Windows 8.1" -then - WINVER="Windows 8.1" -elif echo "$VERSION" | grep "Windows 8" -then - WINVER="Windows 8" -elif echo "$VERSION" | grep "Windows 7" -then - WINVER="Windows 7" -elif echo "$VERSION" | grep "Windows Seven" -then - WINVER="Windows Vista" -elif echo "$VERSION" | grep "XP" -then - MOUNT=$(ogMount $1 $2) - [ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTOS; echo $?) - cat ${MOUNT}/boot.ini | sed s/partition\([0-9]\)/partition\($PART\)/g | sed s/rdisk\([0-9]\)/rdisk\($DISK\)/g > ${MOUNT}/tmp.boot.ini; mv ${MOUNT}/tmp.boot.ini ${MOUNT}/boot.ini - return 0 -else - return $(ogRaiseError $OG_ERR_NOTOS; echo $?) +# Acciones para Windows XP. +if [[ "$WINVER" =~ "XP" ]]; then + MOUNT=$(ogMount $1 $2) + [ -f ${MOUNT}/boot.ini ] || return $(ogRaiseError $OG_ERR_NOTFOUND "boot.ini"; echo $?) + cat ${MOUNT}/boot.ini | sed s/partition\([0-9]\)/partition\($PART\)/g | sed s/rdisk\([0-9]\)/rdisk\($DISK\)/g > ${MOUNT}/tmp.boot.ini; mv ${MOUNT}/tmp.boot.ini ${MOUNT}/boot.ini + return 0 fi ogUnmount $1 $2 || return $(ogRaiseError $OG_ERR_PARTITION; echo $?) @@ -653,8 +647,8 @@ ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null } -# ogGrubInstallMbr int_disk_GRUBCFG int_partition_GRUBCFG #@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default] -#@brief Instala y actualiza el gestor grub el el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows. +# ogGrubInstallMbr int_disk_GRUBCFG int_partition_GRUBCFG +#@brief Instala el grub el el MBR del primer disco duro (FIRSTSTAGE). El fichero de configuración grub.cfg ubicado según parametros disk y part(SECONDSTAGE). Admite sistemas Windows. #@param int_disk_SecondStage #@param int_part_SecondStage #@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default] @@ -669,6 +663,12 @@ ps aux > /dev/null | grep $! | grep -E "T|S" | kill -9 $! > /dev/null #@version 1.0.3 - Ficheros de configuracion independientes segun ubicación de la primera etapa #@author Antonio J. Doblas Viso. Universidad de Malaga. #@date 2012-03-13 +#@version 1.1.0 - #791 El FIRSTSTAGE(MBR) siempre será el primer disco duro. EL SECONDSTAGE(grub.cfg) estára en el DISK y PART indicados en los parámetros. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2017-06-19 +#@version 1.1.0 - #827 Entrada para el ogLive si el equipo tiene partición cache. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2018-01-21 #*/ ## function ogGrubInstallMbr { @@ -698,8 +698,8 @@ BACKUPNAME=".backup.og" #VERSION=$(ogGetOsVersion $DISK $PART) #echo $VERSION | grep "Linux" || return $(ogRaiseError $OG_ERR_NOTOS "no es linux"; echo $?) -#Localizar primera etapa del grub -FIRSTSTAGE=$(ogDiskToDev $DISK) +#La primera etapa del grub se fija en el primer disco duro +FIRSTSTAGE=$(ogDiskToDev 1) #localizar disco segunda etapa del grub SECONDSTAGE=$(ogMount $DISK $PART) @@ -726,6 +726,10 @@ then fi # SI Reconfigurar segunda etapa (grub.cfg) == TRUE + +#llamada a updateBootCache para que aloje la primera fase del ogLive +updateBootCache + #Configur la sintaxis grub para evitar menus de "recovery" en el OGLive echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub @@ -735,9 +739,9 @@ echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub #Preparar configuración segunda etapa: crear ubicacion mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/ -#Preparar configuración segunda etapa: crear cabecera del fichero +#Preparar configuración segunda etapa: crear cabecera del fichero (ignorar errores) sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header -/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg +/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null #Preparar configuración segunda etapa: crear entrada del sistema operativo grubSyntax "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg @@ -825,9 +829,9 @@ echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub #Preparar configuración segunda etapa: crear ubicacion mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/ -#Preparar configuración segunda etapa: crear cabecera del fichero +#Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores) sed -i 's/^set -e/#set -e/' /etc/grub.d/00_header -/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg +/etc/grub.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg 2>/dev/null #Preparar configuración segunda etapa: crear entrada del sistema operativo grubSyntax $DISK $PART "$KERNELPARAM" >> ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/grub/grub.cfg @@ -846,7 +850,7 @@ grub-install --force --root-directory=${SECONDSTAGE}${PREFIXSECONDSTAGE} $FIRSTS #@exception OG_ERR_NOTFOUND No se encuentra el fichero fstab a procesar. #@warning Puede haber un error si hay más de 1 partición swap. #@version 1.0.5 - Primera versión para OpenGnSys. Solo configura la SWAP -#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@author Antonio J. Doblas Viso. Universidad de Malaga. #@date 2013-03-21 #@version 1.0.6b - correccion. Si no hay partición fisica para la SWAP, eliminar entrada del fstab. #@author Antonio J. Doblas Viso. Universidad de Malaga. @@ -1003,7 +1007,7 @@ MNTDIR=$(ogMount $1 $2) || return $? } #/** -# ogGrubAddOgclient num_disk num_part [ timeout ] [ offline ] +# ogGrubAddOgLive num_disk num_part [ timeout ] [ offline ] #@brief Crea entrada de menu grub para ogclient, tomando como paramentros del kernel los actuales del cliente. #@param 1 Numero de disco #@param 2 Numero de particion @@ -1014,9 +1018,18 @@ MNTDIR=$(ogMount $1 $2) || return $? #@exception OG_ERR_NOTFOUND No existe kernel o initrd en cache. #@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub. # /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos. +#@version 1.0.6 - Prmera integración +#@author +#@date 2016-11-07 +#@version 1.1.0 - Se renombra funcion para adaptacion al cambio de nombre de ogclient a ogLive. Soporta varios ogLives en la cache. Se añade el ogLive asignado al cliente. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2017-06-17 +#*/ ## +#*/ ## + #*/ -ogGrubAddOgclient () { +function ogGrubAddOgLive () { local TIMEOUT DIRMOUNT GRUBGFC PARTTABLETYPE NUMDISK NUMPART KERNEL STATUS NUMLINE MENUENTRY # Si se solicita, mostrar ayuda. @@ -1033,7 +1046,7 @@ ogGrubAddOgclient () { # Error si no existe el kernel y el initrd en la cache. # Falta crear nuevo codigo de error. - [ -r $OGCAC/boot/ogvmlinuz -a -r $OGCAC/boot/oginitrd.img ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "CACHE: ogvmlinuz, oginitrd.img" 1>&2; echo $?) + [ -r $OGCAC/boot/${oglivedir}/ogvmlinuz -a -r $OGCAC/boot/${oglivedir}/oginitrd.img ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "CACHE: ogvmlinuz, oginitrd.img" 1>&2; echo $?) # Archivo de configuracion del grub DIRMOUNT=$(ogMount $1 $2) @@ -1042,8 +1055,8 @@ ogGrubAddOgclient () { # Error si no existe archivo del grub [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "$GRUBGFC" 1>&2; echo $?) - # Si existe la entrada de opengnsys nos salimos. - grep "menuentry Opengnsys" $GRUBGFC &>/dev/null && return 0 + # Si existe la entrada de opengnsys, se borra + grep -q "menuentry Opengnsys" $GRUBGFC && sed -ie "/menuentry Opengnsys/,+6d" $GRUBGFC # Tipo de tabla de particiones PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:]) @@ -1052,7 +1065,7 @@ ogGrubAddOgclient () { read NUMDISK NUMPART <<< $(ogFindCache) let NUMDISK=$NUMDISK-1 # kernel y sus opciones. Pasamos a modo usuario - KERNEL="/boot/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=true/ogactiveadmin=false/g /proc/cmdline)" + KERNEL="/boot/${oglivedir}/ogvmlinuz $(sed -e s/^.*linuz//g -e s/ogactiveadmin=[a-z]*//g /proc/cmdline)" # Configuracion offline si existe parametro echo "$@" |grep offline &>/dev/null && STATUS=offline @@ -1062,12 +1075,12 @@ ogGrubAddOgclient () { # Numero de línea de la primera entrada del grub. NUMLINE=$(grep -n -m 1 "^menuentry" $GRUBGFC|cut -d: -f1) # Texto de la entrada de opengnsys -MENUENTRY="menuentry "Opengnsys" --class gnu-linux --class gnu --class os { \n \ +MENUENTRY="menuentry "OpenGnsys" --class opengnsys --class gnu --class os { \n \ \tinsmod part_$PARTTABLETYPE \n \ \tinsmod ext2 \n \ \tset root='(hd${NUMDISK},$PARTTABLETYPE${NUMPART})' \n \ \tlinux $KERNEL \n \ -\tinitrd /boot/oginitrd.img \n \ +\tinitrd /boot/${oglivedir}/oginitrd.img \n \ }" @@ -1081,120 +1094,1075 @@ MENUENTRY="menuentry "Opengnsys" --class gnu-linux --class gnu --class os { \n [ $TIMEOUT ] && sed -i s/timeout=.*$/timeout=$TIMEOUT/g $GRUBGFC } - #/** # ogGrubHidePartitions num_disk num_part -#@brief Configura el grub para que oculte las particiones de windows que no se esten iniciando. +#@see ogBootLoaderHidePartitions +#*/ +function ogGrubHidePartitions { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \ + "$FUNCNAME 1 6" + return + fi + ogBootLoaderHidePartitions $@ + return $? +} + +#/** +# ogBurgHidePartitions num_disk num_part +#@see ogBootLoaderHidePartitions +#*/ +function ogBurgHidePartitions { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \ + "$FUNCNAME 1 6" + return + fi + ogBootLoaderHidePartitions $@ + return $? +} + +#/** +# ogBootLoaderHidePartitions num_disk num_part +#@brief Configura el grub/burg para que oculte las particiones de windows que no se esten iniciando. #@param 1 Numero de disco #@param 2 Numero de particion #@return (nada) #@exception OG_ERR_FORMAT Formato incorrecto. -#@exception No existe archivo de configuracion del grub. -#@ /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos. +#@exception No existe archivo de configuracion del grub/burg. +#@version 1.1 Se comprueban las particiones de Windows con blkid (y no con grub.cfg) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-11-17 +#@version 1.1 Se generaliza la función para grub y burg +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017-10-20 #*/ -function ogGrubHidePartitions { - local DIRMOUNT GRUBGFC PARTTABLETYPE WINENTRY ENTRY TEXT ENTRY2 LINE2 PART2 HIDDEN +function ogBootLoaderHidePartitions { + local FUNC DIRMOUNT GFCFILE PARTTABLETYPE WINENTRY ENTRY PART TEXT LINE2 PART2 HIDDEN # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition" \ - "$FUNCNAME 1 6" + ogHelp "$FUNCNAME" "$MSG_SEE ogGrubHidePartitions ogBurgHidePartitions" return fi + # Nombre de la función que llama a esta. + FUNC="${FUNCNAME[@]:1}" + FUNC="${FUNC%%\ *}" + # Error si no se reciben 2 parámetros. [ $# -lt 2 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?) # Archivo de configuracion del grub DIRMOUNT=$(ogMount $1 $2) - GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg" + # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions. + case "$FUNC" in + ogGrubHidePartitions) + CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg" + ;; + ogBurgHidePartitions) + CFGFILE="$DIRMOUNT/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogGrubHidePartitions or ogBurgHidePartitions." + return $? + ;; + esac # Error si no existe archivo del grub - [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "$GRUBGFC" 1>&2; echo $?) + [ -r $CFGFILE ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "$CFGFILE" 1>&2; echo $?) - # Si solo hay una entrada de Windows me salgo - [ $(grep -n "menuentry.*Windows" $GRUBGFC |wc -l) -eq 1 ] && return 0 + # Si solo hay una particion de Windows me salgo + [ $(fdisk -l $(ogDiskToDev $1) | grep 'NTFS' |wc -l) -eq 1 ] && return 0 # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion. - sed -i '/parttool/d' $GRUBGFC + sed -i '/parttool/d' $CFGFILE PARTTABLETYPE=$(ogGetPartitionTableType $1 | tr [:upper:] [:lower:]) # Entradas de Windows: numero de linea y particion. De mayor a menor. - WINENTRY=$(awk '/menuentry.*Windows/ { gsub(/\/dev\/sda/,""); gsub(/\)\"/, ""); print NR":"$6} ' $GRUBGFC | sed '1!G;h;$!d' ) + WINENTRY=$(awk '/menuentry.*Windows/ {gsub(/\)\"/, ""); print NR":"$6} ' $CFGFILE | sed -e '1!G;h;$!d' -e s/[a-z\/]//g) + # Particiones de Windows, pueden no estar en el grub. + WINPART=$(fdisk -l $(ogDiskToDev $1)|awk '/NTFS/ {print substr($1,9,1)}' |sed '1!G;h;$!d') # Modifico todas las entradas de Windows. for ENTRY in $WINENTRY; do LINE=${ENTRY%:*} + PART=${ENTRY#*:} # En cada entrada, oculto o muestro cada particion. TEXT="" - for ENTRY2 in $WINENTRY; do - LINE2=${ENTRY2%:*} - PART2=${ENTRY2#*:} + for PART2 in $WINPART; do # Muestro solo la particion de la entrada actual. - [ $LINE2 -eq $LINE ] && HIDDEN="-" || HIDDEN="+" + [ $PART2 -eq $PART ] && HIDDEN="-" || HIDDEN="+" TEXT="\tparttool (hd0,$PARTTABLETYPE$PART2) hidden$HIDDEN \n$TEXT" done - sed -i "${LINE}a\ $TEXT" $GRUBGFC + sed -i "${LINE}a\ $TEXT" $CFGFILE done # Activamos la particion que se inicia en todas las entradas de windows. - sed -i "/chainloader/i\\\tparttool \$\{root\} boot+" $GRUBGFC + sed -i "/chainloader/i\\\tparttool \$\{root\} boot+" $CFGFILE } #/** -# ogGrubDeleteEntry num_disk num_part num_part_delete +# ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete +#@see ogBootLoaderDeleteEntry +#*/ +function ogGrubDeleteEntry { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \ + "$FUNCNAME 1 6 2 1" + return + fi + ogBootLoaderDeleteEntry $@ + return $? +} + +#/** +# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete +#@see ogBootLoaderDeleteEntry +#*/ +function ogBurgDeleteEntry { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_delete int_npartition_delete" \ + "$FUNCNAME 1 6 2 1" + return + fi + ogBootLoaderDeleteEntry $@ + return $? +} + +#/** +# ogBootLoaderDeleteEntry num_disk num_part num_part_delete #@brief Borra en el grub las entradas para el inicio en una particion. #@param 1 Numero de disco donde esta el grub #@param 2 Numero de particion donde esta el grub -#@parm 3 Numero de la particion de la que borramos las entradas +#@param 3 Numero del disco del que borramos las entradas +#@param 4 Numero de la particion de la que borramos las entradas +#@note Tiene que ser llamada desde ogGrubDeleteEntry o ogBurgDeleteEntry #@return (nada) +#@exception OG_ERR_FORMAT Use ogGrubDeleteEntry or ogBurgDeleteEntry. #@exception OG_ERR_FORMAT Formato incorrecto. -#@exception No existe archivo de configuracion del grub. -#@ /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos. +#@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub. +#@version 1.1 Se generaliza la función para grub y burg +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017-10-20 #*/ - - -function ogGrubDeleteEntry { - local DIRMOUNT GRUBGFC MENUENTRY DELETEENTRY ENDENTRY ENTRY +function ogBootLoaderDeleteEntry { + local FUNC DIRMOUNT CFGFILE DEVICE MENUENTRY DELETEENTRY ENDENTRY ENTRY # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_npartition_delete" \ - "$FUNCNAME 1 6 2" + ogHelp "$FUNCNAME" "$MSG_SEE ogBurgDeleteEntry ogGrubDeleteEntry" return fi - # Error si no se reciben 3 parámetros. - [ $# -lt 3 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part"; echo $?) + # Si el número de parámetros menos que 4 nos salimos + [ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME num_disk num_part num_disk_delete num_part_delete"; echo $?) + + + # Nombre de la función que llama a esta. + FUNC="${FUNCNAME[@]:1}" + FUNC="${FUNC%%\ *}" # Archivo de configuracion del grub DIRMOUNT=$(ogMount $1 $2) - GRUBGFC="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg" + # La función debe ser llamanda desde ogGrubDeleteEntry or ogBurgDeleteEntry. + case "$FUNC" in + ogGrubDeleteEntry) + CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg" + ;; + ogBurgDeleteEntry) + CFGFILE="$DIRMOUNT/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogGrubDeleteEntry or ogBurgDeleteEntry." + return $? + ;; + esac + + # Dispositivo + DEVICE=$(ogDiskToDev $3 $4) # Error si no existe archivo del grub) - [ -r $GRUBGFC ] || return $(ogRaiseError log session $OG_ERR_NOTFOUND "$GRUBGFC"; echo $?) + [ -r $CFGFILE ] || ogRaiseError log session $OG_ERR_NOTFOUND "$CFGFILE" || return $? - # Numero de linea de cada entrada, de mayor a menor. - MENUENTRY="$(grep -n -e menuentry.*/dev/sda $GRUBGFC| cut -d: -f1 | sed '1!G;h;$!d' )" + # Numero de linea de cada entrada. + MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | sed '1!G;h;$!d' )" # Entradas que hay que borrar. - DELETEENTRY=$(grep -n menuentry.*/dev/sda$3 $GRUBGFC| cut -d: -f1) + DELETEENTRY=$(grep -n menuentry.*$DEVICE $CFGFILE| cut -d: -f1) + + # Si no hay entradas para borrar me salgo con aviso + [ "$DELETEENTRY" != "" ] || ogRaiseError log session $OG_ERR_NOTFOUND "Menuentry $DEVICE" || return $? # Recorremos el fichero del final hacia el principio. - ENDENTRY="$(wc -l $GRUBGFC|cut -d" " -f1)" + ENDENTRY="$(wc -l $CFGFILE|cut -d" " -f1)" for ENTRY in $MENUENTRY; do # Comprobamos si hay que borrar la entrada. if ogCheckStringInGroup $ENTRY "$DELETEENTRY" ; then let ENDENTRY=$ENDENTRY-1 - sed -i -e $ENTRY,${ENDENTRY}d $GRUBGFC + sed -i -e $ENTRY,${ENDENTRY}d $CFGFILE fi # Guardamos el número de línea de la entrada, que sera el final de la siguiente. ENDENTRY=$ENTRY done +} + + +# ogBurgInstallMbr int_disk_GRUBCFG int_partition_GRUBCFG +#@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default] +#@brief Instala y actualiza el gestor grub en el MBR del disco duro donde se encuentra el fichero grub.cfg. Admite sistemas Windows. +#@param int_disk_SecondStage +#@param int_part_SecondStage +#@param bolean_Check_Os_installed_and_Configure_2ndStage true | false[default] +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Partición no soportada +#@version 1.1.0 - Primeras pruebas instalando BURG. Codigo basado en el ogGrubInstallMBR. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2017-06-23 +#@version 1.1.0 - Redirección del proceso de copiado de archivos y de la instalacion del binario +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2018-01-21 +#@version 1.1.0 - Refactorizar fichero de configuacion +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2018-01-24 +#*/ ## + +function ogBurgInstallMbr { + +# Variables locales. +local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage bolean_Configure_2ndStage \"param param \" " \ + "$FUNCNAME 1 1 FALSE " \ + "$FUNCNAME 1 1 TRUE \"nomodeset irqpoll pci=noacpi quiet splash \" " + return +fi + +# Error si no se reciben 2 parametros. +[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?) + + +DISK=$1; PART=$2; +CHECKOS=${3:-"FALSE"} +KERNELPARAM=$4 +BACKUPNAME=".backup.og" + +#Error si no es linux. +ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?) + + +#La primera etapa del grub se fija en el primer disco duro +FIRSTSTAGE=$(ogDiskToDev 1) + +#localizar disco segunda etapa del grub +SECONDSTAGE=$(ogMount $DISK $PART) + +# prepara el directorio principal de la segunda etapa (y copia los binarios) +[ -d ${SECONDSTAGE}/boot/burg/ ] || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/* ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; cp -prv $OGLIB/burg/* ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; + +#Copiamos el tema +mkdir -p ${SECONDSTAGE}/boot/burg/themes/OpenGnsys +cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null + +#Localizar directorio segunda etapa del grub +#PREFIXSECONDSTAGE="/boot/burg/" + +# Si Reconfigurar segunda etapa (grub.cfg) == FALSE +if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ] +then + if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ] + then + burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null + return $? + fi +fi + +# SI Reconfigurar segunda etapa (burg.cfg) == TRUE + +#llamada a updateBootCache para que aloje la primera fase del ogLive +updateBootCache + +#Configur la sintaxis grub para evitar menus de "recovery" en el OGLive +echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub +echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub + + +#Preparar configuración segunda etapa: crear ubicacion +mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/ + +#Preparar configuración segunda etapa: crear cabecera del fichero +#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg + +FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg + +cat > "$FILECFG" << EOF + +set theme_name=OpenGnsys +set gfxmode=1024x768 + + +set locale_dir=(\$root)/boot/burg/locale + +set default=0 +set timeout=25 +set lang=es + + +insmod ext2 +insmod gettext + + + + +if [ -s \$prefix/burgenv ]; then + load_env +fi + + + +if [ \${prev_saved_entry} ]; then + set saved_entry=\${prev_saved_entry} + save_env saved_entry + set prev_saved_entry= + save_env prev_saved_entry + set boot_once=true +fi + +function savedefault { + if [ -z \${boot_once} ]; then + saved_entry=\${chosen} + save_env saved_entry + fi +} +function select_menu { + if menu_popup -t template_popup theme_menu ; then + free_config template_popup template_subitem menu class screen + load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name} + save_env theme_name + menu_refresh + fi +} + +function toggle_fold { + if test -z $theme_fold ; then + set theme_fold=1 + else + set theme_fold= + fi + save_env theme_fold + menu_refresh +} +function select_resolution { + if menu_popup -t template_popup resolution_menu ; then + menu_reload_mode + save_env gfxmode + fi +} + + +if test -f \${prefix}/themes/\${theme_name}/theme ; then + insmod coreui + menu_region.text + load_string '+theme_menu { -OpenGnsys { command="set theme_name=OpenGnsys" }}' + load_config \${prefix}/themes/conf.d/10_hotkey + load_config \${prefix}/themes/\${theme_name}/theme \${prefix}/themes/custom/theme_\${theme_name} + insmod vbe + insmod png + insmod jpeg + set gfxfont="Unifont Regular 16" + menu_region.gfx + vmenu resolution_menu + controller.ext +fi + + +EOF + + +#Preparar configuración segunda etapa: crear entrada del sistema operativo +grubSyntax "$KERNELPARAM" >> "$FILECFG" + + +#Instalar el burg +burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null +} + +#/** +# ogGrubDefaultEntry int_disk_GRUGCFG int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry +#@see ogBootLoaderDefaultEntry +#*/ +function ogGrubDefaultEntry { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \ + "$FUNCNAME 1 6 1 1" + return + fi + ogBootLoaderDefaultEntry $@ + return $? +} + +#/** +# ogBurgDefaultEntry int_disk_BURGCFG int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry +#@see ogBootLoaderDefaultEntry +#*/ +function ogBurgDefaultEntry { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry" \ + "$FUNCNAME 1 6 1 1" + return + fi + ogBootLoaderDefaultEntry $@ + return $? +} + +#/** +# ogBootLoaderDefaultEntry int_disk_CFG int_partition_CFG int_disk_default_entry int_npartition_default_entry +#@brief Configura la entrada por defecto de Burg +#@param int_disk_SecondStage +#@param int_part_SecondStage +#@param int_disk_default_entry +#@param int_part_default_entry +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount). +#@exception OG_ERR_OUTOFLIMIT Param $3 no es entero. +#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: burg.cfg. +#@version 1.1.0 - Define la entrada por defecto del Burg +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017-08-09 +#@version 1.1 Se generaliza la función para grub y burg +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2018-01-04 +#*/ ## +function ogBootLoaderDefaultEntry { + +# Variables locales. +local PART CFGFILE DEFAULTENTRY MSG + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$MSG_SEE ogGrubDefaultEntry ogBurgDefaultEntry" + return +fi + +# Nombre de la función que llama a esta. +FUNC="${FUNCNAME[@]:1}" +FUNC="${FUNC%%\ *}" + +# Error si no se reciben 3 parametros. +[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_disk_default_entry int_partitions_default_entry" || return $? + +# Error si no puede montar sistema de archivos. +DIRMOUNT=$(ogMount $1 $2) || return $? + +# Comprobamos que exista fichero de configuración +# La función debe ser llamanda desde ogGrubDefaultEntry or ogBurgDefaultEntry. +case "$FUNC" in + ogGrubDefaultEntry) + CFGFILE="$DIRMOUNT/boot/grubMBR/boot/grub/grub.cfg" + ;; + ogBurgDefaultEntry) + CFGFILE="$DIRMOUNT/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogGrubDefaultEntry or ogBurgDefaultEntry." + return $? + ;; +esac + +# Error si no existe archivo de configuración +[ -r $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $? + +# Dispositivo +DEVICE=$(ogDiskToDev $3 $4) + +# Número de línea de la entrada por defecto en CFGFILE (primera de la partición). +DEFAULTENTRY=$(grep -n -m 1 menuentry.*$DEVICE $CFGFILE| cut -d: -f1) + +# Si no hay entradas para borrar me salgo con aviso +[ "$DEFAULTENTRY" != "" ] || ogRaiseError session log $OG_ERR_NOTFOUND "No menuentry $DEVICE" || return $? + +# Número de la de linea por defecto en el menú de usuario +MENUENTRY="$(grep -n -e menuentry $CFGFILE| cut -d: -f1 | grep -n $DEFAULTENTRY |cut -d: -f1)" +# Las líneas empiezan a contar desde cero +let MENUENTRY=$MENUENTRY-1 + +sed --regexp-extended -i s/"set default=\"?[0-9]*\"?"/"set default=\"$MENUENTRY\""/g $CFGFILE + +MSG="MSG_HELP_$FUNC" +echo "${!MSG%%\.}: $@" +} + +#/** +# ogGrubOgliveDefaultEntry num_disk num_part +#@see ogBootLoaderOgliveDefaultEntry +#*/ +function ogGrubOgliveDefaultEntry { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \ + "$FUNCNAME 1 6" + return + fi + ogBootLoaderOgliveDefaultEntry $@ + return $? +} + +#/** +# ogBurgOgliveDefaultEntry num_disk num_part +#@see ogBootLoaderOgliveDefaultEntry +#*/ +function ogBurgOgliveDefaultEntry { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" \ + "$FUNCNAME 1 6" + return + fi + ogBootLoaderOgliveDefaultEntry $@ + return $? +} + +#/** +# ogBootLoaderOgliveDefaultEntry +#@brief Configura la entrada de ogLive como la entrada por defecto de Burg. +#@param int_disk_SecondStage +#@param int_part_SecondStage +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount). +#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: burg.cfg. +#@exception OG_ERR_NOTFOUND Entrada de OgLive no encontrada en burg.cfg. +#@version 1.1.0 - Primeras pruebas con Burg +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017-08-09 +#@version 1.1 Se generaliza la función para grub y burg +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2018-01-04 +#*/ ## +function ogBootLoaderOgliveDefaultEntry { + +# Variables locales. +local FUNC PART CFGFILE NUMENTRY MSG + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$MSG_SEE ogGrubOgliveDefaultEntry ogBurgOgliveDefaultEntry" \ + return +fi + +# Nombre de la función que llama a esta. +FUNC="${FUNCNAME[@]:1}" +FUNC="${FUNC%%\ *}" + +# Error si no se reciben 2 parametros. +[ $# -eq 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage" || return $? + +# Error si no puede montar sistema de archivos. +PART=$(ogMount $1 $2) || return $? +# La función debe ser llamanda desde ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry. +case "$FUNC" in + ogGrubOgliveDefaultEntry) + CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" + ;; + ogBurgOgliveDefaultEntry) + CFGFILE="$PART/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogGrubOgliveDefaultEntry or ogBurgOgliveDefaultEntry." + return $? + ;; +esac + +# Comprobamos que exista fichero de configuración +[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $? + +# Detectamos cual es la entrada de ogLive +NUMENTRY=$(grep ^menuentry $CFGFILE| grep -n "OpenGnsys Live"|cut -d: -f1) + +# Si no existe entrada de ogLive nos salimos +[ -z "$NUMENTRY" ] && (ogRaiseError $OG_ERR_NOTFOUND "menuentry OpenGnsys Live in $CFGFILE" || return $?) + +let NUMENTRY=$NUMENTRY-1 +sed --regexp-extended -i s/"set default=\"?[0-9]+\"?"/"set default=\"$NUMENTRY\""/g $CFGFILE + +MSG="MSG_HELP_$FUNC" +echo "${!MSG%%\.}: $@" +} + + +#/** +# ogGrubSetTheme num_disk num_part str_theme +#@see ogBootLoaderSetTheme +#*/ +function ogGrubSetTheme { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \ + "$FUNCNAME 1 4 ThemeBasic"\ + "$FUNCNAME \$(ogFindCache) ThemeBasic" + return + fi + ogBootLoaderSetTheme $@ + return $? +} + +#/** +# ogBurgSetTheme num_disk num_part str_theme +#@see ogBootLoaderSetTheme +#*/ +function ogBurgSetTheme { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" \ + "$FUNCNAME 1 4 ThemeBasic" \ + "$FUNCNAME \$(ogFindCache) ThemeBasic" + echo "Temas disponibles:\ $(ls $OGCAC/boot/burg/themes/)" + + return + fi + ogBootLoaderSetTheme $@ + return $? +} + + + +#/** +# ogBootLoaderSetTheme +#@brief asigna un tema al BURG +#@param int_disk_SecondStage +#@param int_part_SecondStage +#@param str_theme_name +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount). +#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg. +#@exception OG_ERR_NOTFOUND Entrada deltema no encontrada en burg.cfg. +#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado. +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2018-01-24 +#*/ ## +function ogBootLoaderSetTheme { + +# Variables locales. +local FUNC PART CFGFILE THEME NEWTHEME BOOTLOADER MSG + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTheme ogBurgSetTheme" + return +fi + + +NEWTHEME="$3" + +# Nombre de la función que llama a esta. +FUNC="${FUNCNAME[@]:1}" +FUNC="${FUNC%%\ *}" + + + +# Error si no se reciben 2 parametros. +[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_themeName" || return $? + +# Error si no puede montar sistema de archivos. +PART=$(ogMount $1 $2) || return $? +# La función debe ser llamanda desde ogGrubSetTheme or ogBurgSetTheme. +case "$FUNC" in + ogGrubSetTheme) + BOOTLOADER="grug" + BOOTLOADERDIR="grubMBR" + CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" + ogRaiseError $OG_ERR_FORMAT "ogGrubSetTheme not sopported" + return $? + ;; + ogBurgSetTheme) + BOOTLOADER="burg" + BOOTLOADERDIR="burg" + CFGFILE="$PART/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTheme or ogBurgSetTheme." + return $? + ;; +esac + +# Comprobamos que exista fichero de configuración +[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $? + +# Detectamos cual es el tema asignado +THEME=$(grep "set theme_name=" $CFGFILE | grep ^set | cut -d= -f2) + +# Si no existe entrada de theme_name nos salimos +[ -z "$THEME" ] && (ogRaiseError $OG_ERR_NOTFOUND "theme_name in $CFGFILE" || return $?) + +#Actualizamos el tema del servidor a la particion +if [ -d $OGLIB/$BOOTLOADER/themes/$NEWTHEME ]; then + cp -pr $OGLIB/$BOOTLOADER/themes/$NEWTHEME $PART/boot/$BOOTLOADERDIR/themes/ +fi + +#Verificamos que el tema esta en la particion +if ! [ -d $PART/boot/$BOOTLOADERDIR/themes/$NEWTHEME ]; then + ogRaiseError $OG_ERR_NOTFOUND "theme_name=$NEWTHEME in $PART/boot/$BOOTLOADERDIR/themes/" || return $? +fi + +#Cambiamos la entrada el fichero de configuración. +sed --regexp-extended -i s/"$THEME"/"$NEWTHEME"/g $CFGFILE + + +} + +#/** +# ogGrubSetAdminKeys num_disk num_part str_theme +#@see ogBootLoaderSetTheme +#*/ +function ogGrubSetAdminKeys { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \ + "$FUNCNAME 1 4 FALSE "\ + "$FUNCNAME \$(ogFindCache) ThemeBasic" + return + fi + ogBootLoaderSetAdminKeys $@ + return $? +} + +#/** +# ogBurgSetAdminKeys num_disk num_part str_bolean +#@see ogBootLoaderSetAdminKeys +#*/ +function ogBurgSetAdminKeys { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" \ + "$FUNCNAME 1 4 TRUE" \ + "$FUNCNAME \$(ogFindCache) FALSE" + return + fi + ogBootLoaderSetAdminKeys $@ + return $? +} + + + +#/** +# ogBootLoaderSetAdminKeys +#@brief Activa/Desactica las teclas de administracion +#@param int_disk_SecondStage +#@param int_part_SecondStage +#@param Boolean TRUE/FALSE +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount). +#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg. +#@exception OG_ERR_NOTFOUND Entrada deltema no encontrada en burg.cfg. +#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado. +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2018-01-24 +#*/ ## +function ogBootLoaderSetAdminKeys { +# Variables locales. +local FUNC PART CFGFILE BOOTLOADER BOOTLOADERDIR CFGFILE MSG + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetSetAdminKeys ogBurgSetSetAdminKeys" + return +fi + + +# Nombre de la función que llama a esta. +FUNC="${FUNCNAME[@]:1}" +FUNC="${FUNC%%\ *}" + + +# Error si no se reciben 2 parametros. +[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_bolean" || return $? + +# Error si no puede montar sistema de archivos. +PART=$(ogMount $1 $2) || return $? +# La función debe ser llamanda desde ogGrubSetAdminKeys or ogBurgSetAdminKeys. +case "$FUNC" in + ogGrubSetAdminKeys) + BOOTLOADER="grug" + BOOTLOADERDIR="grubMBR" + CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" + ogRaiseError $OG_ERR_FORMAT "ogGrubSetAdminKeys not sopported" + return $? + ;; + ogBurgSetAdminKeys) + BOOTLOADER="burg" + BOOTLOADERDIR="burg" + CFGFILE="$PART/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetAdminKeys" + return $? + ;; +esac + + +# Comprobamos que exista fichero de configuración +[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $? + + +case "$3" in + true|TRUE) + [ -f ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled ] && mv ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey + ;; + false|FALSE) + [ -f ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey ] && mv ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey ${OGCAC}/boot/$BOOTLOADERDIR/themes/conf.d/10_hotkey.disabled + ;; + *) + ogRaiseError $OG_ERR_FORMAT "str bolean unknow " + return $? + ;; +esac +} + + + +#/** +# ogGrubSetTimeOut num_disk num_part int_timeout_seconds +#@see ogBootLoaderSetTimeOut +#*/ +function ogGrubSetTimeOut { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" \ + "$FUNCNAME 1 4 50 "\ + "$FUNCNAME \$(ogFindCache) 50" + return + fi + ogBootLoaderSetTimeOut $@ + return $? } +#/** +# ogBurgSetTimeOut num_disk num_part str_bolean +#@see ogBootLoaderSetTimeOut +#*/ +function ogBurgSetTimeOut { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage str_timeout_seconds" \ + "$FUNCNAME 1 4 50" \ + "$FUNCNAME \$(ogFindCache) 50" + return + fi + ogBootLoaderSetTimeOut $@ + return $? +} + + + +#/** +# ogBootLoaderSetTimeOut +#@brief Define el tiempo (segundos) que se muestran las opciones de inicio +#@param int_disk_SecondStage +#@param int_part_SecondStage +#@param int_timeout_seconds +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount). +#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg. +#@exception OG_ERR_NOTFOUND Entrada deltema no encontrada en burg.cfg. +#@version 1.1.0 - Primeras pruebas con Burg. GRUB solo si está instalado en MBR +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2018-01-24 +#*/ ## +function ogBootLoaderSetTimeOut { + +# Variables locales. +local FUNC PART CFGFILE TIMEOUT BOOTLOADER BOOTLOADERDIR CFGFILE MSG + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetTimeOut ogBurgSetTimeOut" + return +fi + +ogCheckStringInReg $3 "^[0-9]{1,10}$" && TIMEOUT="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a integer" + +# Nombre de la función que llama a esta. +FUNC="${FUNCNAME[@]:1}" +FUNC="${FUNC%%\ *}" + +# Error si no se reciben 3 parametros. +[ $# -eq 3 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds" || return $? + +# Error si no puede montar sistema de archivos. +PART=$(ogMount $1 $2) || return $? +# La función debe ser llamanda desde ogGrubSetTimeOut or ogBurgSetTimeOut. +case "$FUNC" in + ogGrubSetTimeOut) + BOOTLOADER="grug" + BOOTLOADERDIR="grubMBR" + CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" + ;; + ogBurgSetTimeOut) + BOOTLOADER="burg" + BOOTLOADERDIR="burg" + CFGFILE="$PART/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogGrubSetTimeOut" + return $? + ;; +esac + +# Comprobamos que exista fichero de configuración +[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $? + +# Asignamos el timeOut. +sed -i s/timeout=.*$/timeout=$TIMEOUT/g $CFGFILE +} + + +#/** +# ogGrubSetResolution num_disk num_part int_resolution +#@see ogBootLoaderSetResolution +#*/ +function ogGrubSetResolution { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \ + "$FUNCNAME 1 4 1024x768" \ + "$FUNCNAME \$(ogFindCache) 1024x768" \ + "$FUNCNAME 1 4" + return + fi + ogBootLoaderSetResolution $@ + return $? +} + +#/** +# ogBurgSetResolution num_disk num_part str_bolean +#@see ogBootLoaderSetResolution +#*/ +function ogBurgSetResolution { + # Si se solicita, mostrar ayuda. + if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" \ + "$FUNCNAME 1 4 1024x768" \ + "$FUNCNAME \$(ogFindCache) 1024x768" \ + "$FUNCNAME 1 4" + return + fi + ogBootLoaderSetResolution $@ + return $? +} + + + +#/** +# ogBootLoaderSetResolution +#@brief Define la resolucion que usuara el thema del gestor de arranque +#@param int_disk_SecondStage +#@param int_part_SecondStage +#@param str_resolution (Opcional) +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Partición errónea o desconocida (ogMount). +#@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg. +#@version 1.1.0 - Primeras pruebas con Burg. grub no soportado. +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2018-01-24 +#*/ ## +function ogBootLoaderSetResolution { + +# Variables locales. +local FUNC PART CFGFILE RESOLUTION NEWRESOLUTION DEFAULTRESOLUTION BOOTLOADER BOOTLOADERDIR CFGFILE MSG + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$MSG_SEE ogGrubSetResolution ogBurgSetResolution" + return +fi + + +# Nombre de la función que llama a esta. +FUNC="${FUNCNAME[@]:1}" +FUNC="${FUNC%%\ *}" + + +# Error si no se reciben 2 parametros. +[ $# -ge 2 ] || ogRaiseError $OG_ERR_FORMAT "$FUNCNAME int_ndiskSecondStage int_partitionSecondStage [str_resolution]" || return $? + +# Error si no puede montar sistema de archivos. +PART=$(ogMount $1 $2) || return $? +# La función debe ser llamanda desde oogGrugSetResolution or ogBurgSetResolution. +case "$FUNC" in + ogGrubSetResolution) + BOOTLOADER="grug" + BOOTLOADERDIR="grubMBR" + CFGFILE="$PART/boot/grubMBR/boot/grub/grub.cfg" + ogRaiseError $OG_ERR_FORMAT "ogGrubSetResolution not sopported" + return $? + ;; + ogBurgSetResolution) + BOOTLOADER="burg" + BOOTLOADERDIR="burg" + CFGFILE="$PART/boot/burg/burg.cfg" + ;; + *) + ogRaiseError $OG_ERR_FORMAT "Use ogBootLoaderSetResolution" + return $? + ;; +esac + +DEFAULTRESOLUTION=1024x768 + +# Comprobamos que exista fichero de configuración +[ -f $CFGFILE ] || ogRaiseError $OG_ERR_NOTFOUND "$CFGFILE" || return $? + +#controlar variable a consierar vga (default template) o video (menu) +#Si solo dos parametros autoconfiguracion basado en el parametro vga de las propiedad menu. si no hay menu asignado es 788 por defecto +if [ $# -eq 2 ] ; then + if [ -n $video ]; then + NEWRESOLUTION=$(echo "$video" | cut -f2 -d: | cut -f1 -d-) + fi + if [ -n $vga ] ; then + case "$vga" in + 788|789|814) + NEWRESOLUTION=800x600 + ;; + 791|792|824) + NEWRESOLUTION=1024x768 + ;; + 355) + NEWRESOLUTION=1152x864 + ;; + 794|795|829) + NEWRESOLUTION=1280x1024 + ;; + esac + fi +fi + +if [ $# -eq 3 ] ; then + #comprobamos que el parametro 3 cumple formato NNNNxNNNN + ogCheckStringInReg $3 "[0-9]{3,4}[x][0-9]{3,4}\$" && NEWRESOLUTION="$3" || ogRaiseError $OG_ERR_FORMAT "param 3 is not a valid resolution: 800x600, 1024x768, 1152x864, 1280x1024, 1600x1200" +fi + +# Si no existe NEWRESOLUCION asignamos la defaulT +[ -z "$NEWRESOLUTION" ] && NEWRESOLUTION=$DEFAULRESOLUTION + +#Cambiamos la entrada el fichero de configuración. +sed -i s/gfxmode=.*$/gfxmode=$NEWRESOLUTION/g $CFGFILE +} diff --git a/client/engine/Cache.lib b/client/engine/Cache.lib index e68dedbe..8f6c9663 100755 --- a/client/engine/Cache.lib +++ b/client/engine/Cache.lib @@ -4,15 +4,16 @@ #@brief Librería o clase Cache #@class Cache #@brief Funciones para gestión de la caché local de disco. -#@version 1.0.5 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ #/** # ogCreateCache [int_ndisk] int_partsize -#@brief Define la caché local en la partición 4 del disco 1 +#@brief Define la caché local, por defecto en partición 4 del disco 1. #@param int_ndisk numero de disco donde crear la cache, si no se indica es el 1 por defecto +#@param int_npart número de partición (opcional, 4 por defecto) #@param int_partsize tamaño de la partición (en KB) #@return (nada, por determinar) #@exception OG_ERR_FORMAT formato incorrecto. @@ -31,17 +32,23 @@ #@version 1.0.5 - Posibilidad de crear la cache en cualquier disco duro #@author Universidad de Huelva #@date 2012/09/18 +#@version 1.1.0 - Posibilidad de crear la caché en cualquier partición. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016/05/25 +#@version 1.1.0 - Soporte discos con sectores de 4k +#@date 2017/01/09 #@version 1.0.6b - Al crear las particiones ordenamos los dispositivos en el fichero auxiliar. #@author Irina Gomez, ETSII Universidad de Sevilla -#@date 2016/12/19 +#@date 2017/01/09 #*/ ## function ogCreateCache () { # Variables locales. -local FINDCACHE NDSK SIZECACHE IOSIZE PART DISK START END ENDPREVPART SIZE MINSIZE MAXSIZE PTTYPE ID +local FINDCACHE IOSIZE NDSK SIZECACHE PART DISK START END ENDPREVPART SIZE MINSIZE MAXSIZE PTTYPE ID TMPFILE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_partsize" "$FUNCNAME 1 10000000" + ogHelp "$FUNCNAME" "$FUNCNAME [int_ndisk [int_npart]] int_partsize" \ + "$FUNCNAME 10000000" "$FUNCNAME 1 10000000" "$FUNCNAME 1 4 10000000" return fi # Si se recibe un parametro, sera el tamano de la cache @@ -49,34 +56,41 @@ case $# in 1) # Error, si no es un entero positivo [[ $1 =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$1" || return $? NDSK=1 + PART=4 SIZECACHE=$1 ;; 2) # Error, si no son enteros positivos [[ $1 =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$1" || return $? [[ $2 =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$2" || return $? NDSK=$1 + PART=4 SIZECACHE=$2 ;; + 3) # Error, si no son enteros positivos + [[ $1 =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$1" || return $? + [[ $2 =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$2" || return $? + [[ $3 =~ ^[1-9][0-9]*$ ]] || ogRaiseError $OG_ERR_FORMAT "$3" || return $? + NDSK=$1 + PART=$2 + SIZECACHE=$3 + ;; *) ogRaiseError $OG_ERR_FORMAT return $? ;; esac -# De momento la cache sigue siendo siempre la cuarta particion -PART=4 - +TMPFILE=/tmp/sfdisk$$ DISK=$(ogDiskToDev $NDSK) || return $? END=$[$(ogGetLastSector $NDSK 2>/dev/null)] # Sector final del disco. SIZE=$[$SIZECACHE*2] # Tamaño en sectores de 512 B. -###### agp ############ -IOSIZE=$(fdisk -l $DISK | grep I/O | cut -d ":" -f2 | cut -d "/" -f1 | cut -d " " -f2) -if [[ $IOSIZE = 4096 ]]; then - END=$[$END-8192] - START=$[END-SIZE-8192] +# Inicio partición cache según el disco tenga sectores de 4k o menores +IOSIZE=$(fdisk -l $DISK | awk '/I\/O/ {print $4}') +if [ $IOSIZE -eq 4096 ]; then + END=$[$END-8192] + START=$[END-SIZE-8192] else - START=$[END-SIZE+1] + START=$[END-SIZE+1] fi -###### agp ############ ENDPREVPART=$[$(ogGetLastSector $NDSK $[PART-1] 2>/dev/null)] # Error si tamaño no está entre límites permitidos o si se solapa con la partición anterior. MINSIZE=25000 # Error de formateo si tamaño < 50 MB. @@ -98,7 +112,7 @@ fi case "$(ogGetPartitionTableType $NDSK)" in GPT) # Si la tabla de particiones no es valida, volver a generarla. - [ ! $(sgdisk -p $DISK 2>&1 >/dev/null) ] || echo -e "2\nw\nY\n" | gdisk $DISK + [ ! $(sgdisk -p $DISK &>/dev/null) ] || echo -e "2\nw\nY\n" | gdisk $DISK # Si existe la cache se borra previamente [ -n "$(ogFindCache)" ] && ogDeleteCache # Capturamos el codigo de particion GPT para cache @@ -107,23 +121,24 @@ case "$(ogGetPartitionTableType $NDSK)" in ;; MSDOS) # Si la tabla de particiones no es valida, volver a generarla. - [ $(parted -s $DISK print >/dev/null) ] || fdisk $DISK <<< "w" + parted -s $DISK print &>/dev/null || fdisk $DISK <<< "w" # Definir particiones y notificar al kernel. ID=$(ogTypeToId CACHE MSDOS) - local TMPFILE=/tmp/sfdisk$$ + # Salvamos la configuración de las particiones e incluimos la cache. trap "rm -f $TMPFILE" 1 2 3 9 15 sfdisk --dump $DISK | grep -v $DISK$PART > $TMPFILE echo "$DISK$PART : start= $START, size= $SIZE, Id=$ID" >> $TMPFILE - # Ordenamos las lineas de los dispositivos - UNIT=$(grep unit $TMPFILE) - grep ^/dev $TMPFILE|sort -o $TMPFILE - sed -i "1i $UNIT\n" $TMPFILE + # Ordenamos las líneas de los dispositivos + UNIT=$(grep unit $TMPFILE) + grep ^/dev $TMPFILE|sort -o $TMPFILE + sed -i "1i $UNIT\n" $TMPFILE + # Guardamos nueva configuración en el disco. sfdisk --no-reread $DISK < $TMPFILE rm -f $TMPFILE ;; esac -#Actualiza la tabla de particiones en el kernel. -ogUpdatePartitionTable $NDISK +# Actualiza la tabla de particiones en el kernel. +ogUpdatePartitionTable } @@ -132,16 +147,19 @@ ogUpdatePartitionTable $NDISK #@brief Elimina la partición de caché local. #@return (nada, por determinar) #@exception OG_ERR_FORMAT formato incorrecto. -#@note Requisitos: sfdisk, parted, awk, sed +#@note Requisitos: fdisk, sgdisk, partprobe #@version 0.91 - Definición de caché local. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2010/03/11 #@version 1.0.4 - Soporte para discos GPT. #@author Universidad de Huelva #@date 2012/03/13 -#@version 1.0.6b - llamada correcta a ogGetPartitionTableType y ogUpdatePartitionTable +#@version 1.0.6b - llamada correcta a ogUpdatePartitionTable #@author Antonio Doblas Universidad de Málaga #@date 2016/11/16 +#@version 1.1.0 - Sustituir "sfdisk" por "fdisk" para discos MSDOS. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016/05/25 #*/ ## function ogDeleteCache () { @@ -163,13 +181,13 @@ case "$(ogGetPartitionTableType $NDISK)" in GPT) # Si la tabla de particiones no es valida, volver a generarla. [ ! $(sgdisk -p $DISK 2>&1 >/dev/null) ] || echo -e "2\nw\nY\n" | gdisk $DISK - sgdisk $DISK -d$NPART 2>/dev/null + sgdisk $DISK -d$NPART 2>/dev/null ;; MSDOS) # Si la tabla de particiones no es valida, volver a generarla. - [ $(parted -s $DISK print >/dev/null) ] || fdisk $DISK <<< "w" - # Eliminar (poner a 0) la partición de caché. - sfdisk -f $DISK -N$NPART <<<"0,0,0" 2>/dev/null + parted -s $DISK print &>/dev/null || fdisk $DISK <<< "w" + # Eliminar la partición de caché. + echo -e "d\n$NPART\nw" | fdisk $DISK 2>/dev/null ;; esac # Borrar etiqueta de la caché. @@ -238,6 +256,10 @@ ogDevToDisk ${PART%% *} 2>/dev/null #@version 0.91 - Creacion cache local. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2010-03-11 +#@version 1.1.0 - llamada a updateBootCache. +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2018-01-21 + #*/ ## function ogFormatCache () { @@ -260,6 +282,9 @@ mkfs.ext4 -q -F $DEV -L "CACHE" -O extent,large_file 2>/dev/null || ogRaiseError # Crear estructura básica. MNTDIR=$(ogMountCache) mkdir -p $MNTDIR/$OGIMG + +# Incluir kernel e Initrd del ogLive +updateBootCache 2>&1>/dev/null } diff --git a/client/engine/Disk.lib b/client/engine/Disk.lib index 1bba0a28..38765bcf 100755 --- a/client/engine/Disk.lib +++ b/client/engine/Disk.lib @@ -4,7 +4,7 @@ #@brief Librería o clase Disk #@class Disk #@brief Funciones para gestión de discos y particiones. -#@version 1.0.6 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ @@ -40,11 +40,14 @@ timeout -k 5s -s KILL 3s $(which parted) "$@" #@version 1.0.4 - Llamada a función específica para tablas GPT. #@author Universidad de Huelva #@date 2012/03/30 +#@version 1.1.1 - El inicio de la primera partición logica es el de la extendida más 4x512 +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2016/07/11 #*/ ## function ogCreatePartitions () { # Variables locales. -local ND DISK PTTYPE PART SECTORS START SIZE TYPE CACHEPART CACHESIZE IOSIZE EXTSTART EXTSIZE tmpsfdisk +local ND DISK PTTYPE PART SECTORS START SIZE TYPE CACHEPART IODISCO IOSIZE CACHESIZE EXTSTART EXTSIZE tmpsfdisk # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_parttype:int_partsize ..." \ @@ -71,21 +74,15 @@ SECTORS=$(ogGetLastSector $1) CACHEPART=$(ogFindCache 2>/dev/null) [ "$ND" = "${CACHEPART% *}" ] && CACHESIZE=$(ogGetCacheSize 2>/dev/null | awk '{print $0*2}') [ -n "$CACHESIZE" ] && SECTORS=$[SECTORS-CACHESIZE] + # Sector de inicio (la partición 1 empieza en el sector 63). -########## agp ########### -iodisco=$(ogDiskToDev $1) -IOSIZE=$(fdisk -l $iodisco | grep I/O | cut -d ":" -f2 | cut -d "/" -f1 | cut -d " " -f2) -if [[ $IOSIZE = 4096 ]]; then - START=4096 +IODISCO=$(ogDiskToDev $1) +IOSIZE=$(fdisk -l $IODISCO | awk '/I\/O/ {print $4}') +if [ "$IOSIZE" == "4096" ]; then + START=4096 else - START=63 + START=63 fi -########## agp ########### - - - - - PART=1 # Fichero temporal de entrada para "sfdisk" @@ -115,6 +112,7 @@ while [ $# -gt 0 ]; do # Comprobar si la partición es extendida. if [ $ID = 5 ]; then [ $PART -le 4 ] || ogRaiseError $OG_ERR_FORMAT || return $? + # El inicio de la primera partición logica es el de la extendida más 4x512 let EXTSTART=$START+2048 let EXTSIZE=$SIZE-2048 fi @@ -267,8 +265,8 @@ sgdisk $DELOPTIONS $OPTIONS $DISK 2>/dev/null && partprobe $DISK #@return (por determinar) #@exception OG_ERR_FORMAT Formato incorrecto. #@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo. -#@note tabletype: { MSDOS, GPT } -#@note Requisitos: sfdisk, sgdisk +#@note tabletype: { MSDOS, GPT }, MSDOS por defecto +#@note Requisitos: fdisk, gdisk, parted #@version 1.0.4 - Primera versión compatible con OpenGnSys. #@author Universidad de Huelva #@date 2012/03/06 @@ -326,7 +324,7 @@ case "$CREATE" in if [ "$PTTYPE" == "GPT" ]; then sgdisk -Z $DISK fi - # Crear y borrar una partición para que la tabla se genere bien. + # Crear y borrar una partición para que la tabla se genere bien. echo -e "o\nn\np\n\n\n\nd\n\nw" | fdisk $DISK partprobe $DISK 2>/dev/null ;; @@ -393,7 +391,7 @@ esac function ogDevToDisk () { # Variables locales. -local DEV d n +local CACHEFILE DEV PART d n # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then ogHelp "$FUNCNAME" "$FUNCNAME path_device | LABEL=str_label | UUID=str_uuid" \ @@ -413,10 +411,17 @@ case "$DEV" in UUID=*) DEV=$(blkid -U "${1#*=}") ;; esac -# Error si no es fichero de bloques. -[ -b "$DEV" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $? +# Error si no es fichero de bloques o directorio (para LVM). +[ -b "$DEV" -o -d "$DEV" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $? -# Procesa todos los discos para devolver su nº de orden y de partición. +# Buscar en fichero de caché de discos. +CACHEFILE=/var/cache/disks.cfg +PART=$(awk -F: -v d="$DEV" '{if ($2==d) {print $1}}' $CACHEFILE 2>/dev/null) +if [ -n "$PART" ]; then + echo "$PART" + return +fi +# Si no se encuentra, procesa todos los discos para devolver su nº de orden y de partición. n=1 for d in $(ogDiskToDev); do [ -n "$(echo $DEV | grep $d)" ] && echo "$n ${DEV#$d}" && return @@ -449,14 +454,17 @@ return $OG_ERR_NOTFOUND #@version 1.0.5 - Comprobación correcta de parámetros para soportar valores > 9. #@author Ramon Gomez, ETSII Universidad Sevilla #@date 2013-05-07 -#@version 1.0.6 - Soporta RAID hardware y Multipath. +#@version 1.0.6 - Soportar RAID hardware y Multipath. #@author Ramon Gomez, ETSII Universidad Sevilla #@date 2014-09-23 +#@version 1.1.0 - Usar caché de datos y soportar pool de volúmenes ZFS. +#@author Ramon Gomez, ETSII Universidad Sevilla +#@date 2016-05-27 #*/ ## function ogDiskToDev () { # Variables locales -local ALLDISKS MPATH VOLGROUPS DISK PART i +local CACHEFILE ALLDISKS MPATH VOLGROUPS ZFSVOLS DISK PART ZPOOL i # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -467,9 +475,25 @@ if [ "$*" == "help" ]; then return fi -# Listar dispositivos de discos duros. -ALLDISKS=$(lsblk -n -e 1,2 | awk '$6~/^disk$/ {gsub(/!/,"/"); printf "/dev/%s ",$1}') +# Borrar fichero de caché de configuración si hay cambios en las particiones. +CACHEFILE=/var/cache/disks.cfg +if ! diff -q <(cat /proc/partitions) /tmp/.partitions &>/dev/null; then + # Guardar copia de las particiones definidas para comprobar cambios. + cp -a /proc/partitions /tmp/.partitions + rm -f $CACHEFILE +fi + +# Si existe una correspondencia con disco/dispositivo en el caché; mostrarlo y salir. +PART=$(awk -F: -v d="$*" '{if ($1==d) {print $2}}' $CACHEFILE 2>/dev/null) +if [ -n "$PART" ]; then + echo "$PART" + return +fi +# Continuar para detectar nuevos dispositivos. +# Listar dispositivos de discos. +ALLDISKS=$((lsblk -n -e 1,2 -x MAJ:MIN 2>/dev/null || lsblk -n -e 1,2) | \ + awk '$6~/^disk$/ {gsub(/!/,"/"); printf "/dev/%s ",$1}') # Listar volúmenes lógicos. VOLGROUPS=$(vgs -a --noheadings 2>/dev/null | awk '{printf "/dev/%s ",$1}') ALLDISKS="$ALLDISKS $VOLGROUPS" @@ -484,6 +508,10 @@ if MPATH=$(multipath -l -v 1 2>/dev/null | awk '{printf "/dev/mapper/%s ",$1}'; ALLDISKS="$ALLDISKS $MPATH" fi +# Detectar volúmenes ZFS. +ZFSVOLS=$(blkid | awk -F: '/zfs/ {print $1}') +ALLDISKS="$ALLDISKS $ZFSVOLS" + # Mostrar salidas segun el número de parametros. case $# in 0) # Muestra todos los discos, separados por espacios. @@ -494,6 +522,8 @@ case $# in DISK=$(echo "$ALLDISKS" | awk -v n=$1 '{print $n}') # Error si el fichero no existe. [ -e "$DISK" ] || ogRaiseError $OG_ERR_NOTFOUND "$1" || return $? + # Actualizar caché de configuración y mostrar dispositivo. + echo "$*:$DISK" >> $CACHEFILE echo "$DISK" ;; 2) # Error si los 2 parámetros no son números positivos. @@ -503,21 +533,38 @@ case $# in PART="$DISK$2" # Comprobar si es partición. if [ -b "$PART" ]; then + # Actualizar caché de configuración y mostrar dispositivo. + echo "$*:$PART" >> $CACHEFILE echo "$PART" else # Comprobar si RAID o Multipath (tener en cuenta enlace simbólico). PART="${DISK}p$2" if [ "$(stat -L -c "%A" "$PART" 2>/dev/null | cut -c1)" == "b" ]; then - echo "$PART" - elif [ -n "$VOLGROUPS" ]; then - # Comprobar si volumen lógico. /* (comentario Doxygen) - PART=$(lvscan -a 2>/dev/null | \ - awk -F\' -v n=$2 "\$2~/^${DISK//\//\\/}\// {if (NR==n) print \$2}") - [ -e "$PART" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $? - # (comentario Doxygen) */ + # Actualizar caché de configuración y mostrar dispositivo. + echo "$*:$PART" >> $CACHEFILE echo "$PART" else - ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $? + PART="" + # Comprobar si volumen lógico. /* (comentario Doxygen) + if ogCheckStringInGroup "$DISK" "$VOLGROUPS"; then + PART=$(lvscan -a 2>/dev/null | \ + awk -F\' -v n=$2 "\$2~/^${DISK//\//\\/}\// {if (NR==n) print \$2}") + [ -e "$PART" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $? + # (comentario Doxygen) */ + fi + # Comprobar si volumen ZFS que puede ser montado. + if ogCheckStringInGroup "$DISK" "$ZFSVOLS"; then + zpool import -f -R /mnt -N -a 2>/dev/null + ZPOOL=$(blkid -s LABEL -o value $DISK) + PART=$(zfs list -Hp -o name,canmount,mountpoint -r $ZPOOL | \ + awk -v n=$2 '$2=="on" && $3!="none" {c++; if (c==n) print $1}') + fi + # Salir si no se encuentra dispositivo. + [ -n "$PART" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $? + # Devolver camino al dispositivo. + # Actualizar caché de configuración y mostrar dispositivo. + echo "$*:$PART" >> $CACHEFILE + echo "$PART" fi fi ;; @@ -610,7 +657,6 @@ echo $TYPE #@author Universidad de Málaga #@date 2016/11/10 #*/ ## - function ogGetLastSector () { # Variables locales @@ -622,23 +668,22 @@ if [ "$*" == "help" ]; then "$FUNCNAME 1 1 => 102400062" return fi -# Error si no se reciben 1 o 2 parámetros. + +# Obtener último sector. case $# in - 1) DISK=$(ogDiskToDev $1) || return $? + 1) # Para un disco. + DISK=$(ogDiskToDev $1) || return $? + LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk '/last usable sector/ {print($(NF))}') ;; - 2) DISK=$(ogDiskToDev $1) || return $? + 2) # Para una partición. + DISK=$(ogDiskToDev $1) || return $? PART=$(ogDiskToDev $1 $2) || return $? + LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk -v P="$2" '{if ($1==P) print $3}') ;; - *) ogRaiseError $OG_ERR_FORMAT + *) # Error si se reciben más parámetros. + ogRaiseError $OG_ERR_FORMAT return $? ;; esac - -if [ $# == 1 ]; then - LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk '/last usable sector/ {print($(NF))}') -else - LASTSECTOR=$(LANG=C sgdisk -p $DISK | awk -v P="$2" '{if ($1==P) print $3}') -fi - echo $LASTSECTOR } @@ -671,7 +716,7 @@ fi # Comprobar que el disco existe y listar su partición activa. DISK="$(ogDiskToDev $1)" || return $? -parted $DISK print 2>/dev/null | awk '/boot/ {print $1}' +LANG=C parted -sm $DISK print 2>/dev/null | awk -F: '$7~/boot/ {print $1}' } @@ -686,15 +731,21 @@ parted $DISK print 2>/dev/null | awk '/boot/ {print $1}' #@note Requisitos: sfdisk #@version 0.9 - Primera versión compatible con OpenGnSys. #@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2009/03/25 +#@date 2009-03-25 #@version 1.0.2 - Detectar partición vacía. #@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2011/12/23 +#@date 2011-12-23 +#@version 1.0.6 - Soportar LVM. +#@author Universidad de Huelva +#@date 2014-09-04 +#@version 1.1.0 - Soportar pool de volúmenes ZFS. +#@author Ramon Gomez, ETSII Universidad Sevilla +#@date 2014-11-14 #*/ ## function ogGetPartitionId () { # Variables locales. -local DISK PART ID +local DISK ID # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -705,14 +756,15 @@ fi # Error si no se reciben 2 parámetros. [ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? -# Detectar id. de tipo de partición y codificar al mnemónico. +# Detectar y mostrar el id. de tipo de partición. DISK=$(ogDiskToDev $1) || return $? -PART=$(ogDiskToDev $1 $2) || return $? case "$(ogGetPartitionTableType $1)" in GPT) ID=$(sgdisk -p $DISK 2>/dev/null | awk -v p="$2" '{if ($1==p) print $6;}') || ogRaiseError $OG_ERR_NOTFOUND "$1,$2" || return $? [ "$ID" == "8300" -a "$1 $2" == "$(ogFindCache)" ] && ID=CA00 ;; MSDOS) ID=$(sfdisk --id $DISK $2 2>/dev/null) || ogRaiseError $OG_ERR_NOTFOUND "$1,$2" || return $? ;; + LVM) ID=10000 ;; + ZPOOL) ID=10010 ;; esac echo $ID } @@ -733,11 +785,14 @@ echo $ID #@version 0.9 - Primera version para OpenGnSys #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2009/07/24 +#@version 1.1.0 - Sustituir "sfdisk" por "partx". +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016/05/04 #*/ ## function ogGetPartitionSize () { # Variables locales. -local PART +local PART SIZE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -748,11 +803,12 @@ fi # Error si no se reciben 2 parámetros. [ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? -# Obtener el tamaño de la partición. +# Devolver tamaño de partición, del volumen lógico o del sistema de archivos (para ZFS). PART="$(ogDiskToDev $1 $2)" || return $? -partx -gbo SIZE $PART 2>/dev/null | awk '{print int($1/1024)}' -[ ${PIPESTATUS[0]} -ne 0 ] && echo "0" -return 0 +SIZE=$(partx -gbo SIZE $PART 2>/dev/null | awk '{print int($1/1024)}') +[ -z "$SIZE" ] && SIZE=$(lvs --noheadings -o lv_size --units k $PART | awk '{printf "%d",$0}') +[ -z "$SIZE" ] && SIZE=$(ogGetFsSize $1 $2) +echo ${SIZE:-0} } @@ -769,13 +825,16 @@ return 0 #@date Date: 27/10/2008 #@version 1.0 - Uso de sfdisk Primera version para OpenGnSys #@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2009/07/24 +#@date 2009-07-24 #@version 1.0.4 - Uso de /proc/partitions para detectar el numero de particiones #@author Universidad de Huelva -#@date 2012/03/28 +#@date 2012-03-28 #@version 1.0.6 - Soportar LVM. #@author Universidad de Huelva -#@date 2014/09/04 +#@date 2014-09-04 +#@version 1.1.0 - Soportar ZFS y sustituir "sfdisk" por "partx". +#@author Ramon Gomez, ETSII Universidad Sevilla +#@date 2016-04-28 #*/ ## function ogGetPartitionsNumber () { @@ -796,6 +855,12 @@ case "$(ogGetPartitionTableType $1)" in GPT|MSDOS) partx -gso NR $DISK 2>/dev/null | awk -v p=0 '{p=$1} END {print p}' ;; LVM) lvs --noheadings $DISK 2>/dev/null | wc -l ;; + ZPOOL) zpool list &>/dev/null || modprobe zfs + zpool import -f -R /mnt -N -a 2>/dev/null + zfs list -Hp -o name,canmount,mountpoint -r $(blkid -s LABEL -o value $DISK) | \ + awk '$2=="on" && $3!="none" {c++} + END {print c}' + ;; esac } @@ -807,13 +872,16 @@ esac #@return str_tabletype - Tipo de tabla de paritiones #@warning Salidas de errores no determinada #@note tabletype = { MSDOS, GPT } -#@note Requisitos: parted +#@note Requisitos: blkid, parted, vgs #@version 1.0.4 - Primera versión para OpenGnSys #@author Universidad de Huelva #@date 2012/03/01 #@version 1.0.6 - Soportar LVM. #@author Universidad de Huelva -#@date 2014/09/04 +#@date 2014-09-04 +#@version 1.1.0 - Mejorar rendimiento y soportar ZFS. +#@author Ramon Gomez, ETSII Universidad Sevilla +#@date 2014-11-14 #*/ ## function ogGetPartitionTableType () { @@ -833,8 +901,14 @@ fi DISK=$(ogDiskToDev $1) || return $? # Comprobar tabla de particiones. -[ -b $DISK ] && TYPE=$(parted -sm $DISK print | awk -F: -v D=$DISK '{ if($1 == D) print toupper($6)}') +if [ -b $DISK ]; then + TYPE=$(parted -sm $DISK print 2>/dev/null | awk -F: -v D=$DISK '{ if($1 == D) print toupper($6)}') + [ -z "$TYPE" ] && TYPE=$(parted -sm $DISK print 2>/dev/null | awk -F: -v D=$DISK '{ if($1 == D) print toupper($6)}') +fi +# Comprobar si es volumen lógico. [ -d $DISK ] && vgs $DISK &>/dev/null && TYPE="LVM" +# Comprobar si es pool de ZFS. +[ -z "$TYPE" -o "$TYPE" == "UNKNOWN" ] && [ -n "$(blkid -s TYPE $DISK | grep zfs)" ] && TYPE="ZPOOL" # Mostrar salida. [ -n "$TYPE" ] && echo "$TYPE" @@ -995,12 +1069,44 @@ case "${ID,,}" in bf03) TYPE="SOLARIS-DISK" ;; ef01) TYPE="MBR" ;; ef02) TYPE="BIOS-BOOT" ;; + 10000) TYPE="LVM-LV" ;; + 10010) TYPE="ZFS-VOL" ;; *) TYPE="UNKNOWN" ;; esac echo "$TYPE" } +# ogIsDiskLocked int_ndisk +#@brief Comprueba si un disco está bloqueado por una operación de uso exclusivo. +#@param int_ndisk nº de orden del disco +#@return Código de salida: 0 - bloqueado, 1 - sin bloquear o error. +#@note Los ficheros de bloqueo se localizan en \c /var/lock/dev, siendo \c dev el dispositivo de la partición o de su disco, sustituyendo el carácter "/" por "-". +#@version 1.1.0 - Primera versión para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-04-08 +#*/ ## +function ogIsDiskLocked () +{ +# Variables locales +local DISK LOCKFILE + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \ + "if $FUNCNAME 1; then ... ; fi" + return +fi +# Falso, en caso de error. +[ $# == 1 ] || return 1 +DISK="$(ogDiskToDev $1 2>/dev/null)" || return 1 + +# Comprobar existencia de fichero de bloqueo para el disco. +LOCKFILE="/var/lock/lock${DISK//\//-}" +test -f $LOCKFILE +} + + #/** # ogListPartitions int_ndisk #@brief Lista las particiones definidas en un disco. @@ -1052,6 +1158,13 @@ function ogListPrimaryPartitions () # Variables locales. local PTTYPE PARTS +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \ + "$FUNCNAME 1 => NTFS:10000000 EXT3:5000000 EXTENDED:1000000" + return +fi + PTTYPE=$(ogGetPartitionTableType $1) || return $? PARTS=$(ogListPartitions "$@") || return $? case "$PTTYPE" in @@ -1072,6 +1185,12 @@ function ogListLogicalPartitions () # Variables locales. local PTTYPE PARTS +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \ + "$FUNCNAME 1 => LINUX-SWAP:999998" + return +fi PTTYPE=$(ogGetPartitionTableType $1) || return $? [ "$PTTYPE" == "MSDOS" ] || ogRaiseError $OG_ERR_PARTITION "" || return $? PARTS=$(ogListPartitions "$@") || return $? @@ -1079,6 +1198,41 @@ echo $PARTS | cut -sf5- -d" " } +#/** +# ogLockDisk int_ndisk +#@brief Genera un fichero de bloqueo para un disco en uso exlusivo. +#@param int_ndisk nº de orden del disco +#@return (nada) +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo. +#@note El fichero de bloqueo se localiza en \c /var/lock/disk, siendo \c disk el dispositivo del disco, sustituyendo el carácter "/" por "-". +#@version 1.1.0 - Primera versión para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-04-07 +#*/ ## +function ogLockDisk () +{ +# Variables locales +local DISK LOCKFILE + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \ + "$FUNCNAME 1" + return +fi +# Error si no se recibe 1 parámetro. +[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $? + +# Obtener partición. +DISK="$(ogDiskToDev $1)" || return $? + +# Crear archivo de bloqueo exclusivo. +LOCKFILE="/var/lock/lock${DISK//\//-}" +touch $LOCKFILE +} + + #/** # ogSetPartitionActive int_ndisk int_npartition #@brief Establece cual es la partición activa de un disco. @@ -1163,7 +1317,7 @@ ID="${3^^}" PTTYPE=$(ogGetPartitionTableType $1) case "$PTTYPE" in GPT) sgdisk -t$2:$ID $DISK 2>/dev/null ;; - MSDOS) echo -ne "t\n$2\n${ID}\nw\n" | fdisk $DISK | grep Syncing &>/dev/null ;; + MSDOS) sfdisk --id $DISK $2 $ID 2>/dev/null ;; *) ogRaiseError $OG_ERR_OUTOFLIMIT "$1,$PTTYPE" return $? ;; esac @@ -1284,7 +1438,7 @@ ogSetPartitionId $1 $2 $ID function ogTypeToId () { # Variables locales -local PTTYPE ID +local PTTYPE ID="" # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -1328,7 +1482,6 @@ case "$PTTYPE" in CACHE) ID=CA00;; EFI) ID=EF00 ;; LINUX-RAID) ID=FD00 ;; - *) ID="" ;; esac ;; MSDOS) @@ -1359,7 +1512,16 @@ case "$PTTYPE" in EFI) ID=ef ;; VMFS) ID=fb ;; LINUX-RAID) ID=fd ;; - *) ID="" ;; + esac + ;; + LVM) + case "$1" in + LVM-LV) ID=10000 ;; + esac + ;; + ZVOL) + case "$1" in + ZFS-VOL) ID=10010 ;; esac ;; esac @@ -1409,6 +1571,41 @@ ogSetPartitionType $1 $2 $NEWTYPE } +#/** +# ogUnlockDisk int_ndisk +#@brief Elimina el fichero de bloqueo para un disco. +#@param int_ndisk nº de orden del disco +#@return (nada) +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_NOTFOUND Disco o particion no corresponden con un dispositivo. +#@note El fichero de bloqueo se localiza en \c /var/lock/disk, siendo \c disk el dispositivo del disco, sustituyendo el carácter "/" por "-". +#@version 1.1.0 - Primera versión para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-04-08 +#*/ ## +function ogUnlockDisk () +{ +# Variables locales +local DISK LOCKFILE + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk" \ + "$FUNCNAME 1" + return +fi +# Error si no se recibe 1 parámetro. +[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $? + +# Obtener partición. +DISK="$(ogDiskToDev $1)" || return $? + +# Borrar archivo de bloqueo exclusivo. +LOCKFILE="/var/lock/lock${DISK//\//-}" +rm -f $LOCKFILE +} + + #/** # ogUpdatePartitionTable #@brief Fuerza al kernel releer la tabla de particiones de los discos duros @@ -1428,53 +1625,3 @@ do partprobe $i done } - - -#/** @function ogDiskToRelativeDev: @brief Traduce los ID de discos o particiones EAC a ID Linux relativos, es decir 1 1 => sda1 -#@param Admite 1 parametro: $1 int_numdisk -#@param Admite 2 parametro: $1 int_numdisk $2 int_partition -#@return Para 1 parametros traduce Discos Duros: Devuelve la ruta relativa linux del disco duro indicado con nomenclatura EAC.........ejemplo: IdPartition 1 => sda -#@return Para 2 parametros traduce Particiones: Devuelve la ruta relativa linux de la particion indicado con nomenclatura EAC........... ejemplo: IdPartition 2 1 => sdb1 -#@warning No definidas -#@attention -#@note Notas sin especificar -#@version 0.1 - Integracion para Opengnsys - EAC: IdPartition en ATA.lib -#@author Antonio J. Doblas Viso. Universidad de Malaga -#@date 27/10/2008 -#*/ -function ogDiskToRelativeDev () { -if [ $# = 0 ] -then - Msg "Info: Traduce el identificador del dispositivo EAC a dispositivo linux \n" info - Msg "Sintaxis1: IdPartition int_disk -----------------Ejemplo1: IdPartition 1 -> sda " example - Msg "Sintaxis2: IdPartition int_disk int_partition --Ejemplo2: IdPartition 1 2 -> sda2 " example - -return -fi -#PART="$(Disk|cut -f$1 -d' ')$2" # se comenta esta linea porque doxygen no reconoce la funcion disk y no crea los enlaces y referencias correctas. -PART=$(ogDiskToDev|cut -f$1 -d' ')$2 -echo $PART | cut -f3 -d \/ -} - - -#/** @function ogDeletePartitionsLabels: @brief Elimina la informacion que tiene el kernel del cliente og sobre los labels de los sistemas de archivos -#@param No requiere -#@return Nada -#@warning -#@attention Requisitos: comando interno linux rm -#@note -#@version 0.1 - Integracion para Opengnsys - EAC: DeletePartitionTable() en ATA.lib -#@author Antonio J. Doblas Viso. Universidad de Malaga -#@date 27/10/2008 -#*/ -function ogDeletePartitionsLabels () { -# Si se solicita, mostrar ayuda. -if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME " \ - "$FUNCNAME " - return -fi - -rm /dev/disk/by-label/* # */ COMENTARIO OBLIGATORIO PARA DOXYGEN -} - diff --git a/client/engine/File.lib b/client/engine/File.lib index 88e0af7e..f37e947d 100755 --- a/client/engine/File.lib +++ b/client/engine/File.lib @@ -265,25 +265,24 @@ case $# in return $? ;; esac -# Volver a directorio inicial en caso de error. -CURRENTDIR="$PWD" -trap "cd $CURRENTDIR" RETURN - -# Eliminar caracteres \c / iniciales, finales y duplicados. +# Eliminar caracteres \c / duplicados y finales. # /* (comentario Doxygen) -FILE="$(echo $FILE|sed -e 's/\(\/\)*\1/\//g' -e 's/^\///' -e 's/\/$//')" -PREVFILE="" -FILEPATH="/" -while [ "$FILE" != "$PREVFILE" ]; do - # Busca el nombre correcto en el directorio actual. - cd "$FILEPATH" 2>/dev/null || FILE="" - FILEPATH="${FILEPATH}/$(ls -A 2>/dev/null | grep -i -m1 "^${FILE%%/*}$")" || return $? - PREVFILE="$FILE" - FILE="${FILE#*/}" -done +FILE="$(echo $FILE|sed -e 's/\(\/\)*\1/\//g; s/\/$//')" +# Comprobar si existe el fichero para reducir tiempos. +if [ -e "$FILE" ]; then + FILEPATH="$FILE" +else + # Buscar el nombre correcto en cada subdirectorio del camino. + FILEPATH="/" + while [ "$FILE" != "$PREVFILE" ]; do + FILEPATH="$(ls -d "${FILEPATH%/}/${FILE%%/*}" 2>/dev/null || find "$FILEPATH" -maxdepth 1 -iname "${FILE%%/*}" -print 2>/dev/null)" + PREVFILE="$FILE" + FILE="${FILE#*/}" + done +fi # (comentario Doxygen) */ -# Muestra el camino Linux, quitando el / inicial duplicado. -[ "$FILEPATH" != "/" ] && echo ${FILEPATH#/} +[ -n "$FILEPATH" ] && echo "$FILEPATH" +return 0 } diff --git a/client/engine/FileSystem.lib b/client/engine/FileSystem.lib index 2a29b213..8dd1a87a 100755 --- a/client/engine/FileSystem.lib +++ b/client/engine/FileSystem.lib @@ -4,7 +4,7 @@ #@brief Librería o clase FileSystem #@class FileSystem #@brief Funciones para gestión de sistemas de archivos. -#@version 1.0.6 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ @@ -33,6 +33,9 @@ #@version 1.0.5 - Desmontar antes de comprobar, soportar Btrfs y ExFAT. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2012-09-05 +#@version 1.1.0 - Soportar F2FS. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-05-03 #*/ ## function ogCheckFs () { @@ -57,7 +60,8 @@ case "$TYPE" in REISERFS) PROG="fsck.reiserfs"; PARAMS="<<<\"Yes\""; CODES=(1 2) ;; REISER4) PROG="fsck.reiser4"; PARAMS="-ay" ;; JFS) PROG="fsck.jfs"; CODES=(1 2) ;; - XFS) PROG="fsck.xfs" ;; + XFS) PROG="xfs_repair" ;; + F2FS) PROG="fsck.f2fs" ;; NTFS) PROG="ntfsfix" ;; EXFAT) PROG="fsck.exfat" ;; FAT32) PROG="dosfsck"; PARAMS="-a"; CODES=1 ;; @@ -66,6 +70,7 @@ case "$TYPE" in HFS) PROG="fsck.hfs"; PARAMS="-f" ;; HFSPLUS) PROG="fsck.hfs"; PARAMS="-f" ;; UFS) PROG="fsck.ufs" ;; + ZFS) PROG="fsck.zfs" ;; *) ogRaiseError $OG_ERR_PARTITION "$1, $2, $TYPE" return $? ;; esac @@ -143,7 +148,9 @@ case "$TYPE" in ;; REISERFS|REISER4) PROG="resize_reiserfs"; PARAMS="-f" ;; + F2FS) ;; # No se reduce (por el momento). JFS) ;; # No se reduce (por el momento). + NILFS2) ;; # No se reduce (probar "nilfs-resize"). XFS) ;; # No se reduce (por el momento). NTFS) PROG="ntfsresize"; PARAMS="<<<\"y\" -f" ;; EXFAT) ;; # No se reduce (por el momento). @@ -223,11 +230,14 @@ esac #@version 1.0.5 - Comprobar errores al inicio e independizar del tipo de tabla de particiones. #@author Universidad de Huelva #@date 2013-05-16 +#@version 1.1.0 - Soportar F2FS y NILFS. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-05-03 #*/ ## function ogFormatFs () { # Variables locales -local PART TYPE LABEL PROG PARAMS LABELPARAM ERRCODE +local PART ID TYPE LABEL PROG PARAMS LABELPARAM ERRCODE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -258,14 +268,16 @@ TYPE="${3:-$(ogGetFsType $1 $2)}" # Elegir tipo de formato. case "$TYPE" in - EXT2) PROG="mkfs.ext2" ;; - EXT3) PROG="mkfs.ext3" ;; - EXT4) PROG="mkfs.ext4" ;; - BTRFS) PROG="mkfs.btrfs" ;; + EXT2) PROG="mkfs.ext2"; PARAMS="-F" ;; + EXT3) PROG="mkfs.ext3"; PARAMS="-F" ;; + EXT4) PROG="mkfs.ext4"; PARAMS="-F" ;; + BTRFS) PROG="mkfs.btrfs"; PARAMS="-f" ;; REISERFS) PROG="mkfs.reiserfs"; PARAMS="-f"; LABELPARAM="-l" ;; - REISER4) PROG="mkfs.reiser4"; PARAMS="-fy" ;; + REISER4) PROG="mkfs.reiser4"; PARAMS="-f <<<\"y\"" ;; XFS) PROG="mkfs.xfs"; PARAMS="-f" ;; JFS) PROG="mkfs.jfs"; PARAMS="<<<\"y\"" ;; + F2FS) PROG="mkfs.f2fs"; LABELPARAM="-l" ;; + NILFS2) PROG="mkfs.nilfs2"; PARAMS="-f" ;; LINUX-SWAP) PROG="mkswap" ;; NTFS) PROG="mkntfs"; PARAMS="-f" ;; EXFAT) PROG="mkfs.exfat"; LABELPARAM="-n" ;; @@ -380,11 +392,14 @@ echo ${SIZE%.0*} #@version 1.0.5 - Usar "blkid" para detectar tipo de sistema de archivo. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2014-06-10 +#@version 1.1.0 - Detectar volumen ZFS. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2014-11-14 #*/ ## function ogGetFsType () { # Variables locales. -local PART TYPE +local PART ID TYPE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \ @@ -396,16 +411,25 @@ fi # Detectar tipo de sistema de archivo (independientemente del tipo de partición). PART=$(ogDiskToDev "$1" "$2") || return $? -TYPE=$(blkid -o export $PART | awk -F= '$1=="TYPE" { print toupper($2) }') +if [[ "$PART" =~ ^/ ]]; then + TYPE=$(blkid -o export $PART | awk -F= '$1~/^TYPE/ { print toupper($2) }') +else + zfs mount $PART 2>/dev/null + TYPE=$(mount | awk "\$1==\"$PART\" { print toupper(\$5) }") +fi # Componer valores correctos. case "$TYPE" in EXT4) # Comprobar si es caché o Ext4. - [ "$1 $2" == "$(ogFindCache)" ] && TYPE="CACHE" ;; - VFAT) TYPE="$(blkid -po export $PART | awk -F= '$1=="VERSION" { print toupper($2) }')" ;; + if [ "$1 $2" == "$(ogFindCache)" ]; then + ogIsFormated $1 $2 2>/dev/null && TYPE="CACHE" + fi + ;; + VFAT) TYPE="$(blkid -po export $PART | awk -F= '$1~/^VERSION$/ { print toupper($2) }')" ;; SWAP) TYPE="LINUX-SWAP" ;; LVM*) TYPE="LINUX-LVM" ;; *RAID*) TYPE="LINUX-RAID" ;; + ZFS_MEMBER) TYPE="ZVOL" ;; *_MEMBER) TYPE="${TYPE/_MEMBER/}" ;; esac @@ -464,6 +488,9 @@ findmnt -n -o TARGET $PART #@version 1.0.5 - Dejar de usar "parted". #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2012-09-04 +#@version 1.1.0 - Comprobar sin montar el sistema de ficheros. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-01-21 #*/ ## function ogIsFormated () { @@ -476,30 +503,49 @@ if [ "$*" == "help" ]; then fi # Falso, en caso de error. [ $# == 2 ] || return 1 -PART="$(ogDiskToDev $1 $2 2>/dev/null)" || return 1 +PART="$(ogDiskToDev $1 $2 2>/dev/null)" || return 1 -test -n "$(blkid -s TYPE $PART | egrep -vi "swap|_member")" +# Revisar tipo de sistema de ficheros. +if [[ "$PART" =~ ^/ ]]; then + # Sistemas de ficheros genéricos. + test -n "$(blkid -s TYPE $PART | egrep -vi "swap|_member")" +else + # ZFS. + test "$(zfs list -Hp -o canmount $PART 2>/dev/null)" = "on" +fi } #/** # ogIsLocked int_ndisk int_npartition -#@brief Comprueba si una partición está bloqueada por una operación de uso exclusivo. +#@see ogIsPartitionLocked +#*/ +function ogIsLocked () +{ +ogIsPartitionLocked "$@" +} + +#/** +# ogIsPartitionLocked int_ndisk int_npartition +#@brief Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo. #@param int_ndisk nº de orden del disco #@param int_npartition nº de orden de la partición #@return Código de salida: 0 - bloqueado, 1 - sin bloquear o error. -#@note El fichero de bloqueo se localiza en \c /var/lock/part, siendo \c part el dispositivo de la partición, sustituyendo el carácter "/" por "-". +#@note Los ficheros de bloqueo se localizan en \c /var/lock/dev, siendo \c dev el dispositivo de la partición o de su disco, sustituyendo el carácter "/" por "-". #@version 0.9 - Primera versión para OpenGnSys. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2009-09-03 #@version 1.0.1 - Devolver falso en caso de error. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2011-05-18 +#@version 1.1.0 - Comprobar si el disco está también bloqueado. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-04-08 #*/ ## -function ogIsLocked () +function ogIsPartitionLocked () { # Variables locales -local PART LOCKFILE +local DISK PART LOCKDISK LOCKPART # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -509,13 +555,13 @@ if [ "$*" == "help" ]; then fi # Falso, en caso de error. [ $# == 2 ] || return 1 +PART="$(ogDiskToDev $1 $2 2>/dev/null)" || return 1 +DISK="$(ogDiskToDev $1)" -# Obtener partición. -PART="$(ogDiskToDev $1 $2)" || return 1 - -# Comprobar existencia del fichero de bloqueo. -LOCKFILE="/var/lock/lock${PART//\//-}" -test -f $LOCKFILE +# Comprobar existencia de fichero de bloqueo de la partición o de su disco. +LOCKDISK="/var/lock/lock${DISK//\//-}" +LOCKPART="/var/lock/lock${PART//\//-}" +test -f $LOCKDISK -o -f $LOCKPART } @@ -547,6 +593,35 @@ test -n "$(ogGetMountPoint $1 $2)" } +#/** +# ogIsReadonly int_ndisk int_nfilesys +#@brief Comprueba si un sistema de archivos está montado solo de lectura. +#@param int_ndisk nº de orden del disco +#@param int_nfilesys nº de orden del sistema de archivos +#@return Código de salida: 0 - montado solo de lectura, 1 - con escritura o no montado. +#@version 1.1.0 - Primera versión para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-01-20 +#/** +function ogIsReadonly () +{ +# Variables locales +local PART + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys" \ + "if $FUNCNAME 1 1; then ... ; fi" + return +fi +# Falso, en caso de error. +[ $# == 2 ] || return 1 +PART="$(ogDiskToDev $1 $2 2>/dev/null)" || return 1 + +test -n "$(findmnt -n -o OPTIONS $PART | awk 'BEGIN {RS=","} /^ro$/ {print}')" +} + + #/** # ogIsWritable int_ndisk int_nfilesys #@brief Comprueba si un sistema de archivos está montado de lectura y escritura. @@ -570,9 +645,7 @@ if [ "$*" == "help" ]; then fi # Falso, en caso de error. [ $# == 2 ] || return 1 - -# Obtener partición. -PART="$(ogDiskToDev $1 $2)" || return 1 +PART="$(ogDiskToDev $1 $2 2>/dev/null)" || return 1 test -n "$(findmnt -n -o OPTIONS $PART | awk 'BEGIN {RS=","} /^rw$/ {print}')" } @@ -657,6 +730,9 @@ esac #@version 1.0.5 - Independiente del tipo de sistema de ficheros. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2012-09-04 +#@version 1.1.0 - Montar sistema de archivos ZFS y NTFS hibernado. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-09-19 #*/ ## function ogMountFs () { @@ -684,28 +760,66 @@ if [ -z "$MNTDIR" ]; then ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION, $1 $2" return $? fi - # Crear punto de montaje o enlace simbólico para caché local. - MNTDIR=${PART/dev/mnt} - if [ "$(ogFindCache)" == "$1 $2" -a -n "$OGCAC" ]; then - mkdir -p $OGCAC - ln -fs $OGCAC $MNTDIR + # El camino de un dispositivo normal comienza por el carácter "/". + if [[ "$PART" =~ ^/ ]]; then + # Crear punto de montaje o enlace simbólico para caché local. + MNTDIR=${PART/dev/mnt} + DEBUG="no" + if [ "$(ogFindCache)" == "$1 $2" -a -n "$OGCAC" ]; then + mkdir -p $OGCAC + ln -fs $OGCAC $MNTDIR + else + mkdir -p $MNTDIR + fi + unset DEBUG + # Montar sistema de archivos. + mount $PART $MNTDIR &>/dev/null || \ + mount $PART $MNTDIR -o force,remove_hiberfile &>/dev/null + case $? in + 0) # Correcto. + ;; + 14) # Intentar limpiar hibernación NTFS y montar. + ntfsfix -d $PART &>/dev/null && mount $PART $MNTDIR &>/dev/null || \ + ogRaiseError $OG_ERR_PARTITION "$1, $2" || return $? + ;; + *) # Probar montaje de solo lectura. + mount $PART $MNTDIR -o ro &>/dev/null || \ + ogRaiseError $OG_ERR_PARTITION "$1, $2" || return $? + ;; + esac + # Aviso de montaje de solo lectura. + if ogIsReadonly $1 $2; then + ogEcho warning "$FUNCNAME: $MSG_MOUNTREADONLY: \"$1, $2\"" + fi else - mkdir -p $MNTDIR + # Montar sistema de archivos ZFS (un ZPOOL no comienza por "/"). + zfs mount $PART 2>/dev/null fi - # Montar sistema de archivos. - mount $PART $MNTDIR &>/dev/null || \ - mount $PART $MNTDIR -o force,remove_hiberfile &>/dev/null || \ - ogRaiseError $OG_ERR_PARTITION "$1, $2" || return $? fi echo "$MNTDIR" } -##### PRUEBAS -# Montar CDROM +#/** +# ogMountCdrom +#@brief Monta dispositivo óptico por defecto +#@return Punto de montaje +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Tipo de particion desconocido o no se puede montar. +#@version +#@author +#@date +#*/ ## function ogMountCdrom () { local DEV MNTDIR +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME" "$FUNCNAME" + return +fi +# Error si se reciben parámetros. +[ $# == 0 ] || ogRaiseError $OG_ERR_FORMAT || return $? DEV="/dev/cdrom" # Por defecto MNTDIR=$(mount | awk -v D=$DEV '{if ($1==D) {print $3}}') if [ -z "$MNTDIR" ]; then @@ -777,9 +891,9 @@ case "$(ogGetFsType $1 $2)" in BTRFS) MNTDIR=$(ogMount $1 $2) - # Calcular tamaño ocupado + 10%. - SIZE=$[ $(df -k $MNTDIR | awk '{getline;print $3}') * 110 / 100 ] - btrfs filesystem resize ${SIZE}k $MNTDIR + # Calcular tamaño ocupado + 10%, redondeado + 1 (incluyendo letra de unidad). + SIZE=$(btrfs filesystem show $MNTDIR | awk -v P=$PART '{ if ($8==P) printf ("%d%s", $6*1.1+1, substr($6,match($6,/[A-Z]/),1)) }') + btrfs filesystem resize ${SIZE} $MNTDIR 2>/dev/null ;; REISERFS|REISER4) # Calcular tamaño ocupado + 10%. @@ -789,7 +903,9 @@ case "$(ogGetFsType $1 $2)" in resize_reiserfs -s${SIZE}K $PART <<<"y" ;; + F2FS) ;; # No se reduce (por el momento). JFS) ;; # No se reduce (por el momento). + NILFS2) ;; # No se reduce (probar "nilfs-resize"). XFS) ;; # No se reduce (por el momento). NTFS) @@ -1001,7 +1117,6 @@ case "$(ogGetFsType $1 $2)" in esac } - # AVISO: Componer corretcamente esta función. function ogGetFreeSize () { local particion unit factor valor diff --git a/client/engine/Image.lib b/client/engine/Image.lib index 7940b4f5..dfbcb487 100755 --- a/client/engine/Image.lib +++ b/client/engine/Image.lib @@ -4,12 +4,11 @@ #@brief Librería o clase Image #@class Image #@brief Funciones para creación, restauración y clonación de imágenes de sistemas. -#@version 1.0.5 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ - #/** # ogCreateImageSyntax path_device path_filename [str_tool] [str_compressionlevel] #@brief Genera una cadena de texto con la instrucción para crear un fichero imagen @@ -29,7 +28,7 @@ #*/ ## function ogCreateImageSyntax() { -local FS TOOL LEVEL PART IMGFILE BUFFER PARAM1 PARAM2 PARAM3 +local FS TOOL LEVEL DEV IMGFILE BUFFER PARAM1 PARAM2 PARAM3 # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -42,10 +41,10 @@ fi [ $# -ge 2 -a $# -le 4 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $? # Asignación de parámetros. -PART="$1" +DEV="$1" IMGFILE="$2" case "$#" in - 2) # Sintaxis por defecto OG PART IMGFILE + 2) # Sintaxis por defecto OG DEV IMGFILE TOOL="partclone" LEVEL="gzip" ;; @@ -57,14 +56,13 @@ esac case "$TOOL" in ntfsclone) - PARAM1="ntfsclone --force --save-image -O - $PART" + PARAM1="ntfsclone --force --save-image -O - $DEV" ;; partimage|default) - PARAM1="partimage -M -f3 -o -d -B gui=no -c -z0 --volume=0 save $PART stdout" + PARAM1="partimage -M -f3 -o -d -B gui=no -c -z0 --volume=0 save $DEV stdout" ;; partclone) - FS="$(ogGetFsType $(ogDevToDisk $PART 2>/dev/null) 2>/dev/null)" - umount $PART 2>/dev/null + FS="$(ogGetFsType $(ogDevToDisk $DEV 2>/dev/null) 2>/dev/null)" case "$FS" in EXT[234]) PARAM1="partclone.extfs" ;; BTRFS) PARAM1="partclone.btrfs" ;; @@ -72,16 +70,21 @@ case "$TOOL" in REISER4) PARAM1="partclone.reiser4" ;; JFS) PARAM1="partclone.jfs" ;; XFS) PARAM1="partclone.xfs" ;; + F2FS) PARAM1="partclone.f2fs" ;; + NILFS2) PARAM1="partclone.nilfs2" ;; NTFS) PARAM1="partclone.ntfs" ;; EXFAT) PARAM1="partclone.exfat" ;; FAT16|FAT32) PARAM1="partclone.fat" ;; HFS|HFSPLUS) PARAM1="partclone.hfsp" ;; UFS) PARAM1="partclone.ufs" ;; - *) PARAM1="partclone.dd" ;; + VMFS) PARAM1="partclone.vmfs" ;; + *) PARAM1="partclone.imager" ;; esac # Por compatibilidad, si no existe el ejecutable usar por defecto "parclone.dd". which $PARAM1 &>/dev/null || PARAM1="partclone.dd" - PARAM1="$PARAM1 -d0 -F -c -s $PART" + PARAM1="$PARAM1 -d0 -F -c -s $DEV" + # Algunas versiones de partclone.dd no tienen opción "-c". + [ -z "$(eval ${PARAM1%% *} --help 2>&1 | grep -- -c)" ] && PARAM1="${PARAM1/ -c / }" ;; esac # Comprobar que existe mbuffer. @@ -116,8 +119,7 @@ esac #@author Antonio J. Doblas Viso. Universidad de Málaga #@date 2010/02/08 #*/ ## - -ogRestoreImageSyntax () +function ogRestoreImageSyntax () { local TOOL COMPRESSOR LEVEL PART IMGFILE FILEHEAD INFOIMG @@ -177,17 +179,20 @@ if [ "$#" -eq 4 ]; then #comprobar mbuffer which mbuffer > /dev/null && MBUFFER="| mbuffer -q -m 40M " || MBUFFER=" " - case "$TOOL" in - "ntfsclone" | "NTFSCLONE") + case "${TOOL,,}" in + ntfsclone) TOOL="| ntfsclone --restore-image --overwrite $PART -" ;; - "partimage"| "PARTIMAGE") + partimage) TOOL="| partimage -f3 -B gui=no restore $PART stdin" ;; - "partclone" | "PARTCLONE") + partclone*) # -C para que no compruebe tamaños TOOL="| partclone.restore -d0 -C -I -o $PART" ;; + dd) + TOOL="| pv | dd conv=sync,noerror bs=1M of=$PART" + ;; *) ogRaiseError $OG_ERR_NOTFOUND "Tools imaging no valid $TOOL" || return $? ;; @@ -201,6 +206,88 @@ fi +#/** +# ogCreateDiskImage int_ndisk str_repo path_image [str_tools] [str_compressionlevel] +#@brief Crea una imagen (copia de seguridad) de un disco completo. +#@param int_ndisk nº de orden del disco +#@param str_repo repositorio de imágenes (remoto o caché local) +#@param path_image camino de la imagen (sin extensión) +#@return (nada, por determinar) +#@note repo = { REPO, CACHE } +#@note Esta primera versión crea imágenes con dd comprimidas con gzip. +#@exception OG_ERR_FORMAT formato incorrecto. +#@exception OG_ERR_NOTFOUND fichero o dispositivo no encontrado. +#@exception OG_ERR_LOCKED particion bloqueada por otra operación. +#@exception OG_ERR_IMAGE error al crear la imagen del sistema. +#@warning En pruebas iniciales +#@todo Gestión de bloqueos de disco +#@todo Comprobar si debe desmontarse la caché local +#@todo Comprobar que no se crea la imagen en el propio disco +#@version 1.1.0 - Primera versión para OpenGnsys con herramientas prefijadas. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@Date 2016/04/08 +#*/ ## +function ogCreateDiskImage () +{ +# Variables locales +local DISK PROGRAM IMGDIR IMGFILE IMGTYPE ERRCODE + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_repo path_image" \ + "$FUNCNAME 1 REPO /disk1" + return +fi +# Error si no se reciben entre 3 y 5 parámetros. +[ $# -ge 3 -a $# -le 5 ] || ogRaiseError $OG_ERR_FORMAT "$*" || return $? + +# Comprobar que no está bloqueada ni la partición, ni la imagen. +DISK="$(ogDiskToDev $1)" || return $? +if ogIsDiskLocked $1; then + ogRaiseError $OG_ERR_LOCKED "$MSG_LOCKED $1" + return $? +fi +IMGTYPE="dsk" # Extensión genérica de imágenes de disco. +IMGDIR=$(ogGetParentPath "$2" "$3") +[ -n "$IMGDIR" ] || ogRaiseError $OG_ERR_NOTFOUND "$2 $(dirname $3)" || return $? +IMGFILE="$IMGDIR/$(basename "$3").$IMGTYPE" +if ogIsImageLocked "$IMGFILE"; then + ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $3, $4" + return $? +fi + +# No guardar imagen en el propio disco (disco no incluido en el camino del repositorio). +if [[ $(ogGetPath "$2" /) =~ ^$DISK ]]; then + ogRaiseError $OG_ERR_IMAGE "$2 = $DISK" + return $? +fi + +# Generar la instruccion a ejecutar antes de aplicar los bloqueos. +PROGRAM=$(ogCreateImageSyntax $DISK $IMGFILE) +# Desmontar todos los sistemas de archivos del disco, bloquear disco e imagen. +ogUnmountAll $1 2>/dev/null +ogLockDisk $1 || return $? +ogLockImage "$2" "$3.$IMGTYPE" || return $? + +# Crear Imagen. +trap "ogUnlockDisk $1; ogUnlockImage "$3" "$4.$IMGTYPE"; rm -f $IMGFILE" 1 2 3 6 9 +eval $PROGRAM + +# Controlar salida de error, crear fichero de información y desbloquear partición. +ERRCODE=$? +if [ $ERRCODE == 0 ]; then + echo "$(ogGetImageInfo $IMGFILE):$(ogGetHostname)" > $IMGFILE.info +else + ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE" + rm -f "$IMGFILE" +fi +# Desbloquear disco e imagen. +ogUnlockDisk $1 +ogUnlockImage "$2" "$3.$IMGTYPE" +return $ERRCODE +} + + #/** # ogCreateImage int_ndisk int_npartition str_repo path_image [str_tools] [str_compressionlevel] #@brief Crea una imagen a partir de una partición. @@ -217,7 +304,6 @@ fi #@exception OG_ERR_PARTITION partición no accesible o no soportada. #@exception OG_ERR_LOCKED particion bloqueada por otra operación. #@exception OG_ERR_IMAGE error al crear la imagen del sistema. -#@warning En pruebas iniciales #@todo Comprobaciones, control de errores, definir parámetros, etc. #@version 0.1 - Integracion para Opengnsys - HIDRA:CrearImagen{EXT3, NTFS}.sh; EAC: CreateImageFromPartition () en Deploy.lib #@author Ramon Gomez, ETSII Universidad de Sevilla @@ -238,8 +324,8 @@ local PART PROGRAM IMGDIR IMGFILE IMGTYPE ERRCODE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart path_dir str_image" \ - "$FUNCNAME 1 1 REPO /aula1/winxp" + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart str_repo path_image" \ + "$FUNCNAME 1 1 REPO /aula1/win7" return fi # Error si no se reciben entre 4 y 6 parámetros. @@ -248,7 +334,7 @@ fi # Comprobar que no está bloqueada ni la partición, ni la imagen. PART="$(ogDiskToDev $1 $2)" || return $? if ogIsLocked $1 $2; then - ogRaiseError $OG_ERR_LOCKED "$MSG_PARTITION $1, $2" + ogRaiseError $OG_ERR_LOCKED "$MSG_LOCKED $1, $2" return $? fi @@ -272,9 +358,11 @@ ogLockImage "$3" "$4.$IMGTYPE" || return $? trap "ogUnlock $1 $2; ogUnlockImage "$3" "$4.$IMGTYPE"; rm -f $IMGFILE" 1 2 3 6 9 eval $PROGRAM -# Controlar salida de error y desbloquear partición. +# Controlar salida de error, crear fichero de información y desbloquear partición. ERRCODE=$? -if [ $ERRCODE != 0 ]; then +if [ $ERRCODE == 0 ]; then + echo "$(ogGetImageInfo $IMGFILE):$(ogGetHostname)" > $IMGFILE.info +else ogRaiseError $OG_ERR_IMAGE "$1 $2 $IMGFILE" rm -f "$IMGFILE" fi @@ -309,7 +397,7 @@ function ogCreateMbrImage () local DISK IMGDIR IMGFILE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \ + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_repo path_image" \ "$FUNCNAME 1 REPO /aula1/mbr" return fi @@ -347,7 +435,7 @@ function ogCreateBootLoaderImage () local DISK IMGDIR IMGFILE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk path_dir str_image" \ + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk str_repo path_image" \ "$FUNCNAME 1 REPO /aula1/mbr" return fi @@ -369,25 +457,39 @@ dd if="$DISK" of="$IMGFILE" bs=446 count=1 || ogRaiseError $OG_ERR_IMAGE "$1 $IM #@param int_disk numero de disco #@param int_part numero de particion #@param str_repo repositorio de imágenes { REPO, CACHE } +#@param str_imageName Nombre de la imagen #@param str_imageType Tipo de imagen: monolit (por defecto), sync o diff. (parametro opcional) -#@return SIZEDATA SIZEREQUIRED ISENOUGHSPACE +#@return SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE #@note si str_imageType= diff necesario /tmp/ogimg.info, que es creado por ogCreateInfoImage. +#@note para el tamaño de la imagen no sigue enlaces simbólicos. #@exception OG_ERR_FORMAT formato incorrecto. #@author Irina Gomez, ETSII Universidad de Sevilla #@date 2014/10/24 +#@version 1.1.0 - En la salida se incluye el espacio disponible en el repositorio (ticket #771) +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2017-03-28 +#@version 1.1.0 - Si la imagen ya existe en el REPO se suma su tamaño al espacio libre +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2017-11-08 #*/ ## function ogGetSizeParameters () { -local MNTDIR SIZEDATA KERNELVERSION SIZEREQUIRED FACTORGZIP FACTORLZOP SIZEFREE +local REPO MNTDIR SIZEDATA KERNELVERSION SIZEREQUIRED FACTORGZIP FACTORLZOP FACTORSYNC SIZEFREE +local IMGTYPE IMGDIR IMGFILE IMGEXT IMGSIZE + # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME num_disk num_part str_repo [monolic|sync|diff]" \ - "if $FUNCNAME 1 2 REPO sync ; then ...; fi" \ - "if $FUNCNAME 1 6 CACHE ; then ...; fi" + ogHelp "$FUNCNAME" "$FUNCNAME num_disk num_part str_repo path_imgname [monolit|sync|diff]" \ + "if $FUNCNAME 1 2 REPO Windows10 sync ; then ...; fi" \ + "if $FUNCNAME 1 6 Ubuntu16 CACHE ; then ...; fi" return fi # Error si no se reciben 1 o 2 parámetros. -[ $# -lt 3 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE [monolitic|sync]" ; echo $?) +[ $# -lt 4 ] && return $(ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE imgname [monolit|sync|diff]" ; echo $?) + +# Recogemos parametros +REPO=${3^^} +IMGTYPE="_${5^^}_" MNTDIR=$(ogMount $1 $2) if [ "$MNTDIR" == "" ]; then @@ -396,21 +498,22 @@ if [ "$MNTDIR" == "" ]; then fi # Datos contenidos en la particion o en la lista de archivos de contiene la diferencial. -if [ "_${4^^}_" == "_DIFF_" ]; then +if [ "$IMGTYPE" == "_DIFF_" ]; then [ -r /tmp/ogimg.info ] || return $(ogRaiseError session $OG_ERR_NOTFOUND "/tmp/ogimg.info"; echo $?) cd $MNTDIR SIZEDATA=$(grep -v "\/$" /tmp/ogimg.info | tr '\n' '\0'| du -x -c --files0-from=- 2>/dev/null|tail -n1 |cut -f1) + cd / else - SIZEDATA=$(df -k | grep $MNTDIR | awk '{print $3}') + SIZEDATA=$(df -k | grep $MNTDIR\$ | awk '{print $3}') fi #Aplicar factor de compresion -if [ "_${4^^}_" == "_SYNC_" -o "_${4^^}_" == "_DIFF_" ]; then +if [ "$IMGTYPE" == "_SYNC_" -o "$IMGTYPE" == "_DIFF_" ]; then # Sistema de fichero de la imagen según kernel, menor que 3.7 EXT4. comparamos revision KERNELVERSION=$(uname -r| awk '{printf("%d",$1);sub(/[0-9]*\./,"",$1);printf(".%02d",$1)}') [ $KERNELVERSION \< 3.07 ] && IMGFS="EXT4" || IMGFS=${IMGFS:-"BTRFS"} - FACTORSYNC=${FACTORSYNC:-"120"} + FACTORSYNC=${FACTORSYNC:-"130"} # Si IMGFS="BTRFS" la compresion es mayor. [ $IMGFS == "BTRFS" ] && let FACTORSYNC=$FACTORSYNC-20 @@ -425,13 +528,33 @@ else fi #Comprobar espacio libre en el contenedor. -[ "${3^^}" == "CACHE" ] && SIZEFREE=$(ogGetFreeSize `ogFindCache`) -[ "${3^^}" == "REPO" ] && SIZEFREE=$(df -k | grep $OGIMG | awk '{print $4}') +[ "$REPO" == "CACHE" ] && SIZEFREE=$(ogGetFreeSize `ogFindCache`) +[ "$REPO" == "REPO" ] && SIZEFREE=$(df -k | grep $OGIMG | awk '{print $4}') + +# Comprobamos si existe una imagen con el mismo nombre en $REPO +# En sincronizadas restamos tamaño de la imagen y en monoloticas de la .ant +case "${IMGTYPE}" in + _DIFF_) IMGEXT="img.diff" + ;; + _SYNC_) IMGEXT="img" + ;; + *) IMGEXT="img.ant" + ;; +esac -[ "$SIZEREQUIRED" -lt "$SIZEFREE" ] && ISENOUGHSPACE=TRUE || ISENOUGHSPACE=FALSE +IMGDIR=$(ogGetParentPath "$REPO" "/$4") +IMGFILE=$(ogGetPath "$IMGDIR/$(basename "/$4").$IMGEXT") +if [ -z "$IMGFILE" ]; then + IMGSIZE=0 +else + IMGSIZE=$(ls -s "$IMGFILE" | cut -f1 -d" ") +fi + +let SIZEFREE=$SIZEFREE+$IMGSIZE -echo $SIZEDATA $SIZEREQUIRED $ISENOUGHSPACE +[ "$SIZEREQUIRED" -lt "$SIZEFREE" ] && ISENOUGHSPACE=TRUE || ISENOUGHSPACE=FALSE +echo $SIZEDATA $SIZEREQUIRED $SIZEFREE $ISENOUGHSPACE } @@ -455,8 +578,8 @@ function ogIsImageLocked () # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \ - "if $FUNCNAME /opt/opengnsys/images/aula1/winxp.img; then ...; fi" \ - "if $FUNCNAME REPO /aula1/winxp.img; then ...; fi" + "if $FUNCNAME /opt/opengnsys/images/aula1/win7.img; then ...; fi" \ + "if $FUNCNAME REPO /aula1/win7.img; then ...; fi" return fi # Error si no se reciben 1 o 2 parámetros. @@ -488,8 +611,8 @@ local IMGDIR # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \ - "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \ - "$FUNCNAME REPO /aula1/winxp.img" + "$FUNCNAME /opt/opengnsys/images/aula1/win7.img" \ + "$FUNCNAME REPO /aula1/win7.img" return fi # Error si no se reciben 1 o 2 parámetros. @@ -501,6 +624,81 @@ touch $IMGDIR/$(basename "${!#}").lock 2>/dev/null || ogRaiseError $OG_ERR_NOTWR } +#/** +# ogRestoreDiskImage str_repo path_image int_npartition +#@brief Restaura (recupera) una imagen de un disco completo. +#@param str_repo repositorio de imágenes o caché local +#@param path_image camino de la imagen +#@param int_ndisk nº de orden del disco +#@return (por determinar) +#@warning Primera versión en pruebas +#@todo Gestionar bloqueos de disco +#@todo Comprobar que no se intenta restaurar de la caché sobre el mismo disco +#@exception OG_ERR_FORMAT formato incorrecto. +#@exception OG_ERR_NOTFOUND fichero de imagen o partición no detectados. +#@exception OG_ERR_LOCKED partición bloqueada por otra operación. +#@exception OG_ERR_IMAGE error al restaurar la imagen del sistema. +#@exception OG_ERR_IMGSIZEPARTITION Tamaño de la particion es menor al tamaño de la imagen. +#@version 1.1.0 - Primera versión para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@Date 2016/04/08 +#*/ ## +function ogRestoreDiskImage () +{ +# Variables locales +local DISK DISKSIZE IMGFILE IMGTYPE IMGSIZE PROGRAM ERRCODE + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk" \ + "$FUNCNAME REPO /aula1/win7 1" + return +fi +# Error si no se reciben 4 parámetros. +[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $? +# Procesar parámetros. +DISK="$(ogDiskToDev $3)" || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?) +IMGTYPE="dsk" +IMGFILE=$(ogGetPath "$1" "$2.$IMGTYPE") +[ -r "$IMGFILE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $3 $4"; echo $?) + +# comprobamos consistencia de la imagen +ogGetImageInfo $IMGFILE >/dev/null || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?) +# Error si la imagen no cabe en la particion. +#IMGSIZE=$(ogGetImageSize "$1" "$2") || return $(ogRaiseError $OG_ERR_IMAGE " $1 $2"; echo $?) +#DISKSIZE=$(ogGetDiskSize $3) +#if [ $IMGSIZE -gt $DISKSIZE ]; then +# ogRaiseError $OG_ERR_IMGSIZEPARTITION "$DISKSIZE < $IMGSIZE" +# return $? +#fi +# Comprobar el bloqueo de la imagen y de la partición. +if ogIsImageLocked "$IMGFILE"; then + ogRaiseError $OG_ERR_LOCKED "$MSG_IMAGE $1, $2.$IMGTYPE" + return $? +fi +if ogIsDiskLocked $3; then + ogRaiseError $OG_ERR_LOCKED "$MSG_DISK $3" + return $? +fi +# Solicitamos la generación de la instruccion a ejecutar +PROGRAM=$(ogRestoreImageSyntax $IMGFILE $DISK) + +# Bloquear el disco +ogLockDisk $3 || return $? +trap "ogUnlockDisk $3" 1 2 3 6 9 + +# Ejecutar restauración según el tipo de imagen. +eval $PROGRAM + +ERRCODE=$? +if [ $ERRCODE != 0 ]; then + ogRaiseError $OG_ERR_IMAGE "$IMGFILE, $3, $4" +fi +ogUnlockDisk $3 $4 +return $ERRCODE +} + + #/** # ogRestoreImage str_repo path_image int_ndisk int_npartition #@brief Restaura una imagen de sistema de archivos en una partición. @@ -538,8 +736,8 @@ local PART PARTSIZE IMGFILE IMGTYPE IMGSIZE FSTYPE PROGRAM ERRCODE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk int_npart" \ - "$FUNCNAME REPO /aula1/winxp 1 1" + ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk int_npart" \ + "$FUNCNAME REPO /aula1/win7 1 1" return fi # Error si no se reciben 4 parámetros. @@ -618,7 +816,7 @@ function ogRestoreMbrImage () local DISK IMGFILE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \ + ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk" \ "$FUNCNAME REPO /aula1/mbr 1" return fi @@ -654,7 +852,7 @@ function ogRestoreBootLoaderImage () local DISK IMGFILE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME path_dir str_image int_ndisk" \ + ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image int_ndisk" \ "$FUNCNAME REPO /aula1/mbr 1" return fi @@ -687,8 +885,8 @@ function ogUnlockImage () # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then ogHelp "$FUNCNAME" "$FUNCNAME [str_repo] path_image" \ - "$FUNCNAME /opt/opengnsys/images/aula1/winxp.img" \ - "$FUNCNAME REPO /aula1/winxp.img" + "$FUNCNAME /opt/opengnsys/images/aula1/win7.img" \ + "$FUNCNAME REPO /aula1/win7.img" return fi # Error si no se reciben 1 o 2 parámetros. @@ -720,12 +918,12 @@ function ogGetImageInfo () { # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME filename " \ - "$FUNCNAME /opt/opengnsys/images/prueba.img " + ogHelp "$FUNCNAME" "$FUNCNAME path_filename" \ + "$FUNCNAME /opt/opengnsys/images/prueba.img ==> PARTCLONE:LZOP:NTFS:5642158" return fi -# Error si no se reciben 1 parámetros. +# Error si no se recibe 1 parámetro. [ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $? #comprobando que el parametro uno es un file. @@ -786,7 +984,13 @@ then FS=$(echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $17;}' | awk '{sub(/\.\.+/," "); print toupper($2)}') SIZE=$( echo $PARTIMAGEINFO | awk '{gsub(/ /,"\n"); print $36;}' | awk '{sub(/\.\.+/," "); printf "%d\n",$2*1024*1024;}') IMGDETECT="TRUE" - fi + fi + if file $FILEHEAD 2> /dev/null | grep -q "boot sector"; then + TOOLS="partclone.dd" + FS= + SIZE= + IMGDETECT="TRUE" + fi fi #comprobamos valores #Chequeamos los valores devueltos. if [ -z "$TOOLS" -o -z "$COMPRESSOR" -o "$IMGDETECT" == "FALSE" ] @@ -798,34 +1002,58 @@ else fi } + function ogGetImageProgram () { local IMGFILE +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image" \ + "$FUNCNAME REPO prueba ==> PARTCLONE" + return +fi +# Error si no se reciben 2 parámetros. +[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? IMGFILE=$(ogGetPath "$1" "$2.img") || return $? [ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $? ogGetImageInfo $IMGFILE | awk -F: '{print $1}' - } + function ogGetImageCompressor () { local IMGFILE +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image" \ + "$FUNCNAME REPO prueba ==> LZOP" + return +fi +# Error si no se reciben 2 parámetros. +[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? IMGFILE=$(ogGetPath "$1" "$2.img") || return $? [ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $? ogGetImageInfo $IMGFILE | awk -F: '{print $2}' } + function ogGetImageType () { local IMGFILE +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME str_repo path_image" \ + "$FUNCNAME REPO prueba ==> NTFS" + return +fi +# Error si no se reciben 2 parámetros. +[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? IMGFILE=$(ogGetPath "$1" "$2.img") || return $? [ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $? -#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \ -# awk '/^Filesystem/ {sub(/\.\.+/," "); sub(/fs$/,""); print toupper($2);}' ogGetImageInfo $IMGFILE | awk -F: '{print $3}' - } + function ogGetImageSize () { # Variables locales @@ -833,8 +1061,8 @@ local IMGFILE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME REPO|CACHE /str_image" \ - "$FUNCNAME REPO /aula1/winxp ==> 5642158" + ogHelp "$FUNCNAME" "$FUNCNAME str repo path_image" \ + "$FUNCNAME REPO prueba ==> 5642158" return fi # Error si no se reciben 2 parámetros. @@ -844,8 +1072,6 @@ IMGFILE=$(ogGetPath "$1" "$2.img") || return $? [ -r "$IMGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$IMGFILE" || return $? # Devuelve el tamaño de la imagen en KB. -#partimage -B gui=no imginfo "$IMGFILE" 2>&1 | \ -# awk '/Partition size/ {sub(/\.\.+/," "); printf "%d\n",$3*1024*1024;}' ogGetImageInfo $IMGFILE | awk -F: '{print $4}' } diff --git a/client/engine/Inventory.lib b/client/engine/Inventory.lib index 4cbdcabb..3450b3e5 100755 --- a/client/engine/Inventory.lib +++ b/client/engine/Inventory.lib @@ -4,7 +4,7 @@ #@brief Librería o clase Inventory #@class Inventory #@brief Funciones para recogida de datos de inventario de hardware y software de los clientes. -#@version 1.0.6 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ @@ -48,6 +48,48 @@ ogGetOsVersion "$@" | cut -sf1 -d: } +#/** +# ogGetOsUuid int_ndisk int_nfilesys +#@brief Devuelve el UUID del sistema operativo instalado en un sistema de archivos. +#@param int_ndisk nº de orden del disco +#@param int_nfilesys nº de orden de la partición +#@return str_uuid - UUID del sistema operativo. +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_NOTFOUND Disco o partición no corresponden con un dispositiv +#@version 1.1.0 - Primera versión para OpenGnsys +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2015-09-09 +#*/ ## +function ogGetOsUuid () +{ +# Variables locales. +local MNTDIR +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_nfilesys" \ + "$FUNCNAME 1 2 => 540e47c6-8e78-4178-aa46-042e4803fb16" + return +fi +# Error si no se reciben 2 parametros. +[ $# = 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? + +# Montar la particion, si no lo estaba previamente. +MNTDIR=$(ogMount $1 $2) || return $? + +# Obtener UUID según el tipo de sistema operativo. +case "$(ogGetOsType $1 $2)" in + Linux) + # Leer el UUID del sistema de ficheros raíz o el fichero de identificador. + findmnt -no UUID $MNTDIR 2>/dev/null || cat $MNTDIR/etc/machine-id 2>/dev/null + ;; + Windows) + # Leer identificador en clave de registro. + ogGetRegistryValue $MNTDIR SOFTWARE '\Microsoft\Cryptography\MachineGuid' 2>/dev/null + ;; +esac +} + + #/** # ogGetOsVersion int_ndisk int_nfilesys #@brief Devuelve la versión del sistema operativo instalado en un sistema de archivos. @@ -126,8 +168,23 @@ fi # Para Windows: leer la version del registro. if [ -z "$VERSION" ]; then TYPE="Windows" - VERSION=$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows NT\CurrentVersion\ProductName' 2>/dev/null) - [ -n "$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows\CurrentVersion\ProgramW6432Dir' 2>/dev/null)" ] && IS64BIT="$MSG_64BIT" + FILE="$(ogGetHivePath $MNTDIR SOFTWARE)" + if [ -n "$FILE" ]; then + # Nuevo método más rápido para acceder al registro de Windows.. + VERSION=$(echo $(hivexsh << EOT 2>/dev/null +load $FILE +cd \Microsoft\Windows NT\CurrentVersion +lsval ProductName +lsval ReleaseId +EOT + )) + [ -n "$(reglookup -H -p "Microsoft/Windows/CurrentVersion/ProgramW6432Dir" "$FILE" 2>/dev/null)" ] && IS64BIT="$MSG_64BIT" + if [ -z "$VERSION" ]; then + # Compatibilidad con métrodo antiguo y más lento de acceder al registro. + VERSION=$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows NT\CurrentVersion\ProductName' 2>/dev/null) + [ -n "$(ogGetRegistryValue $MNTDIR software '\Microsoft\Windows\CurrentVersion\ProgramW6432Dir' 2>/dev/null)" ] && IS64BIT="$MSG_64BIT" + fi + fi fi # Para cargador Windows: buscar versión en fichero BCD (basado en os-prober). if [ -z "$VERSION" ]; then @@ -136,20 +193,20 @@ if [ -z "$VERSION" ]; then [ -z "$FILE" ] && FILE="$(ogGetPath $MNTDIR/EFI/Microsoft/boot/bcd)" if [ -n "$FILE" ]; then for DISTRIB in "Windows Recovery" "Windows Boot"; do - if grep -qs "$(echo "$DISTRIB" | sed 's/./&./g')" $FILE; then + if grep -aqs "$(echo "$DISTRIB" | sed 's/./&./g')" $FILE; then VERSION="$DISTRIB loader" fi done fi fi -# Para MacOS: detectar kernel y completar con fichero plist de información del sistema. +# Para macOS: detectar kernel y completar con fichero plist de información del sistema. if [ -z "$VERSION" ]; then TYPE="MacOS" # Kernel de Mac OS (no debe ser fichero de texto). FILE="$MNTDIR/mach_kernel" if [ -z "$(file -b $FILE | grep 'text')" ]; then # Obtener tipo de kernel. - [ -n "$(file -b $FILE | grep 'Mach-O')" ] && VERSION="Mac OS" + [ -n "$(file -b $FILE | grep 'Mach-O')" ] && VERSION="macOS" [ -n "$(file -b $FILE | grep 'Mach-O 64-bit')" ] && IS64BIT="$MSG_64BIT" # Datos de configuración de versión de Mac OS. FILE="$MNTDIR/System/Library/CoreServices/SystemVersion.plist" @@ -157,7 +214,7 @@ if [ -z "$VERSION" ]; then /ProductName/ {getline;s=$3} /ProductVersion/ {getline;v=$3} END {print s,v}' $FILE) - # Datos de recuperación de Mac OS. + # Datos de recuperación de macOS. FILE="$MNTDIR/com.apple.recovery.boot" [ -r $FILE -a -n "$VERSION" ] && VERSION="$VERSION recovery" fi @@ -168,7 +225,7 @@ if [ -z "$VERSION" ]; then TYPE="BSD" FILE="$MNTDIR/boot/kernel/kernel" if [ -r $FILE ]; then - VERSION="$(strings $FILE|awk '/@.*RELEASE/ {print $1,$2}')" + VERSION="$(strings $FILE|awk '/@.*RELEASE/ {sub(/@\(#\)/,""); print $1,$2}')" [ -n "$(file -b $FILE | grep 'x86-64')" ] && IS64BIT="$MSG_64BIT" fi fi @@ -196,16 +253,38 @@ return 0 } +#/** +# ogGetSerialNumber +#@brief Obtiene el nº de serie del cliente. +#@version 1.1.0 - Primeras versión con OpenGnsys +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2015-06-08 +function ogGetSerialNumber () +{ +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME" + return +fi + +# Obtener nº de serie (ignorar los no especificados) +dmidecode -s system-serial-number | egrep -vi "(^[ 0]+$|not specified|filled by o.e.m.)" +} + + #/** # ogListHardwareInfo #@brief Lista el inventario de hardware de la máquina cliente. #@return TipoDispositivo:Modelo (por determinar) #@warning Se ignoran los parámetros de entrada. -#@note TipoDispositivo = { ata, bio, boa, cdr, cpu, dis, fir, mem, mod, mul, net, ser, vga } -#@note Requisitos: lshw, awk +#@note TipoDispositivo = { bio, boa, bus, cha, cdr, cpu, dis, fir, mem, mod, mul, net, sto, usb, vga } +#@note Requisitos: dmidecode, lshw, awk #@version 0.1 - Primeras pruebas con OpenGnSys #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2009-07-28 +#@version 1.1.0 - Incluir nuevos componentes al inventario. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2014-04-23 #*/ ## function ogListHardwareInfo () { @@ -215,34 +294,51 @@ if [ "$*" == "help" ]; then return fi -# Recopilación de disposibivos procesando la salida de \c lshw +# Recopilación de dispositivos procesando la salida de \c lshw ogEcho info "$MSG_HARDWAREINVENTORY}" +echo "cha=$(dmidecode -s chassis-type)" | grep -v "Other" +[ -e /sys/firmware/efi ] && echo "boo=UEFI" || echo "boo=BIOS" lshw | awk 'BEGIN {type="mod";} - /product:/ {sub(/ *product: */,""); prod=$0;} - /vendor:/ {sub(/ *vendor: */,""); vend=$0;} - /version:/ {sub(/ *version: */,"v.");vers=$0;} - /size:/ {sub(/ *size: */,""); size=$0;} - /\*-/ {if (type=="mem") - print type"="size; - else - if (type!="" && prod!="") + /product:/ {sub(/ *product: */,""); prod=$0;} + /vendor:/ {sub(/ *vendor: */,""); vend=$0;} + /version:/ {sub(/ *version: */,"v.");vers=$0;} + /size:/ {size=$2;} + /clock:/ {clock=$2;} + /slot:/ {sub(/ *slot: */,""); slot=$0;} + /\*-/ {if (type=="mem"){ + if (size!=""){ + numbank++; + print type"="vend,prod,size,clock" ("slot")";} + }else{ + if (type=="totalmem"){ + if (size!=""){ + totalmemory="mem="size;} + }else{ + if (type!="" && prod!=""){ + if (prod=="v."vers) + vers=""; + print type"="vend,prod,size,vers;} } + } + type=prod=vend=vers=size=clock=slot="";} + $1~/-core/ {type="boa";} + $1~/-firmware/ {type="bio";} + $1~/-cpu/ {type="cpu";} + $1~/-bank/ {type="mem";} + $1~/-memory/ {type="totalmem";} + $1~/-ide/ {type="ide";} + $1~/-storage/ {type="sto";} + $1~/-disk/ {type="dis";} + $1~/-cdrom/ {type="cdr";} + $1~/-display/ {type="vga";} + $1~/-network/ {type="net";} + $1~/-multimedia/ {type="mul";} + $1~/-usb/ {type="usb";} + $1~/-firewire/ {type="fir";} + $1~/-serial/ {type="bus";} + END {if (type!="" && prod!="") print type"="vend,prod,size,vers; - type=prod=vend=vers=size="";} - /-core/ {type="boa";} - /-firmware/ {type="bio";} - /-cpu/ {type="cpu";} - /-memory/ {type="mem";} - /-ide/ {type="ide";} - /-disk/ {type="dis";} - /-cdrom/ {type="cdr";} - /-display/ {type="vga";} - /-network/ {type="net";} - /-multimedia/ {type="mul";} - /-usb/ {type="usb";} - /-firewire/ {type="fir";} - /-serial/ {type="bus";} - END {if (type!="" && prod!="") - print type"="vend,prod,size,vers;} + if (length(numbank)==0 && length(totalmemory)>=4) + print totalmemory; } ' # */ (comentario para Doxygen) } @@ -263,14 +359,17 @@ lshw | awk 'BEGIN {type="mod";} #@version 1.0.5 - Aproximación para inventario de software de Mac OS. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2013-10-08 -#@version 1.0.6 - Proceso depende del tipo de SO y sporte para FreeBSD. +#@version 1.0.6 - Proceso depende del tipo de SO y soporte para FreeBSD. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2014-11-13 +#@version 1.1.0 - Se muestra el sistema operativo en la primera línea de la salida +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2016-04-26 #*/ ## function ogListSoftware () { # Variables locales. -local MNTDIR TYPE DPKGDIR RPMDIR PACMANDIR KEYS KEYS32 k PROG VERS +local MNTDIR TYPE DPKGDIR RPMDIR PACMANDIR k # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -284,29 +383,23 @@ fi MNTDIR=$(ogMount $1 $2) || return $? TYPE=$(ogGetOsType $1 $2) || return $? +# Sistema Operativo en la primera línea de la salida +ogGetOsVersion $1 $2 | awk -F ':' '{print $2}' + case "$TYPE" in Linux) # Software de GNU/Linux. # Procesar paquetes dpkg. DPKGDIR="${MNTDIR}/var/lib/dpkg" if [ -r $DPKGDIR ]; then - # dpkg --admindir=$DPKGDIR -l | \ # Proceso de fichero en sistemas de 64 bits. - if [ -e $MNTDIR/lib64 ]; then - awk '/Package:/ {if (pack!="") print pack,vers; - sub(/-dev$/,"",$2); - pack=$2} - /Version:/ {sub(/^.*:/,"",$2); sub(/-.*$/,"",$2); - vers=$2} - /Status:/ {if ($2!="install") pack=vers=""} - END {if (pack!="") print pack,vers} - ' $DPKGDIR/status | sort | uniq - else - # FIXME Sólo 32 bits - chroot "$MNTDIR" /usr/bin/dpkg -l | \ - awk '$1~/ii/ {sub(/-dev$/,"",$2); sub(/^.*:/,"",$3); - sub(/-.*$/,"",$3); print $2,$3} - ' | sort | uniq - fi + awk '/Package:/ {if (pack!="") print pack,vers; + sub(/-dev$/,"",$2); + pack=$2} + /Version:/ {sub(/^.*:/,"",$2); sub(/-.*$/,"",$2); + vers=$2} + /Status:/ {if ($2!="install") pack=vers=""} + END {if (pack!="") print pack,vers} + ' $DPKGDIR/status | sort | uniq fi # Procesar paquetes RPM. RPMDIR="${MNTDIR}/var/lib/rpm" @@ -330,29 +423,50 @@ for k in db.keys(): # Procesar paquetes pacman. PACMANDIR="${MNTDIR}/var/lib/pacman/local" if [ -r $PACMANDIR ]; then - # FIXME Separar nombre y versión de los paquetes - ls -A $PACMANDIR + ls $PACMANDIR | awk -F- '/-/ {print gensub(/-/, " ", NF-2);}' fi ;; Windows) # Software de Windows. - # Claves de registro para programas instalados: formato "{clave}". - KEYS=$(ogListRegistryKeys $MNTDIR software '\Microsoft\Windows\CurrentVersion\Uninstall') - KEYS32=$(ogListRegistryKeys $MNTDIR software '\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall') - # Mostrar los valores "DisplayName" y "DisplayVersion" para cada clave. - (for k in $KEYS; do - PROG=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName") - if [ -n "$PROG" ]; then - VERS=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion") - echo "$PROG $VERS" + # Comprobar tipo de proceso del registro de Windows. + if which hivexregedit &>/dev/null; then + # Nuevo proceso más rápido basado en "hivexregedit". + local HIVE TMPFILE + HIVE=$(ogGetHivePath $MNTDIR software 2>/dev/null) + if [ -n "$HIVE" ]; then + # Claves de registro para programas instalados. + TMPFILE=/tmp/tmp$$ + trap "rm -f $TMPFILE" 1 2 3 9 15 + hivexregedit --unsafe-printable-strings --export "$HIVE" '\Microsoft\Windows\CurrentVersion\Uninstall' > $TMPFILE 2>/dev/null + hivexregedit --unsafe-printable-strings --export "$HIVE" '\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall' >> $TMPFILE 2>/dev/null + # Mostrar los valores "DisplayName" y "DisplayVersion" para cada clave. + awk -F\" '$1~/^\[/ {n=""} + $2~/DisplayName/ {n=$4} + $2~/DisplayVersion/ {print n,$4} + ' $TMPFILE | sort | uniq + rm -f $TMPFILE fi - done - for k in $KEYS32; do - PROG=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName") - if [ -n "$PROG" ]; then - VERS=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion") - echo "$PROG $VERS" - fi - done) | sort | uniq + else + # Compatibilidad con clientes ogLive antiguos. + local KEYS KEYS32 PROG VERS + # Claves de registro para programas instalados: formato "{clave}". + KEYS=$(ogListRegistryKeys $MNTDIR software '\Microsoft\Windows\CurrentVersion\Uninstall') + KEYS32=$(ogListRegistryKeys $MNTDIR software '\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall') + # Mostrar los valores "DisplayName" y "DisplayVersion" para cada clave. + (for k in $KEYS; do + PROG=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName") + if [ -n "$PROG" ]; then + VERS=$(ogGetRegistryValue $MNTDIR software "\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion") + echo "$PROG $VERS" + fi + done + for k in $KEYS32; do + PROG=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayName") + if [ -n "$PROG" ]; then + VERS=$(ogGetRegistryValue $MNTDIR software "\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$k\\DisplayVersion") + echo "$PROG $VERS" + fi + done) | sort | uniq + fi ;; MacOS) # Software de Mac OS. # Listar directorios de aplicaciones e intentar obtener la versión del fichero .plist (tanto original como descomprimido). @@ -373,48 +487,3 @@ for k in db.keys(): return $? ;; esac } - - -#/** @function ogInfoCache: @brief muestra la informacion de la CACHE. -#@param sin parametros -#@return texto que se almacena en $IP.-InfoCache. punto_montaje, tama?oTotal, TamanioOcupado, TaminioLibre, imagenes dentro de la cahce -#@warning Salidas de errores no determinada -#@warning printf no soportado por busybox -#@attention -#@version 0.1 Date: 27/10/2008 Author Antonio J. Doblas Viso. Universidad de Malaga -#*/ -function ogInfoCache () -{ -local info infoFilesystem infoSize infoUsed infoUsedPorcet infoMountedOn content -if ogMountCache -then - info=`df -h | grep $OGCAC` - infoFilesystem=`echo $info | cut -f1 -d" "` - infoSize=`echo $info | cut -f2 -d" "` - infoUsed=`echo $info | cut -f3 -d" "` - infoAvail=`echo $info | cut -f4 -d" "` - infoUsedPorcet=`echo $info | cut -f5 -d" "` - infoMountedOn=`echo $info | cut -f2 -d" "` - if `ls ${OGCAC}$OGIMG > /dev/null 2>&1` - then - cd ${OGCAC}${OPENGNSYS} - #content=`find images/ -type f -printf "%h/ %f %s \n"` busybox no soporta printf - content=`find images/ -type f` - cd / - echo $info - echo -ne $content - echo " " - #echo "$info" > ${OGLOG}/${IP}-InfoCache - #echo "$content" >> {$OGLOG}/${IP}-InfoCache - else - echo $info - #echo "$info" > {$OGLOG}/${IP}-InfoCache - fi - ogUnmountCache -else - echo " " - #echo " " > {$OGLOG}/${IP}-InfoCache - -fi -} - diff --git a/client/engine/Net.lib b/client/engine/Net.lib index f76dcc11..17c932d2 100755 --- a/client/engine/Net.lib +++ b/client/engine/Net.lib @@ -9,9 +9,66 @@ #*/ +#/** +# ogChangeRepo IPREPO [ OgUnit ] +#@brief Cambia el repositorio para el recurso remoto images. +#@param 1 Ip Repositorio +#@param 2 Abreviatura Unidad Organizativa +#@return Cambio recurso remoto en OGIMG. +#@version 1.1 - Primera versión para OpenGnSys. +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-06-16 +#*/ +function ogChangeRepo { +local SRCIMG NEWREPO REPO OGUNIT + +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME IPREPO [ OgUnit ]" \ + "$FUNCNAME 10.1.120.3" \ + "$FUNCNAME 10.1.120.3 cdc" + return +fi + + +if [ $# -lt 1 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $FUNCNAME IPREPO [ OgUnit ]" + return $? +fi + + +# Si REPO tomamos el repositorio y la unidad organizativa actual +REPO=$(ogGetRepoIp) +OGUNIT="$(df | awk -F " " '/oglog/ {sub("//.*/oglog","",$1); sub("/","",$1); print $1}')" + +# Parametros de entrada. Si $1 = "REPO" dejo el repositorio actual +[ "${1^^}" == "REPO" ] && NEWREPO="$REPO" || NEWREPO="${1}" + +# Si $1 y $2 son el repositorio y la OU actual me salgo +[ "$NEWREPO" == "$REPO" ] && [ "$2" == "$OGUNIT" ] && return 0 + +source /scripts/functions +source /scripts/ogfunctions +umount $OGIMG +[ "$2" == "" ] && SRCIMG="ogimages" || SRCIMG="ogimages/$2" +eval $(grep "OPTIONS=" /scripts/ogfunctions) +[ "$ogactiveadmin" == "true" ] && RW=",rw" || RW=",ro" + +ogEcho session log "$MSG_HELP_ogChangeRepo $NEWREPO ${2%/}" +ogConnect $NEWREPO $ogprotocol $SRCIMG $OGIMG $RW + +# Si da error volvemos a montar el inicial +if [ $? -ne 0 ]; then + ogConnect $REPO $ogprotocol $SRCIMG $OGIMG $RW + ogRaiseError session $OG_ERR_REPO "$NEWREPO" + return $? +fi + +} + + #/** # ogGetGroupDir [ str_repo ] -#@brief Devuelve el cmaino del directorio para el grupo del cliente. +#@brief Devuelve el camino del directorio para el grupo del cliente. #@param str_repo repositorio de imágenes (opcional) #@return path_dir - Camino al directorio del grupo. #@note repo = { REPO, CACHE } REPO por defecto @@ -41,6 +98,8 @@ if [ -n "$GROUP" ]; then DIR=$(ogGetPath "$REPO" "/groups/$GROUP" 2>/dev/null) [ -d "$DIR" ] && echo "$DIR" fi +# Para que no haya error al fallar la condición anterior +return 0 } diff --git a/client/engine/PostConf.lib b/client/engine/PostConf.lib index e82c00cb..4f760255 100755 --- a/client/engine/PostConf.lib +++ b/client/engine/PostConf.lib @@ -4,7 +4,7 @@ #@brief Librería o clase PostConf #@class PostConf #@brief Funciones para la postconfiguración de sistemas operativos. -#@version 1.0.5 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ @@ -59,13 +59,18 @@ esac #*/ ## function ogInstallMiniSetup () { +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$MSG_SEE ogInstallFirstBoot ogInstallRunonce" + return +fi case $# in 3) # Ejecución en el primer arranque de la máquina. ogInstallFirstBoot "$@" ;; 6|8) # Ejecución en el "runonce". ogInstallRunonce "$@" ;; *) ogRaiseError $OG_ERR_FORMAT - exit $? ;; + return $? ;; esac } @@ -141,6 +146,9 @@ ogSetRegistryValue "$MNTDIR" SYSTEM "\Setup\CmdLine" "cmd.exe /c $(basename $CMD #@version 1.0.4 - Heredado de antigua función ogInstallMiniSetup #@author Jonathan Alonso Martinez - Universidad Autonoma de Barcelona #@date 2012-04-16 +#@version 1.1.0 - Resuelve problemas a partir de Windows 10 +#@author Carmelo Cabezuelo Aguilar - Universidad Politécnica de Valencia +#@date 2018-02-20 #*/ ## function ogInstallRunonce () { @@ -184,10 +192,16 @@ fi #Creamos las claves de registro necesarias para que meter el cmd en el runonce del usuario y este haga autologin ogAddRegistryValue $MOUNTPOINT software '\Microsoft\Windows\CurrentVersion\RunOnce\PostConfiguracion' 2>/dev/null ogSetRegistryValue $MOUNTPOINT software '\Microsoft\Windows\CurrentVersion\RunOnce\PostConfiguracion' "C:\windows\system32\\$3" 2>/dev/null +ogAddRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoAdminLogon' 2>/dev/null ogSetRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoAdminLogon' 1 2>/dev/null +ogAddRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' 2>/dev/null ogSetRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' "$4" 2>/dev/null +ogAddRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultDomainName' 2>/dev/null +ogSetRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultDomainName' ".\\" 2>/dev/null ogAddRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultPassword' 2>/dev/null ogSetRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultPassword' "$5" 2>/dev/null +ogDeleteRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\ForceAutoLockOnLogon' 2>/dev/null +ogDeleteRegistryValue $MOUNTPOINT software '\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoLogonCount' 2>/dev/null } #/** @@ -220,8 +234,9 @@ fi [ $# == 4 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?) # Punto de montaje MOUNTPOINT="$(ogMount "$1" "$2")" || return $? -# Comprobar que existe el fichero de comandos. +# Crear fichero de comandos, si no existe. CMDFILE="$(ogGetPath "$MOUNTPOINT/windows/system32")/$3" +[ -n "$CMDFILE" ] || ogInstallMiniSetup "$1" "$2" "$3" [ -n "$CMDFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$MOUNTPOINT/windows/system32/$3" || return $? # Concatenamos el comando en el fichero de comandos @@ -304,9 +319,49 @@ EOF ### PRUEBAS. +#/** +# ogConfigureOgagent int_ndisk int_filesys +#@brief Modifica el fichero de configuración del nuevo agente OGAent para sistemas operativos. +#@param int_ndisk nº de orden del disco +#@param int_filesys nº de orden del sistema de archivos +#@return (nada) +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_NOTFOUND Fichero o dispositivo no encontrado. +#@exception OG_ERR_LOCKED Sistema de archivos bloqueado. +#@version 1.1.0 - Primera adaptación para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-07-15 +#*/ ## +function ogConfigureOgagent () +{ +# Variables locales. +local MNTDIR AGENTDIR CFGFILE +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys" \ + "$FUNCNAME 1 1" + return +fi + +# Error si no se reciben 2 parámetros. +[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? +# Obtener sistema de archvios. +MNTDIR=$(ogMount $1 $2) || return $? + +# Comprobar si existe el fichero de configuración de OGAgent. +for AGENTDIR in usr/share/OGAgent "Program Files/OGAgent" "Program Files (x86)/OGAgent" Applications/OGAgent.app; do + CFGFILE=$(ogGetPath "$MNTDIR/$AGENTDIR/cfg/ogagent.cfg") + [ -n "$CFGFILE" ] && break +done +[ -n "$CFGFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "ogagent.cfg" || return $? +# Parchear dirección del servidor OpenGnsys en el fichero de configuración de OGAgent. +sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," "$CFGFILE" +} + + #/** # ogInstallLaunchDaemon int_ndisk int_nfilesys str_filename -#@brief Instala archivo que se ejecutará en el arranque de Mac OS. +#@brief Instala archivo que se ejecutará en el arranque de macOS. #@param int_ndisk nº de orden del disco #@param int_nfilesys nº de orden del sistema de archivos #@param str_filename nombre del script @@ -480,7 +535,7 @@ ogUnlock $1 $2 #/** -# ogInstallWindowsClient int_ndisk int_filesys +# ogInstallWindowsClient int_ndisk int_filesys str_filename #@brief Instala el cliente OpenGnSys para sistemas operativos Windows. #@param int_ndisk nº de orden del disco #@param int_npartition nº de orden de la partición @@ -501,10 +556,11 @@ ogUnlock $1 $2 function ogInstallWindowsClient () { # Variables locales. -local MNTDIR CLIENTFILE i SBINDIR ETCDIR RCLOCAL +local MNTDIR CLIENTFILE i DIR WINDIR # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys" \ + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_filename" \ + "$FUNCNAME 1 1 filename.cmd" return fi @@ -527,3 +583,80 @@ ogAddCmd $1 $2 $3 "ogAdmWinClient -remove" ogAddCmd $1 $2 $3 "ogAdmWinClient -install -s $(ogGetServerIp) -p 2008 -i $(ogGetIpAddress)" } + + +#/** +# ogUninstallLinuxClient int_ndisk int_filesys +#@brief Desinstala el cliente OpenGnSys para sistemas operativos GNU/Linux. +#@param int_ndisk nº de orden del disco +#@param int_filesys nº de orden del sistema de archivos +#@return (nada) +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Paritición o sistema de archivos incorrectos. +#@exception OG_ERR_LOCKED Sistema de archivos bloqueado. +#@version 1.1.0 - Primera adaptación para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-08-22 +#*/ ## +function ogUninstallLinuxClient () +{ +# Variables locales. +local MNTDIR +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys" \ + "$FUNCNAME 1 1" + return +fi + +# Error si no se reciben 2 parámetros. +[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? +# Obtener sistema de archvios. +MNTDIR=$(ogMount $1 $2) || return $? + +# Borrar ficheros y quitar llamada al cliente durante el proceso de inicio. +rm -f $MNTDIR/{usr/sbin,sbin,usr/local/sbin}/ogAdmLnxClient +rm -f $MNTDIR/{etc,usr/local/etc}/ogAdmLnxClient.cfg +sed -i -e '/ogAdmLnxClient/ d' $MNTDIR/{etc,usr/local/etc}/{rc.local,rc.d/rc.local} 2>/dev/null +} + + +#/** +# ogUninstallWindowsClient int_ndisk int_filesys str_filename +#@brief Desinstala el cliente OpenGnSys para sistemas operativos Windows. +#@param int_ndisk nº de orden del disco +#@param int_npartition nº de orden de la partición +#@param str_filename nombre del fichero cmd donde deberemos introducir el comando de ejecutar el script vbs +#@return (nada) +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Paritición o sistema de archivos incorrectos. +#@exception OG_ERR_LOCKED Sistema de archivos bloqueado. +#@version 1.1.0 - Primera adaptación para OpenGnsys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-08-22 +#*/ ## + +function ogUninstallWindowsClient () +{ +# Variables locales. +local MNTDIR +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_filesys str_filename" \ + "$FUNCNAME 1 1 filename.cmd" + return +fi + +# Error si no se reciben 3 parámetros. +[ $# == 3 ] || ogRaiseError $OG_ERR_FORMAT || return $? +# Obtener sistema de archvios. +MNTDIR=$(ogMount "$1" "$2") || return $? + +# Crear órdenes para desinstalar servicio y borrar ejecutable del cliente. +if [ -n "$(ogGetPath $MNTDIR/windows/ogAdmWinClient.exe)" -o -n "$(ogGetPath $MNTDIR/winnt/ogAdmWinClient.exe)" ]; then + ogAddCmd $1 $2 "$3" 'ogAdmWinClient -remove' + ogAddCmd $1 $2 "$3" 'DEL C:\Windows\ogAdmWinClient.exe' + ogAddCmd $1 $2 "$3" 'DEL C:\Winnt\ogAdmWinClient.exe' +fi +} + diff --git a/client/engine/PostConfEAC.lib b/client/engine/PostConfEAC.lib index cb121081..6826620d 100755 --- a/client/engine/PostConfEAC.lib +++ b/client/engine/PostConfEAC.lib @@ -601,3 +601,96 @@ schroot -c linux schroot -end-sessiona --all-sessions } + +#/** @function ogDiskToRelativeDev: @brief Traduce los ID de discos o particiones EAC a ID Linux relativos, es decir 1 1 => sda1 +#@param Admite 1 parametro: $1 int_numdisk +#@param Admite 2 parametro: $1 int_numdisk $2 int_partition +#@return Para 1 parametros traduce Discos Duros: Devuelve la ruta relativa linux del disco duro indicado con nomenclatura EAC.........ejemplo: IdPartition 1 => sda +#@return Para 2 parametros traduce Particiones: Devuelve la ruta relativa linux de la particion indicado con nomenclatura EAC........... ejemplo: IdPartition 2 1 => sdb1 +#@warning No definidas +#@attention +#@note Notas sin especificar +#@version 0.1 - Integracion para Opengnsys - EAC: IdPartition en ATA.lib +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 27/10/2008 +#*/ +function ogDiskToRelativeDev () { +if [ $# = 0 ] +then + Msg "Info: Traduce el identificador del dispositivo EAC a dispositivo linux \n" info + Msg "Sintaxis1: IdPartition int_disk -----------------Ejemplo1: IdPartition 1 -> sda " example + Msg "Sintaxis2: IdPartition int_disk int_partition --Ejemplo2: IdPartition 1 2 -> sda2 " example + +return +fi +#PART="$(Disk|cut -f$1 -d' ')$2" # se comenta esta linea porque doxygen no reconoce la funcion disk y no crea los enlaces y referencias correctas. +PART=$(ogDiskToDev|cut -f$1 -d' ')$2 +echo $PART | cut -f3 -d \/ +} + + +#/** @function ogDeletePartitionsLabels: @brief Elimina la informacion que tiene el kernel del cliente og sobre los labels de los sistemas de archivos +#@param No requiere +#@return Nada +#@warning +#@attention Requisitos: comando interno linux rm +#@note +#@version 0.1 - Integracion para Opengnsys - EAC: DeletePartitionTable() en ATA.lib +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 27/10/2008 +#*/ +function ogDeletePartitionsLabels () { +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME " \ + "$FUNCNAME " + return +fi + +rm /dev/disk/by-label/* # */ COMENTARIO OBLIGATORIO PARA DOXYGEN +} + + +#/** @function ogInfoCache: @brief muestra la informacion de la CACHE. +#@param sin parametros +#@return texto que se almacena en $IP.-InfoCache. punto_montaje, tama?oTotal, TamanioOcupado, TaminioLibre, imagenes dentro de la cahce +#@warning Salidas de errores no determinada +#@warning printf no soportado por busybox +#@attention +#@version 0.1 Date: 27/10/2008 Author Antonio J. Doblas Viso. Universidad de Malaga +#*/ +function ogInfoCache () +{ +local info infoFilesystem infoSize infoUsed infoUsedPorcet infoMountedOn content +if ogMountCache +then + info=`df -h | grep $OGCAC` + infoFilesystem=`echo $info | cut -f1 -d" "` + infoSize=`echo $info | cut -f2 -d" "` + infoUsed=`echo $info | cut -f3 -d" "` + infoAvail=`echo $info | cut -f4 -d" "` + infoUsedPorcet=`echo $info | cut -f5 -d" "` + infoMountedOn=`echo $info | cut -f2 -d" "` + if `ls ${OGCAC}$OGIMG > /dev/null 2>&1` + then + cd ${OGCAC}${OPENGNSYS} + #content=`find images/ -type f -printf "%h/ %f %s \n"` busybox no soporta printf + content=`find images/ -type f` + cd / + echo $info + echo -ne $content + echo " " + #echo "$info" > ${OGLOG}/${IP}-InfoCache + #echo "$content" >> {$OGLOG}/${IP}-InfoCache + else + echo $info + #echo "$info" > {$OGLOG}/${IP}-InfoCache + fi + ogUnmountCache +else + echo " " + #echo " " > {$OGLOG}/${IP}-InfoCache + +fi +} + diff --git a/client/engine/Protocol.lib b/client/engine/Protocol.lib index 36ef1fba..49a83d73 100755 --- a/client/engine/Protocol.lib +++ b/client/engine/Protocol.lib @@ -91,7 +91,7 @@ else fi #3er param check - que puede ser un dispositvo o un fichero. -#ogGetPath "$3" > /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $3" || PERROR=9 #return $? +#[ -n "$(ogGetPath "$3")" ] || ogRaiseError $OG_ERR_NOTFOUND " device or file $3" || PERROR=9 #return $? DEVICE=$3 #4 y 5 param check . solo si es sobre particiones. @@ -331,15 +331,21 @@ fi #@version 1.0 - #@author Antonio Doblas Viso, Universidad de Málaga #@date 2010/05/09 +#@version 2.0 - cambios en udp-receiver para permitir multicast entre subredes +#@author Juan Carlos Garcia, Universidad de Zaragoza +#@date 2015/11/17 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 #*/ ## # function ogMcastSyntax () { -local ISUDPCAST PARM SESSION SESSIONPARM MODE PORTBASE PERROR +local ISUDPCAST RECEIVERTIMEOUT PARM SESSION SESSIONPARM MODE PORTBASE PERROR local METHOD ADDRESS BITRATE NCLIENTS MAXTIME CERROR -local TOOL LEVEL DEVICE MBUFFER SYNTAXSERVER SYNTAXCLIENT +local TOOL LEVEL DEVICE MBUFFER SYNTAXSERVER SYNTAXCLIENT # Si se solicita, mostrar ayuda. if [ "$*" == "help" -o "$2" == "help" ]; then @@ -359,6 +365,12 @@ PERROR=0 ISUDPCAST=$(udp-receiver --help 2>&1) echo $ISUDPCAST | grep start-timeout > /dev/null || ogRaiseError $OG_ERR_NOTEXEC "upd-cast no existe o version antigua -requerida 2009-"|| return $? +# Si la version de udp-receiver permite --receive-timeout utilizamos la opción +if echo $ISUDPCAST | grep receive-timeout &>/dev/null; then + RECEIVERTIMEOUT=" --receive-timeout $MCASTWAIT" +else + RECEIVERTIMEOUT="" +fi # Error si no se reciben $PARM parámetros. echo "$1" | grep "PARTITION" > /dev/null && PARM=5 || PARM=3 @@ -425,8 +437,51 @@ which mbuffer > /dev/null && MBUFFER=" --pipe 'mbuffer -q -m 20M' " # Generamos la instrucción base de multicast -Envio,Recepcion- SYNTAXSERVER="udp-sender $MBUFFER --nokbd --portbase $PORTBASE --$METHOD --mcast-data-address $ADDRESS --fec $CERROR --max-bitrate $BITRATE --ttl 16 --min-clients $NCLIENTS --max-wait $MAXTIME --autostart $MAXTIME --log /tmp/mcast.log" -SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE " +#SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE " + +# Deteccion automatica de la subred del cliente para anadir la IP del repositorio a la orden udp-receiver en el caso de encontrarse en distinta subred del repo +REPOIP="$(ogGetRepoIp)" +CLIENTIP=$(ip -o address show up | awk '$2!~/lo/ {if ($3~/inet$/) {printf ("%s ", $4)}}') +MASCARA=`echo $CLIENTIP | cut -f2 -d/` +CLIENTIP=`echo $CLIENTIP | cut -f1 -d/` +RIPBT="" +IPBT="" +for (( i = 1 ; i < 5 ; i++ )) +do + RIP=`echo $REPOIP | cut -f$i -d.` + RIP=`echo "$[$RIP + 256]"` + RIPB="" + while [ $RIP -gt 0 ] + do + let COCIENTE=$RIP/2 + let RESTO=$RIP%2 + RIPB=$RESTO$RIPB + RIP=$COCIENTE + done + RIPB=`echo "$RIPB" | cut -c2-` + RIPBT=$RIPBT$RIPB + IP=`echo $CLIENTIP | cut -f$i -d.` + IP=`echo "$[$IP + 256]"` + IPB="" + while [ $IP -gt 0 ] + do + let COCIENTE=$IP/2 + let RESTO=$IP%2 + IPB=$RESTO$IPB + IP=$COCIENTE + done + IPB=`echo "$IPB" | cut -c2-` + IPBT=$IPBT$IPB +done +MCASTWAIT=${MCASTWAIT:-120} +REPOSUBRED=`echo $RIPBT | cut -c1-$MASCARA` +CLIENTSUBRED=`echo $IPBT | cut -c1-$MASCARA` +if [ $REPOSUBRED == $CLIENTSUBRED ]; then + SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE $RECEIVERTIMEOUT --start-timeout $MCASTWAIT" +else + SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE --mcast-rdv-address $REPOIP $RECEIVERTIMEOUT --start-timeout $MCASTWAIT" +fi case "$1" in SENDPARTITION) @@ -598,7 +653,7 @@ then return $RETVAL else echo $COMMAND - eval $COMMAND || ogRaiseError $OG_ERR_MCASTRECEIVERFILE " "; return $? + eval $COMMAND || ogRaiseError $OG_ERR_MCASTRECEIVERFILE "$TARGETFILE"; return $? #[ -s "$LOGFILE" ] || return 21 fi } @@ -719,14 +774,29 @@ fi #@version 1.0.5 #@author Antonio Doblas Viso, Universidad de Málaga #@date 2012/05/29 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 +#@version 1.1 - Unidades organizativas con directorio de imágenes separado. (ticket #678) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/06/23 #*/ ## function ogMcastRequest { # Variables locales -local FILE PROTOOPT PORT PORTAUX REPOIP REPOPORTAUX REPEAT -FILE="$1" +local FILE PROTOOPT PORT PORTAUX REPOIP REPOPORTAUX REPEAT OGUNIT + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME path_filename str_mcastoptions" + return +fi +# Error si no se reciben 2 parámetros. +[ "$#" == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? + +OGUNIT="$(df|awk '/ogimages/ {print $1}'|cut -d/ -f5)/" +FILE="$OGUNIT$1" PROTOOPT="$2" -#TODO AYUDA #TODO: CONTROL PARAMETROS PORT=$(echo $2 | cut -f1 -d":") @@ -736,12 +806,12 @@ REPOPORTAUX=2009 REPEAT=0 until nmap -n -sU -p $PORTAUX $REPOIP | grep open do - echo "$MSG_SCRIPTS_TASK_START : hose $REPOIP $REPOPORTAUX --out sh -c "echo -ne START_MULTICAST $1 $2"" + let REPEAT=$REPEAT+1 + [ "$REPEAT" -lt 6 ] || ogRaiseError session log $OG_ERR_PROTOCOLJOINMASTER "MULTICAST \"$FILE\" \"$PROTOOPT\" $FILELIST" || return $? + echo "$MSG_SCRIPTS_TASK_START : hose $REPOIP $REPOPORTAUX --out sh -c "echo -ne START_MULTICAST $FILE $2"" #update-cache: hose $REPOIP $REPOPORTAUX --out sh -c "echo -ne START_MULTICAST "$FILE" "$PROTOOPT"" #multicas-direct: hose $REPOIP 2009 --out sh -c "echo -ne START_MULTICAST /$IMAGE.img $OPTPROTOCOLO" - let REPEAT=$REPEAT+1 - [ "$REPEAT" -eq 5 ] && return sleep 10 done } @@ -1020,23 +1090,23 @@ ogFindCache &>/dev/null || return $(ogRaiseError $OG_ERR_NOTCACHE; echo $?) [ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG str_repo relative_path_image [protocol|FULL]"; echo $?) ogCheckStringInGroup "$1" "REPO repo" || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?) -FILESOURCE=`ogGetPath $1 $2` || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?) +FILESOURCE=`ogGetPath $1 $2` +[ -n "$FILESOURCE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?) #echo "paso 1. si no existe la imagen, confirmar que es necesario actualizar la cache." FILETARGET=`ogGetPath CACHE $2` -if [ -z $FILETARGET ] +if [ -z "$FILETARGET" ] then # borramos el fichero bf del torrent, en el caso de que se hubiese quedado de algun proceso fallido - ogGetPath CACHE "/$2.torrent.bf" && ogDeleteFile CACHE "/$2.torrent.bf" &> /dev/null - ogGetPath CACHE "/$2.sum" && ogDeleteFile CACHE "/$2.sum" &> /dev/null - ogGetPath CACHE "/$2.full.sum" && ogDeleteFile CACHE "/$2.full.sum" &> /dev/null + [ -n "$(ogGetPath CACHE "/$2.torrent.bf")" ] && ogDeleteFile CACHE "/$2.torrent.bf" &> /dev/null + [ -n "$(ogGetPath CACHE "/$2.sum")" ] && ogDeleteFile CACHE "/$2.sum" &> /dev/null + [ -n "$(ogGetPath CACHE "/$2.full.sum")" ] && ogDeleteFile CACHE "/$2.full.sum" &> /dev/null echo "TRUE(0), es necesario actualizar. Paso 1, la cache no contiene esa imagen " return 0 fi #echo "Paso 2. Comprobamos que la imagen no estuviese en un proceso previo torrent" -if ogGetPath $FILETARGET.torrent.bf > /dev/null -then +if [ -n "$(ogGetPath "$FILETARGET.torrent.bf")" ]; then #TODO: comprobar los md5 del fichero .torrent para asegurarnos que la imagen a descarga es la misma. echo "TRUE(0), es necesario actualizar. Paso 2, la imagen esta en un estado de descarga torrent interrumpido" return 0 diff --git a/client/engine/README.es.txt b/client/engine/README.es.txt index c2b90b4b..531900af 100644 --- a/client/engine/README.es.txt +++ b/client/engine/README.es.txt @@ -1,9 +1,9 @@ -OpenGnSys Client Cloning Engine README +OpenGnsys Client Cloning Engine README ======================================= En este directorio se incluirán las funciones del motor de -clonación de OpenGnSys y la documentación asociada. +clonación de OpenGnsys y la documentación asociada. Este directorio estará localizado en el directorio del servidor /opt/opengnsys/client/lib/engine/bin @@ -11,7 +11,7 @@ Este directorio estará localizado en el directorio del servidor Las funciones serán accesibles por el cliente en el directorio /opt/opengnsys/lib/engine/bin -OpenGnSys Client Cloning Engine se distribuye en un conjunto de +OpenGnsys Client Cloning Engine se distribuye en un conjunto de librerías que incluyen funciones BASH que deben ser exportadas al entorno del cliente. @@ -32,5 +32,7 @@ Librerías: - Protocol.lib funciones de implementación de protocolos de comunicaciones. - Registry.lib funciones de gestión del registro de Windows. +- Rsync.lib funciones de sincronización de ficheros. +- String.lib funciones de control de cadena. - System.lib funciones básicas del sistema. diff --git a/client/engine/Registry.lib b/client/engine/Registry.lib index a46404d0..dbe69aee 100755 --- a/client/engine/Registry.lib +++ b/client/engine/Registry.lib @@ -4,7 +4,7 @@ #@brief Librería o clase Registry #@class Boot #@brief Funciones para gestión del registro de Windows. -#@version 1.0.5 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ @@ -202,41 +202,43 @@ EOT #/** -# ogGetHivePath path_mountpoint str_hive +# ogGetHivePath path_mountpoint [str_hive|str_user] #@brief Función básica que devuelve el camino del fichero con una sección del registro. #@param path_mountpoint directorio donde está montado el sistema Windows #@param str_hive sección del registro #@return str_path - camino del fichero de registro #@exception OG_ERR_FORMAT Formato incorrecto. #@exception OG_ERR_NOTFOUND Fichero de registro no encontrado. -#@note hive = { DEFAULT, SAM, SECURITY, SOFTWARE, SYSTEM, COMPONENTS } +#@note hive = { DEFAULT, SAM, SECURITY, SOFTWARE, SYSTEM, COMPONENTS, NombreDeUsuario } #@warning El sistema de archivos de Windows debe estar montada previamente. #@version 1.0.1 - Nueva función #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2011-05-18 +#@version 1.1.0 - Soportar registro de un usuario local. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2015-10-14 #*/ ## function ogGetHivePath () { # Variables locales. -local FILE FILENT FILEXP +local FILE HIVE # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" "$FUNCNAME path_mountpoint str_hive" \ - "$FUNCNAME /mnt/sda1 SOFTWARE => /mnt/sda1/WINDOWS/System32/config/SOFTWARE" + ogHelp "$FUNCNAME" "$FUNCNAME path_mountpoint [str_hive|str_user]" \ + "$FUNCNAME /mnt/sda1 SOFTWARE => /mnt/sda1/WINDOWS/System32/config/SOFTWARE" \ + "$FUNCNAME /mnt/sda1 user1 => /mnt/sda1/Users/user1/NTUSER.DAT" return fi # Error si no se reciben 2 parámetros. [ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $? -# Camino del fichero de registro en NT/2000 o en XP y posteriores. -FILENT=$(ogGetPath "/$1/winnt/system32/config/$2") -[ -f "$FILENT" ] && FILE="$FILENT" -FILEXP=$(ogGetPath "/$1/windows/system32/config/$2") -[ -f "$FILEXP" ] && FILE="$FILEXP" -[ -f "$FILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $? - -echo "$FILE" +# Camino del fichero de registro de usuario o de sistema (de menor a mayor prioridad). +FILE="$(ogGetPath "/$1/Windows/System32/config/$2")" +[ -z "$FILE" ] && FILE="$(ogGetPath "/$1/Users/$2/NTUSER.DAT")" +[ -z "$FILE" ] && FILE="$(ogGetPath "/$1/winnt/system32/config/$2")" +[ -z "$FILE" ] && FILE="$(ogGetPath "/$1/Documents and Settings/$2/NTUSER.DAT")" +[ -f "$FILE" ] && echo "$FILE" || ogRaiseError $OG_ERR_NOTFOUND "$1 $2" || return $? } @@ -255,6 +257,9 @@ echo "$FILE" #@version 0.9 - Adaptación para OpenGNSys. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2009-09-11 +#@version 1.1.0 - Soportar tipos BINARY (parejas hexadecimales separadas por espacio). +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2015-09-28 #*/ ## function ogGetRegistryValue () { @@ -274,7 +279,12 @@ FILE=$(ogGetHivePath "$1" "$2") || return $? # Devolver el dato del valor de registro. # /* (comentario Doxygen) -chntpw "$FILE" << EOT 2> /dev/null | awk '/> Value/ {getline;print $0;}' +chntpw "$FILE" << EOT 2> /dev/null | awk '/> Value/ {if (index($0, "REG_BINARY") > 0) + {data=""} + else + {getline; data=$0;} } + /^:[0-9A-F]+ / {data=data""substr($0, 9, 48);} + END {print data;}' cd ${3%\\*} cat ${3##*\\} q @@ -380,16 +390,21 @@ EOT #@version 0.9 - Adaptación para OpenGNSys. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2009-09-24 +#@version 1.1.0 - Soportar tipos BINARY (parejas hexadecimales separadas por espacio). +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2015-09-28 #*/ ## function ogSetRegistryValue () { # Variables locales. -local FILE +local FILE i n tmpfile # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then ogHelp "$FUNCNAME" "$FUNCNAME path_mountpoint str_hive str_valuename str_data" \ - "$FUNCNAME /mnt/sda1 SOFTWARE '\Microsoft\NewKey\Value1' 1" + "$FUNCNAME /mnt/sda1 SOFTWARE '\Key\SubKey\StringValue' \"Abcde Fghij\"" \ + "$FUNCNAME /mnt/sda1 SOFTWARE '\Key\SubKey\DwordValue' 1" \ + "$FUNCNAME /mnt/sda1 SOFTWARE '\Key\SubKey\BinaryValue' \"04 08 0C 10\"" return fi # Error si no se reciben 4 parámetros. @@ -397,13 +412,44 @@ fi # Camino del fichero de registro. FILE=$(ogGetHivePath "$1" "$2") || return $? -# Cambiar el dato del valor de registro. -chntpw "$FILE" << EOT &> /dev/null +# Fichero temporal para componer la entrada al comando "chntpw". +tmpfile=/tmp/chntpw$$ +trap "rm -f $tmpfile" 1 2 3 9 15 + +# Comprobar tipo de datos del valor del registro. +cat << EOT >$tmpfile +ls ${3%\\*} +q +EOT +if [ -n "$(chntpw "$FILE" < $tmpfile 2> /dev/null | grep "BINARY.*<${3##*\\}>")" ]; then + # Procesar tipo binario (incluir nº de bytes y líneas de 16 parejas hexadecimales). + [[ "$4 " =~ ^([0-9A-F]{2} )*$ ]] || ogRaiseError $OG_ERR_FORMAT "\"$4\"" || return $? + let n=${#4}+1 + cat << EOT >$tmpfile +cd ${3%\\*} +ed ${3##*\\} +$[n/3] +EOT + # Formato de líneas hexadecimales: :OFFSET XX YY ZZ ... (hasta 16 parejas). + for (( i=0; i> $tmpfile + done + echo -e "s\nq\ny" >> $tmpfile +else + # Cambiar el dato del valor de registro para cadenas y bytes. + cat << EOT >$tmpfile cd ${3%\\*} ed ${3##*\\} $4 q y EOT + +fi + +# Aplicar cambios. +chntpw "$FILE" < $tmpfile &> /dev/null +rm -f $tmpfile } + diff --git a/client/engine/Rsync.lib b/client/engine/Rsync.lib index a2889dac..d123232a 100755 --- a/client/engine/Rsync.lib +++ b/client/engine/Rsync.lib @@ -30,8 +30,8 @@ function ogCreateFileImage () { local SIZEREQUIRED IMGDIR IMGFILE DIRMOUNT LOOPDEVICE IMGSIZE IMGEXT KERNELVERSION if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME" : "$MSG_HELP_ogCreateFileImage" \ - "$FUNCNAME [ REPO|CACHE ] image_name extension size(K)" \ + ogHelp "$FUNCNAME" \ + "$FUNCNAME [ REPO|CACHE ] image_name extension size(K)" \ "$FUNCNAME REPO Ubuntu12 img 300000" \ "$FUNCNAME CACHE Windows7 diff 20000000" return @@ -127,7 +127,7 @@ fi } -function ogCreateInfoImage () { + #/** # ogCreateInfoImage #@brief Crear listados con la informacion de la imagen, los situa en /tmp. @@ -138,14 +138,15 @@ function ogCreateInfoImage () { #@param 5 Tipo imagen [ img | diff ] #@version 1.0.6 rsync opcion W (whole) para que sea más rápido #*/ +function ogCreateInfoImage () { local IMGTYPE IMGDIRAUX DIRMOUNT DESTRSYNC PASSWORD USERRSYNC ORIG FSTYPE PART DIREMPTY IMGLIST IMGINFO IMGACL KERNELVERSION # Ayuda o menos de 5 parametros y la imagen no es basica if [ "$*" == "help" -o $# -lt 5 -a "$3" != "img" ]; then - ogHelp "$FUNCNAME" : "$MSG_HELP_ogCreateInfoImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME num_disk num_part [ REPO|CACHE ] [ base_image_name ] extension " \ "base image -> $FUNCNAME 1 2 img" \ "diff image -> $FUNCNAME 1 1 CACHE Windows7 diff " - return + return fi if [ $# -lt 3 ]; then @@ -237,7 +238,6 @@ if [ $FSTYPE == "NTFS" ]; then ntfs-3g.secaudit -b $PART / > $IMGACL fi - } @@ -252,9 +252,8 @@ local IMGACL IMGINFO FILES ACLTMP # Ayuda if [ "$*" == "help" ]; then - ogHelp "$MSG_HELP_ogAclFilter" \ - "$FUNCNAME [ no parameters ] " - return + ogHelp "$FUNCNAME" "$FUNCNAME" + return fi IMGACL="/tmp/ogimg.acl" @@ -284,9 +283,9 @@ done < $FILES cp $ACLTMP $IMGACL rm -f $FILES $ACLTMP $ACLFILES - } + #/** # ogRestoreInfoImage #@brief Crear o modificar enlaces y restaurar las ACL. La informacion esta ya copiada a la particion. @@ -298,11 +297,11 @@ local DEST PART IMGACL IMGLN OPTLN LINEA DESTLN ORIGLN TYPELN # Ayuda o menos de 5 parametros y la imagen no es basica if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogRestoreInfoImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME num_disk num_part" \ "base image -> $FUNCNAME 1 2 " \ "diff image -> $FUNCNAME 1 1 " - return + return fi if [ $# -lt 2 ]; then @@ -352,6 +351,8 @@ if [ $(wc -l "/tmp/$IMGLN"|cut -f1 -d" ") -ne 0 ]; then fi cd / } + + #/** # ogRestoreAclImage #@brief Restaurar las ACL. La informacion esta ya copiada al directorio /tmp @@ -360,6 +361,14 @@ cd / #*/ function ogRestoreAclImage () { local PART IMGACL + +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" \ + "$FUNCNAME num_disk num_part" \ + "$FUNCNAME 1 1" + return +fi + PART=$(ogDiskToDev "$1" "$2") || return $? IMGACL="ogimg.acl" @@ -372,9 +381,9 @@ if [ "$(ogGetFsType $1 $2)" == "NTFS" -a -f "/tmp/$IMGACL" ] ; then # Para evitar que de falso error echo "" fi - } + function ogSyncCreate () { #/** # ogSyncCreate @@ -391,11 +400,11 @@ local ORIG DIRAUX DIRMOUNT DESTRSYNC USERRSYNC PASSWORD OPTRSYNC RETVAL echo "" >$OGLOGCOMMAND; if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogSyncCreate" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME num_disk num_part [ REPO|CACHE ] image_name extension " \ "$FUNCNAME 1 2 REPO Ubuntu12 img" \ "$FUNCNAME 1 1 CACHE Windows7 diff " - return + return fi @@ -453,11 +462,11 @@ local DIRMOUNT ORIG DESTRSYNC PASSWORD OPTRSYNC USERRSYNC IMGINFO FILESFROM echo "" >$OGLOGCOMMAND; if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogSyncRestore" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME [ REPO|CACHE ] image_name extension num_disk num_part " \ "$FUNCNAME REPO Ubuntu12 img 1 2" \ "$FUNCNAME CACHE Windows7 diff 1 1" - return + return fi @@ -517,10 +526,9 @@ rsync -aHAX$OPTRSYNC $PASSWORD --progress $FILESFROM "$ORIG/" "$DESTRSYNC" 2> RETVAL=${PIPESTATUS[0]} cd / return $RETVAL - } -function ogMountImage () { + #/** # ogMountImage #@brief Monta la imagen para sincronizar. @@ -529,14 +537,15 @@ function ogMountImage () { #@param 3 Tipo imagen [ img |diff ] #@return punto de montaje #*/ +function ogMountImage () { local IMGEXT IMGFILE DIRMOUNT KERNELVERSION if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogMountImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME [ REPO|CACHE ] image_name [ extension ]" \ "$FUNCNAME REPO Ubuntu12" \ "$FUNCNAME CACHE Windows7 diff" - return + return fi @@ -577,10 +586,6 @@ fi } - - - -function ogUnmountImage () { #/** # ogUnmountImage [ REPO | CACHE ] Image_name [ extension ] #@brief Desmonta la imagen para sincronizar. @@ -588,10 +593,11 @@ function ogUnmountImage () { #@param 2 Nombre Imagen #@param 3 Tipo imagen [ img |diff ] #*/ +function ogUnmountImage () { local IMGTYPE DIRMOUNT if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogUnmountImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME [ REPO|CACHE ] image_name [ extension ]" \ "$FUNCNAME REPO Ubuntu12" \ "$FUNCNAME CACHE Windows7 diff" @@ -615,19 +621,19 @@ else echo " hose $REPOIP 2009 --out sh -c echo -ne UMOUNT_IMAGE \"$2\" $IMGTYPE" hose $REPOIP 2009 --out sh -c "echo -ne UMOUNT_IMAGE \"$2\" $IMGTYPE" fi - } -function ogGetMountImageDir () { + #/** # ogGetMountImageDir #@brief Devuelve el directorio de montaje de la imagen. #@param 1 Nombre Imagen #@param 2 Tipo imagen [ img |diff ] #*/ +function ogGetMountImageDir () { local DIRMOUNT if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogGetMountImageDir" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME image_name [ extension ]" \ "$FUNCNAME Ubuntu12" \ "$FUNCNAME Windows7 diff" @@ -645,7 +651,6 @@ DIRMOUNT="mount/$1" [ "$2" == "diff" ] && DIRMOUNT="$DIRMOUNT.diff" echo "$DIRMOUNT" - } @@ -666,11 +671,11 @@ TIME=$SECONDS # Ayuda o menos de 5 parametros y la imagen no es basica if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogWaitMountImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME [ REPO | CACHE ] image_name extension state [ image_size ] " \ "$FUNCNAME REPO Ubuntu12 img 30000000" \ "$FUNCNAME CACHE Windows7 diff " - return + return fi if [ $# -lt 4 ]; then @@ -713,7 +718,6 @@ echo "" | tee -a $OGLOGSESSION $OGLOGFILE } -function ogReduceImage () { #/** # ogReduceImage #@brief Reduce el archivo de la imagen a tamaño datos + 500M @@ -724,9 +728,10 @@ function ogReduceImage () { #@exception OG_ERR_FORMAT # 1 formato incorrecto. #@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado. #*/ +function ogReduceImage () { local IMGEXT DIRMOUNT AVAILABLE USED IMGDIR IMGFILE ENDSIZE LOOPDEVICE if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogReduceImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME [ REPO|CACHE ] image_name [ extension ]" \ "$FUNCNAME REPO Ubuntu12" \ "$FUNCNAME CACHE Windows7 diff" @@ -795,12 +800,10 @@ else hose $REPOIP 2009 --out sh -c "echo -ne REDUCE_IMAGE \"$2\" ${IMGEXT#*\.}" fi - } -function ogIsSyncImage () { #/** # ogIsSyncImage #@brief Comprueba si la imagen es sincronizable @@ -811,10 +814,11 @@ function ogIsSyncImage () { #@exception OG_ERR_FORMAT # 1 formato incorrecto. #@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado. #*/ +function ogIsSyncImage () { local IMGEXT IMGDIR IMGFILE if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogIsSyncImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME [ REPO|CACHE ] image_name [ extension ]" \ "$FUNCNAME REPO Ubuntu12" \ "$FUNCNAME CACHE Windows7 diff" @@ -833,9 +837,9 @@ IMGFILE="${IMGDIR}"/$(basename "/$2").$IMGEXT file "$IMGFILE" | grep -i -e " BTRFS Filesystem " -e " ext4 filesystem " >/dev/null [ $? -eq 0 ] && return 0 || return $OG_ERR_DONTSYNC_IMAGE - } + #/** # ogCheckSyncImage #@brief Muestra el contenido de la imagen para comprobarla. @@ -850,7 +854,7 @@ function ogCheckSyncImage () { local IMGEXT IMGDIR IMGFILE DIRMOUNT ISMOUNT RETVAL KERNELVERSION if [ "$*" == "help" ]; then - ogHelp "$FUNCNAME": "$MSG_HELP_ogCheckSyncImage" \ + ogHelp "$FUNCNAME" \ "$FUNCNAME [ REPO|CACHE ] image_name [ extension ]" \ "$FUNCNAME REPO Ubuntu12" \ "$FUNCNAME CACHE Windows7 diff" @@ -892,3 +896,4 @@ umount "$DIRMOUNT" rmdir "$DIRMOUNT" return $RETVAL } + diff --git a/client/engine/System.lib b/client/engine/System.lib index cbadd952..d016be13 100755 --- a/client/engine/System.lib +++ b/client/engine/System.lib @@ -4,7 +4,7 @@ #@brief Librería o clase System #@class System #@brief Funciones básicas del sistema. -#@version 1.0.6 +#@version 1.1.0 #@warning License: GNU GPLv3+ #*/ @@ -17,6 +17,7 @@ #@param str_message mensaje (puede recibir más de 1 parámetro. #@return Mensaje mostrado. #@warning Si no se indica nivel de registro, solo muestra mensaje en pantalla. +#@warning Si DEBUG="no", no se registran mensajes de error. #@note logfile = { log, command, session }; usa "log" si se indica nivel de registro. #@note loglevel = { help, info, warning, error } #@note El nivel de ayuda \c (help) no se registra en el fichero de incidencias. @@ -26,6 +27,9 @@ #@version 1.0.5 - Elegir fichero de log. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2014-03-17 +#@version 1.1.0 - Posibilidad de no registrar mensajes en ficheros. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2015-11-10 #*/ function ogEcho () { @@ -53,7 +57,9 @@ esac if [ -n "$LOGLEVEL" ]; then DATETIME=$(date +"%F %T") - logger -s -t "OpenGnSys $LOGLEVEL" "$DATETIME $*" 2>&1 | tee -a $OGLOGFILE $LOGS + # Registrar mensajes en fichero de log si la depuración no está desactivada. + [ "${DEBUG,,}" != "no" ] && LOGS="$OGLOGFILE $LOGS" + logger -s -t "OpenGnsys $LOGLEVEL" "$DATETIME $*" 2>&1 | tee -a $LOGS else echo "$*" | tee -a $LOGS fi @@ -124,8 +130,9 @@ return ${PIPESTATUS[0]} function ogGetCaller () { # Obtener el nombre del programa o del script que ha llamado al proceso actual. -basename "$(ps hlp $PPID | awk '{if ($13~/bash/ && $14!="") print $14; - else { sub(/^-/,"",$13); print $13; } }')" +basename "$(COLUMNS=200 ps hp $PPID -o args | \ + awk '{if ($1~/bash/ && $2!="") { print $2; } + else { sub(/^-/,"",$1); print $1; } }')" } @@ -183,6 +190,12 @@ function ogRaiseError () { # Variables locales local CONT=1 LOGS MSG CODE FUNCS +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME [str_logfile ...] int_errorcode str_errormessage" + return +fi + # Selección de rgistros de incidencias. while [ $CONT ]; do case "${1,,}" in @@ -201,6 +214,7 @@ case "$CODE" in $OG_ERR_LOCKED) MSG="$MSG_ERR_LOCKED \"$2\"" ;; $OG_ERR_CACHE) MSG="$MSG_ERR_CACHE \"$2\"" ;; $OG_ERR_NOGPT) MSG="$MSG_ERR_NOGPT \"$2\"" ;; + $OG_ERR_REPO) MSG="$MSG_ERR_REPO \"$2\"" ;; $OG_ERR_FILESYS) MSG="$MSG_ERR_FILESYS \"$2\"" ;; $OG_ERR_IMAGE) MSG="$MSG_ERR_IMAGE \"$2\"" ;; $OG_ERR_NOTOS) MSG="$MSG_ERR_NOTOS \"$2\"" ;; @@ -236,8 +250,10 @@ esac FUNCS="${FUNCNAME[@]:1}" FUNCS="${FUNCS/main/$(basename $0 2>/dev/null)}" -# Mostrar mensaje de error y salir con el código indicado. -ogEcho $LOGS error "${FUNCS// /<-}: $MSG" >&2 +# Mostrar mensaje de error si es función depurable y salir con el código indicado. +if [ $CODE == $OG_ERR_FORMAT ] || ogCheckStringInGroup "$FUNCS" "$NODEBUGFUNCTIONS" || ! ogCheckStringInGroup "${FUNCS%% *}" "$NODEBUGFUNCTIONS"; then + ogEcho $LOGS error "${FUNCS// /<-}: $MSG" >&2 +fi return $CODE } @@ -259,6 +275,12 @@ function ogIsRepoLocked () # Variables locales. local f FILES +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME" "if $FUNCNAME; then ...; fi" + return +fi + # No hacer nada, si no está definido el punto de montaje del repositorio. [ -z "$OGIMG" ] && return 1 @@ -300,3 +322,14 @@ else fi } + + +#### PRUEBA +function ogIsVirtualMachine() { +case "$(dmidecode -s system-product-name)" in + KVM|VirtualBox) + return 1 ;; + *) return 0 ;; +esac +} + diff --git a/client/shared/README.es.txt b/client/shared/README.es.txt index 57dc7f85..fbc03c42 100644 --- a/client/shared/README.es.txt +++ b/client/shared/README.es.txt @@ -3,7 +3,7 @@ OpenGsSys Client README Este directorio contiene la estructura principal de datos que será -importada por los cleintes OpenGnSys mediante Samba (o NFS en las +importada por los cleintes OpenGnsys mediante Samba (o NFS en las primeras versiones del Proyecto). Los subdirectorios se copian íntegramente al servidor bajo @@ -18,10 +18,12 @@ La estructura de datos es la siguiente: - etc ficheros de configuración del cliente. - lib librerías de funciones. - engine/bin ficheros con las funciones del motor de clonación. + - httpd ficheros de configuración del servicio lighttpd. - modules módulos extra para el Kernel del cliente. - - ogclient clientes para instalar en sistemas operativos. + - qtlib librerías Qt complementarias del Browser. + - qtplugins plugins Qt para el Browser. - images repositorio de imágenes de sistemas operativos. - log registro de incidencias de los clientes. -- scripts funciones de alto nivel ejecutables por OpenGnSys Browser - y OpenGnSys Admin. +- scripts funciones de alto nivel ejecutables por OpenGnsys Browser + y OpenGnsys Admin. diff --git a/client/shared/bin/browser b/client/shared/bin/browser index 56fca2f0..4370974f 100755 Binary files a/client/shared/bin/browser and b/client/shared/bin/browser differ diff --git a/client/shared/bin/grub-probe1.99 b/client/shared/bin/grub-probe1.99 deleted file mode 100755 index 21659ef2..00000000 Binary files a/client/shared/bin/grub-probe1.99 and /dev/null differ diff --git a/client/shared/bin/grub-probe1.99_i686 b/client/shared/bin/grub-probe1.99_i686 new file mode 100755 index 00000000..21659ef2 Binary files /dev/null and b/client/shared/bin/grub-probe1.99_i686 differ diff --git a/client/shared/bin/grub-probe1.99_x86_64 b/client/shared/bin/grub-probe1.99_x86_64 new file mode 100755 index 00000000..b62e88ff Binary files /dev/null and b/client/shared/bin/grub-probe1.99_x86_64 differ diff --git a/client/shared/bin/poweroffconf b/client/shared/bin/poweroffconf index 188f4409..02038605 100755 --- a/client/shared/bin/poweroffconf +++ b/client/shared/bin/poweroffconf @@ -15,8 +15,8 @@ # Variables generales. -OPENGNSYS=${OPENGNSYS:-/opt/opengnsys} # Instalación de OpenGnSys -OGETC=${OGETC:-$OPENGNSYS/etc} # Configuración de OpenGnSys +OPENGNSYS=${OPENGNSYS:-/opt/opengnsys} # Instalación de OpenGnsys +OGETC=${OGETC:-$OPENGNSYS/etc} # Configuración de OpenGnsys POWEROFFCONF=/etc/poweroff.conf # Configuración del script # Error si no existe el fichero de configuración de ahorro de energía. @@ -26,6 +26,7 @@ if [ ! -f $POWEROFFCONF ]; then fi # Obtener parámetros de configuración de ahorro de energía. source $POWEROFFCONF +export TZ case $# in 0) # Sin parámetros, comprobar que existe la variable POWEROFFSLEEP. diff --git a/client/shared/etc/engine.cfg b/client/shared/etc/engine.cfg index 895881be..7bb74d48 100644 --- a/client/shared/etc/engine.cfg +++ b/client/shared/etc/engine.cfg @@ -1,4 +1,5 @@ ## Definicion general +set -a OGENGINECONFIGURATE="TRUE" OGLOGSESSION="/tmp/session.log" OGLOGCOMMAND="/tmp/command.log" @@ -23,6 +24,9 @@ IMGREDUCE="TRUE" #Al enviar particion reducir el sistema de archivos previamente. OGWINREDUCE=TRUE +# MULTICAST: timeout si la transferencia no comienza o se interrumpe. +MCASTWAIT=30 + # Imagenes sincronizadas # Factor para calcular el time-out al crear la imagen. 100000k -> 4s CREATESPEED=100000*4 @@ -36,5 +40,14 @@ IMGFS=EXT4 # Tiempo de sleep antes de realizar el reboot OGSLEEP="20" -# Indica si se instala automáticamente el cliente OpenGnSys en el despliegue de un SO (por defecto, no instalar). -INSTALLOSCLIENT=FALSE +# La variable INSTALLOSCLIENT no se utiliza en OpenGnsys 1.1.0. + +# Funciones que no deben mostrar salida de avisos si son llamadas por otras funciones. +NODEBUGFUNCTIONS="ogCreateImageSyntax ogGetHivePath ogGetOsType ogRestoreImageSyntax ogUnmountAll ogUnmountCache" + +# Velocidad de comunicación por defecto (muestra aviso en Browser si no se cumple): +# "", no usar esta característica. +# "100Mb/s", Fast Ethernet. +# "1000Mb/s", Gigabit Ethernet. +DEFAULTSPEED="" + diff --git a/client/shared/etc/init/default.sh b/client/shared/etc/init/default.sh index e87b4b61..0e653e05 100755 --- a/client/shared/etc/init/default.sh +++ b/client/shared/etc/init/default.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Proceso general de arranque de OpenGnSys Client. +# Proceso general de arranque de OpenGnsys Client. # Fichero de registro de incidencias (en el servidor; si no, en local). @@ -13,15 +13,8 @@ LOGLEVEL=5 # Matando plymount para inicir browser o shell pkill -9 plymouthd -# Arranque de OpenGnSys Client daemon (web services). -if [ -x $OPENGNSYS/job_executer/init.d/job_executer ]; then - echo "Running Opengnsys client daemon (web services)" - $OPENGNSYS/job_executer/init.d/job_executer restart -fi - -# Arranque de OpenGnSys Client daemon (socket). +# Arranque de OpenGnsys Client daemon (socket). echo "${MSG_LAUNCHCLIENT:-.}" -[ "$ogactiveadmin" == "true" ] && boot="admin" # Indicar fichero de teclado de Qt para el idioma especificado (tipo "es.qmap"). [ -f /usr/local/etc/${LANG%_*}.qmap ] && export QWS_KEYBOARD="TTY:keymap=/usr/local/etc/${LANG%_*}.qmap" @@ -37,7 +30,7 @@ else fi # Si fallo en cliente y modo "admin", cargar shell; si no, salir. -if [ "$boot" == "admin" ]; then +if [ "$ogactiveadmin" == "true" ]; then bash fi diff --git a/client/shared/etc/lang.ca_ES.conf b/client/shared/etc/lang.ca_ES.conf index 24ca7798..a8a45b2d 100644 --- a/client/shared/etc/lang.ca_ES.conf +++ b/client/shared/etc/lang.ca_ES.conf @@ -9,6 +9,7 @@ MSG_ERR_PARTITION="Partición errónea o desconocida" MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo" MSG_ERR_CACHE="Error en partición de caché local" MSG_ERR_NOGPT="El disco indicado no contiene una particion GPT" +MSG_ERR_REPO="Error al montar el repositorio de imágenes" MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar" MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar" MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema" @@ -39,25 +40,29 @@ MSG_ERR_NOTDIFFERENT="No se detectan diferencias entre la imagen basica y la par MSG_ERR_SYNCHRONIZING="Error al sincronizar, puede afectar la creacion|restauracion de la imagen" # Mensajes de avisos. +MSG_DONTUSE="NO USAR" MSG_DONTMOUNT="Sistema de archivos no montado" MSG_DONTUNMOUNT="El sistema de archivos no se puede desmontar o no está montado" MSG_MOUNT="Sistema de archivos montado" +MSG_MOUNTREADONLY="Sistema de archivos montado solo de lectura" +MSG_OBSOLETE="EN DESUSO" # Mensajes complementarios para las ayudas. MSG_64BIT="64 bits" +MSG_DISK="disc" MSG_ERROR="Error" MSG_EXAMPLE="Exemple" MSG_FORMAT="Format" MSG_FUNCTION="Funció" -MSG_HARDWAREINVENTORY="Inventario de hardware de la máquina" +MSG_HARDWAREINVENTORY="Inventario de maquinari de la màquina" MSG_IMAGE="imatge" MSG_INSTALLED="instal-lat" -MSG_NOCACHE="sin caché local" +MSG_NOCACHE="sense caché local" MSG_NOEXTENDED="sense partició estensa" -MSG_NOFORMAT="sense format" MSG_PARTITION="partició" MSG_PROTOCOL="protocol" MSG_RESERVEDVALUE="Valor reservat" +MSG_SEE="Veure" MSG_UNKNOWN="Desconegut" MSG_WARNING="Avís" @@ -88,20 +93,44 @@ MSG_HELP_ogAclFilter="Extrae las acl de los ficheros de la diferencial" MSG_HELP_ogAddCmd="Añade comandos al fichero creado por la función ogInstalMiniSetup." MSG_HELP_ogAddRegistryKey="Añade una nueva clave al registro de Windows." MSG_HELP_ogAddRegistryValue="Añade un nuevo valor al registro de Windows." +MSG_HELP_ogAddToLaunchDaemon="" MSG_HELP_ogBoot="Arranca un sistema operativo instalado." +MSG_HELP_ogBootLoaderDeleteEntry="$MSG_DONTUSE." +MSG_HELP_ogBootLoaderHidePartitions="$MSG_DONTUSE." +MSG_HELP_ogBootMbrGeneric="" +MSG_HELP_ogBootMbrXP="" +MSG_HELP_ogBurgDefaultEntry="Configura la entrada por defecto de Burg." +MSG_HELP_ogBurgDeleteEntry="Borra en el Burg del MBR las entradas para el inicio en una particion." +MSG_HELP_ogBurgHidePartitions="Configura el Burg del MBR para que oculte las particiones de windows que no se esten iniciando." +MSG_HELP_ogBurgInstallMbr="Instal·la el carregador d'arrencada BURG al MBR del primer disc dur" +MSG_HELP_ogBurgOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de Burg." MSG_HELP_ogCalculateChecksum="Calcula la suma de comprobación (checksum) de un fichero." +MSG_HELP_ogCalculateFullChecksum="" +MSG_HELP_ogChangeRepo="Cambia el repositorio para el recurso remoto images." MSG_HELP_ogCheckFs="Comprueba la consistencia de un sistema de archivos." +MSG_HELP_ogCheckIpAddress="" +MSG_HELP_ogCheckProgram="" +MSG_HELP_ogCheckStringInGroup="" +MSG_HELP_ogCheckStringInReg="" MSG_HELP_ogCheckSyncImage="Muestra el contenido de la imagen para comprobarla." +MSG_HELP_ogCleanLinuxDevices="" MSG_HELP_ogCleanOs="Elimina los archivos que no son necesarios en el sistema operativo." MSG_HELP_ogCompareChecksumFiles="Compara si coinciden las sumas de comprobación almacenadas de 2 ficheros." +MSG_HELP_ogConfigureFstab="" +MSG_HELP_ogConfigureOgagent="Configura el nuevo agente OGAgent para sistemas ooperativos." MSG_HELP_ogCopyFile="Copia un fichero a otro almacenamiento." +MSG_HELP_ogCreateBootLoaderImage="" MSG_HELP_ogCreateCache="Reserva espacio para la partición de caché al final del disco 1." +MSG_HELP_ogCreateDiskImage="Genera una imagen exacta de un disco completo." MSG_HELP_ogCreateFileImage="Crea/Redimensiona el archivo de la imagen sincronizada" +MSG_HELP_ogCreateGptPartitions="" MSG_HELP_ogCreateImage="Genera una imagen exacta de un sistema operativo instalado localmente." +MSG_HELP_ogCreateImageSyntax="" MSG_HELP_ogCreateInfoImage="Crea informacion del contenido de la imagen" MSG_HELP_ogCreateMbrImage="Genera una imagen del sector de arranque (MBR)." MSG_HELP_ogCreatePartitions="Define la estructura de particiones de un disco." MSG_HELP_ogCreatePartitionTable="Genera una tabla de particiones en caso de que no sea valida." +MSG_HELP_ogCreateTorrent="" MSG_HELP_ogDeleteCache="Elimina la partición de caché local." MSG_HELP_ogDeleteFile="Borra un fichero de un espacio de almacenamiento." MSG_HELP_ogDeletePartitionTable="Elimina la tabla de particiones del disco" @@ -110,82 +139,119 @@ MSG_HELP_ogDeleteRegistryValue="Borra un valor del registro de Windows." MSG_HELP_ogDeleteTree="Borra un árbol de directorios de un espacio de almacenamiento." MSG_HELP_ogDevToDisk="Devuelve el nº de orden de disco o de partición correspondiente al camino del fichero de dispositivo." MSG_HELP_ogDiskToDev="Devuelve el camino del fichero de dispositivo correspondiente al nº de orden de disco o de partición." +MSG_HELP_ogDomainScript="" MSG_HELP_ogEcho="" +MSG_HELP_ogExecAndLog="" MSG_HELP_ogExtendFs="Extiende el tamaño de un sistema de archivo al máximo de su partición." MSG_HELP_ogFindCache="Indica la partición reservada para caché local." -MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos." +MSG_HELP_ogFixBootSector="" MSG_HELP_ogFormatCache="Formatea (inicia) el sistema de caché local." +MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos." MSG_HELP_ogFormatFs=$MSG_HELP_ogFormat MSG_HELP_ogGetArch="Devuelve el tipo de arquitectura del cliente." MSG_HELP_ogGetCacheSize="Devuelve el tamaño de la partición de caché local." MSG_HELP_ogGetCacheSpace="Devuelve el espacio máximo disponible que puede ser reservado para la partición de caché local." +MSG_HELP_ogGetCaller="" MSG_HELP_ogGetDiskSize="Devuelve el tamaño del disco." +MSG_HELP_ogGetDiskType="" +MSG_HELP_ogGetFreeSize="" MSG_HELP_ogGetFsSize="Devuelve el tamaño de un sistema de archivos." MSG_HELP_ogGetFsType="Devuelve el mnemónico de tipo de sistema de archivos." MSG_HELP_ogGetGroupDir="Devuelve el camino del directorio por defecto para el grupo del cliente." MSG_HELP_ogGetGroupName="Devuelve el nombre del grupo al que pertenece el cliente." MSG_HELP_ogGetHivePath="Devuelve el camino completo del fichero de una sección del registro de Windows." MSG_HELP_ogGetHostname="Devuelve el nombre de la máquina local." -MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente." +MSG_HELP_ogGetImageCompressor="Devuelve la herramienta de compresión de la imagen." +MSG_HELP_ogGetImageInfo="Muestra información sobre la imagen monolitica: clonacion:compresor:sistemaarchivos:tamañoKB." +MSG_HELP_ogGetImageProgram="Devuelve el programa usado para crear la imagen." MSG_HELP_ogGetImageSize="Devuelve el tamaño de una imagen de sistema." +MSG_HELP_ogGetImageType="Devuelve el sistema de ficheros de la imagen." +MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente." MSG_HELP_ogGetLastSector="Devuelve el último sector usable del disco o de una partición." MSG_HELP_ogGetMacAddress="Devuelve la dirección Ethernet del cliente." MSG_HELP_ogGetMountImageDir="Devuelve el directorio de montaje de una imagen." MSG_HELP_ogGetMountPoint="Devuelve el directorio donde está montado un sistema de archivos local." +MSG_HELP_ogGetNetInterface="" MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado." +MSG_HELP_ogGetOsUuid="" MSG_HELP_ogGetOsVersion="Devuelve el tipo y la versión de un sistema operativo instalado." -MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnSys." +MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnsys." MSG_HELP_ogGetPartitionActive="Indica cual es la partición marcada como activa en un disco." MSG_HELP_ogGetPartitionId="Devuelve el identificador de tipo de una partición." MSG_HELP_ogGetPartitionSize="Devuelve el tamaño de una partición." +MSG_HELP_ogGetPartitionsNumber="" MSG_HELP_ogGetPartitionTableType="Devuelve el tipo de tabla de particiones del disco" MSG_HELP_ogGetPartitionType="Devuelve el mnemónico de tipo de una partición." -MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnSys." +MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnsys." MSG_HELP_ogGetRegistryValue="Devuelve el dato de un valor del registro de Windows." MSG_HELP_ogGetRepoIp="Devuelve la dirección IP del repositorio de datos." +MSG_HELP_ogGetSerialNumber="Devuelve el número de serie del cliente." MSG_HELP_ogGetServerIp="Devuelve la dirección IP del servidor principal." MSG_HELP_ogGetSizeParameters="Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido." MSG_HELP_ogGetWindowsName="Devuelve el nombre del cliente guardado en el registro de Windows." -MSG_HELP_ogGrubAddOgclient="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubAddOgLive="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubDefaultEntry="Configura la entrada por defecto de GRUB." MSG_HELP_ogGrubDeleteEntry="Borra en el grub del MBR las entradas para el inicio en una particion." MSG_HELP_ogGrubHidePartitions="Configura el grub del MBR para que oculte las particiones de windows que no se esten iniciando." +MSG_HELP_ogGrubInstallMbr="Instal·la el carregador d'arrencada GRUB al MBR del primer disc dur" +MSG_HELP_ogGrubInstallPartition="Instal·la el carregador d'arrencada BURG al BootSector" +MSG_HELP_ogGrubOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de GRUB." MSG_HELP_ogHelp="Muestra mensajes de ayudas para las funciones." MSG_HELP_ogHidePartition="Oculta una partición de Windows." MSG_HELP_ogIdToType="Devuelve el mnemónico asociado al identificador de tipo de partición." -MSG_HELP_ogInstallLinuxClient="Instala el cliente OpenGnSys en un sistema operativo GNU/Linux." +MSG_HELP_ogInstallFirstBoot="Crea un archivo que se ejecutará en el primer arranque de Windows." +MSG_HELP_ogInstallLaunchDaemon="Instala un archivo que se ejecutará en el arranque de macOS." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." MSG_HELP_ogInstallMiniSetup="Instala un archivo que se ejecutará en el arranque de Windows." -MSG_HELP_ogInstallWindowsClient="Instala el cliente OpenGnSys en un sistema operativo Windows." +MSG_HELP_ogInstallRunonce="Crea un archivo que se ejecutará en el inicio de un usuario administrador de Windows." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." MSG_HELP_ogIsFormated="Comprueba si un sistema de archivos está formateado." MSG_HELP_ogIsImageLocked="Comprueba si una imagen está bloqueada por una operación de uso exclusivo." -MSG_HELP_ogIsLocked="Comprueba si una partición está bloqueada por una operación de uso exclusivo." +MSG_HELP_ogIsLocked="Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo." +MSG_HELP_ogIsDiskLocked="Comprueba si un disco está bloqueado por una operación de uso exclusivo." MSG_HELP_ogIsMounted="Comprueba si un sistema de archivos está montado." MSG_HELP_ogIsNewerFile="Comprueba si un fichero es más nuevo (se ha modificado después) que otro." MSG_HELP_ogIsPartitionLocked=$MSG_HELP_ogIsLocked +MSG_HELP_ogIsRepoLocked="" MSG_HELP_ogIsSyncImage="Comprueba si la imagen es sincronizable." -MSG_HELP_ogIsValidType="Comprueba si el tipo de sistema de archivos es válido para un identificador de partición." +MSG_HELP_ogIsVirtualMachine="" MSG_HELP_ogIsWritable="Comprueba si un sistema de archivos está montado con permiso de escritura." MSG_HELP_ogLinuxBootParameters="Devuelve los parámetros de arranque de un sistema operativo Linux instalado." MSG_HELP_ogListHardwareInfo="Lista el inventario de dispositivos del cliente." +MSG_HELP_ogListLogicalPartitions="" MSG_HELP_ogListPartitions="Lista la estructura de particiones de un disco." +MSG_HELP_ogListPrimaryPartitions="" MSG_HELP_ogListRegistryKeys="Lista los nombres de las subclaves incluidas en una clave del registro de Windows." MSG_HELP_ogListRegistryValues="Lista los nombres de los valores incluidos en una clave del registro de Windows." MSG_HELP_ogListSoftware="Lista el inventario de programas instalados en un sistema operativo." MSG_HELP_ogLock="Bloquea una partición para operación de uso exclusivo." +MSG_HELP_ogLockDisk="Bloquea un disco para operación de uso exclusivo." MSG_HELP_ogLockImage="Bloquea una imagen para operación de uso exclusivo." MSG_HELP_ogLockPartition=$MSG_HELP_ogLock MSG_HELP_ogMakeChecksumFile="Almacena la suma de comprobación de un fichero." -MSG_HELP_ogMakeDir="Crea un directorio para OpenGnSys." -MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje." +MSG_HELP_ogMakeDir="Crea un directorio para OpenGnsys." +MSG_HELP_ogMakeGroupDir="Crea el directorio de grupo (aula) en un repositorio." +MSG_HELP_ogMcastReceiverFile="" +MSG_HELP_ogMcastReceiverPartition="" +MSG_HELP_ogMcastRequest="" +MSG_HELP_ogMcastSendFile="" +MSG_HELP_ogMcastSendPartition="" +MSG_HELP_ogMcastSyntax="" MSG_HELP_ogMountCache="Monta el sistema de archivos dedicado a caché local." -MSG_HELP_ogMountCdrom="" +MSG_HELP_ogMountCdrom="Monta dispositivo óptico por defecto." MSG_HELP_ogMountFs=$MSG_HELP_ogMount MSG_HELP_ogMountImage="Monta una imagen sincronizable" +MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje." MSG_HELP_ogRaiseError="Muestra y registra mensajes de error y devuelve el código correspondiente." MSG_HELP_ogReduceFs="Reduce el tamaño del sistema de archivos al mínimo ocupado por sus datos." MSG_HELP_ogReduceImage="Reduce el tamaño de la imagen" +MSG_HELP_ogRestoreAclImage="" +MSG_HELP_ogRestoreBootLoaderImage="" +MSG_HELP_ogRestoreDiskImage="Restaura una imagen de un disco completo." MSG_HELP_ogRestoreImage="Restaura una imagen de sistema operativo." MSG_HELP_ogRestoreInfoImage="Restablece informacion del sistema: acl y enlaces simbolicos" MSG_HELP_ogRestoreMbrImage="Restaura una imagen del sector de arranque (MBR)." +MSG_HELP_ogSetLinuxName="" MSG_HELP_ogSetPartitionActive="Establece el número de partición activa de un disco." MSG_HELP_ogSetPartitionId="Modifica el tipo de una partición física usando el mnemónico del tipo." MSG_HELP_ogSetPartitionSize="Establece el tamaño de una partición." @@ -195,24 +261,36 @@ MSG_HELP_ogSetWindowsName="Asigna el nombre del cliente en el registro de Window MSG_HELP_ogSetWinlogonUser="Asigna el nombre de usuario por defecto para el gestor de entrada de Windows." MSG_HELP_ogSyncCreate="Sincroniza los datos de la particion a la imagen" MSG_HELP_ogSyncRestore="Sincroniza los datos de la imagen a la particion" +MSG_HELP_ogTorrentStart="" MSG_HELP_ogTypeToId="Devuelve el identificador asociado al mnemónico de tipo de partición." +MSG_HELP_ogUcastReceiverPartition="" +MSG_HELP_ogUcastSendFile="" +MSG_HELP_ogUcastSendPartition="" +MSG_HELP_ogUcastSyntax="" MSG_HELP_ogUnhidePartition="Hace visible una partición de Windows." +MSG_HELP_ogUninstallLinuxClient="Desinstala el cliente OpenGnSys en un sistema operativo Linux." +MSG_HELP_ogUninstallWindowsClient="Desinstala el cliente OpenGnSys en un sistema operativo Windows." MSG_HELP_ogUnlock="Desbloquea una partición tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockDisk="Desbloquea un disco tras finalizar una operación de uso exclusivo." MSG_HELP_ogUnlockImage="Desbloquea una imagen tras finalizar una operación de uso exclusivo." MSG_HELP_ogUnlockPartition=$MSG_HELP_ogUnlock -MSG_HELP_ogUnmount="Desmonta un sistema de archivos." MSG_HELP_ogUnmountAll="Desmonta todos los sistemas de archivos." MSG_HELP_ogUnmountCache="Desmonta el sistema de archivos de caché local." +MSG_HELP_ogUnmount="Desmonta un sistema de archivos." MSG_HELP_ogUnmountFs=$MSG_HELP_ogUnmount MSG_HELP_ogUnmountImage="Desmonta la imagen" +MSG_HELP_ogUnsetDirtyBit="" MSG_HELP_ogUpdateCacheIsNecesary="Comprueba si es necesario actualizar una archivo en la cache local." MSG_HELP_ogUpdatePartitionTable="Actualiza informacion tabla particiones del disco" -MSG_HELP_ogWaitMountImage="Se espera un tiempo estimado a que se monte la imagen en el servidor." +MSG_HELP_ogWaitSyncImage="" +MSG_HELP_ogWindowsBootParameters="" +MSG_HELP_ogWindowsRegisterPartition="" -# scripts +# Scripts MSG_HELP_configureOs="Post-configura de arranque del sistema" MSG_HELP_createBaseImage="Genera imagen basica de la particion" MSG_HELP_createDiffImage="Genera imagen diferencial de la particion respecto a la imagen basica" +MSG_HELP_installOfflineMode="Prepara el equipo cliente para el modo offline." MSG_HELP_partclone2sync="Convierte imagen de partclone en imagen sincronizable." MSG_HELP_restoreBaseImage="Restaura una imagen basica en una particion" MSG_HELP_restoreDiffImage="Restaura una imagen diferencial en una particion" @@ -259,12 +337,12 @@ MSG_SCRIPTS_TIME_PARTIAL="tiempo parcial del subproceso" # HTTPLOG MSG_HTTPLOG_NOUSE="No apague este ordenador por favor" -# mensajes syncronizadas +# Mensajes sincronizadas MSG_SYNC_RESIZE="Redimensiona la imagen al tamaño necesario" MSG_SYNC_RESTORE="Trae el listado ficheros y baja la imagen" MSG_SYNC_DELETE="Diferencial: Borra archivos antiguos" MSG_SYNC_SLEEP="Espera que se monte/reduzca la imagen" -# mensajes syncronizadas complementarios a errores +# Mensajes sincronizadas complementarios a errores MSG_SYNC_DIFFERENTFS="El sistema de ficheros de destino no coincide con el de la imagen" MSG_SYNC_EXTENSION="Las extensiones de la imagenes deben ser img o diff" MSG_SYNC_NOCHECK="La imagen esta montada por otro proceso, no podemos comprobarla" diff --git a/client/shared/etc/lang.en_GB.conf b/client/shared/etc/lang.en_GB.conf index e3698328..e61d1a8e 100644 --- a/client/shared/etc/lang.en_GB.conf +++ b/client/shared/etc/lang.en_GB.conf @@ -9,6 +9,7 @@ MSG_ERR_PARTITION="Unknown or missing partition" MSG_ERR_LOCKED="Resource locked by an operation" MSG_ERR_CACHE="Local cache error" MSG_ERR_NOGPT="The current disc does not contain a GPT partition" +MSG_ERR_REPO="Error al montar el repositorio de imágenes" MSG_ERR_FILESYS="Unknown or unmounted filesystem" MSG_ERR_NOTOS="Cannot detect or boot the operating system" MSG_ERR_IMAGE="Cannot create or cannot restore an image" @@ -39,12 +40,16 @@ MSG_ERR_NOTDIFFERENT="No differences were detected between the basic image and p MSG_ERR_SYNCHRONIZING="Error al sincronizar, puede afectar la creacion|restauracion de la imagen" # Warning messages. +MSG_DONTUSE="DO NOT USE" MSG_DONTMOUNT="Unmounted filesystem" MSG_DONTUNMOUNT="Cannot unmount the filesystem" -MSG_MOUNT="Sistema de archivos montado" +MSG_MOUNT="Filesystem already mounted" +MSG_MOUNTREADONLY="Filesystem mounted read-only" +MSG_OBSOLETE="OBSOLETE" # Help auxiliary menssages. -MSG_64BIT="64 bit" +MSG_64BIT="64-bit" +MSG_DISK="disk" MSG_ERROR="Error" MSG_EXAMPLE="Example" MSG_FORMAT="Format" @@ -54,10 +59,10 @@ MSG_IMAGE="image" MSG_INSTALLED="installed" MSG_NOCACHE="no lacal cache" MSG_NOEXTENDED="no extended partition" -MSG_NOFORMAT="no formatted" MSG_PARTITION="partition" MSG_PROTOCOL="protocol" MSG_RESERVEDVALUE="Reserved value" +MSG_SEE="See" MSG_UNKNOWN="Unknown" MSG_WARNING="Warning" @@ -88,20 +93,44 @@ MSG_HELP_ogAclFilter="Extract the fileACLs of a differential image." MSG_HELP_ogAddCmd="Add commands to file created by ogInstalMiniSetup function." MSG_HELP_ogAddRegistryKey="Add a new Windows registry key." MSG_HELP_ogAddRegistryValue="Add a new Windows registry value." +MSG_HELP_ogAddToLaunchDaemon="" MSG_HELP_ogBoot="Boot a installed operating system." +MSG_HELP_ogBootLoaderDeleteEntry="$MSG_DONTUSE." +MSG_HELP_ogBootLoaderHidePartitions="$MSG_DONTUSE." +MSG_HELP_ogBootMbrGeneric="" +MSG_HELP_ogBootMbrXP="" +MSG_HELP_ogBurgDefaultEntry="Configura la entrada por defecto de Burg." +MSG_HELP_ogBurgDeleteEntry="Borra en el Burg del MBR las entradas para el inicio en una particion." +MSG_HELP_ogBurgHidePartitions="Configura el Burg del MBR para que oculte las particiones de windows que no se esten iniciando." +MSG_HELP_ogBurgInstallMbr="Install the BURG boot loader on the MBR of the first hard disk" +MSG_HELP_ogBurgOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de Burg." MSG_HELP_ogCalculateChecksum="Calculate file checksum." +MSG_HELP_ogCalculateFullChecksum="" +MSG_HELP_ogChangeRepo="Cambia el repositorio para el recurso remoto images." MSG_HELP_ogCheckFs="Check a filesystem." +MSG_HELP_ogCheckIpAddress="" +MSG_HELP_ogCheckProgram="" +MSG_HELP_ogCheckStringInGroup="" +MSG_HELP_ogCheckStringInReg="" MSG_HELP_ogCheckSyncImage="Displays the contents of the image to check it." +MSG_HELP_ogCleanLinuxDevices="" MSG_HELP_ogCleanOs="Elimina los archivos que no son necesarios en el sistema operativo." MSG_HELP_ogCompareChecksumFiles="Compare if the checksums match." +MSG_HELP_ogConfigureFstab="" +MSG_HELP_ogConfigureOgagent="Configure new agent for operating systems." MSG_HELP_ogCopyFile="Copy a file to other storage." +MSG_HELP_ogCreateBootLoaderImage="" MSG_HELP_ogCreateCache="Reserve space for the cache partition at the end of disc 1." +MSG_HELP_ogCreateDiskImage="Create an exact image from a local disk." MSG_HELP_ogCreateFileImage="Create/Resize the synchronized image file." +MSG_HELP_ogCreateGptPartitions="" MSG_HELP_ogCreateImage="Create an exact image from a local filesystem." +MSG_HELP_ogCreateImageSyntax="" MSG_HELP_ogCreateInfoImage="Create information content of an image." MSG_HELP_ogCreateMbrImage="Create an MBR image." MSG_HELP_ogCreatePartitions="Create the disc partition table." MSG_HELP_ogCreatePartitionTable="Create a new disc partition table, if necesary." +MSG_HELP_ogCreateTorrent="" MSG_HELP_ogDeleteCache="Delete local cache partition." MSG_HELP_ogDeleteFile="Delete a file." MSG_HELP_ogDeletePartitionTable="Delete disk table partition" @@ -110,82 +139,121 @@ MSG_HELP_ogDeleteRegistryValue="Delete a Windows registry value." MSG_HELP_ogDeleteTree="Delete a directory tree." MSG_HELP_ogDevToDisk="Display the order number of disk or partition for the device file path." MSG_HELP_ogDiskToDev="Display the device file path for the order number of disk or partition." +MSG_HELP_ogDomainScript="" MSG_HELP_ogEcho="Display and log messages." +MSG_HELP_ogExecAndLog="" MSG_HELP_ogExtendFs="Extend the size of a filesystem to the maximum of its partition." MSG_HELP_ogFindCache="Indicates which partition is reserved for local cache." -MSG_HELP_ogFormat="Format a filesystem." +MSG_HELP_ogFixBootSector="" MSG_HELP_ogFormatCache="Format (purge) the local cache." +MSG_HELP_ogFormat="Format a filesystem." MSG_HELP_ogFormatFs=$MSG_HELP_ogFormat MSG_HELP_ogGetArch="Return the client architecture." MSG_HELP_ogGetCacheSize="Return the cache partition size." MSG_HELP_ogGetCacheSpace="Returns the maximum available space that can be reserved for the local cache partition." +MSG_HELP_ogGetCaller="" MSG_HELP_ogGetDiskSize="Return the disc size." +MSG_HELP_ogGetDiskType="" +MSG_HELP_ogGetFreeSize="" MSG_HELP_ogGetFsSize="Return the filesystem size." MSG_HELP_ogGetFsType="Return the filesystem type." MSG_HELP_ogGetGroupDir="Return the group directory path for the client." MSG_HELP_ogGetGroupName="Return the group name for the client." MSG_HELP_ogGetHivePath="Return the full file path of a Windows Registry hive." MSG_HELP_ogGetHostname="Return the client's hostname." -MSG_HELP_ogGetIpAddress="Return the client's IP address." +MSG_HELP_ogGetImageCompressor="Devuelve la herramienta de compresión de la imagen." +MSG_HELP_ogGetImageInfo="Muestra información sobre la imagen monolitica: clonacion:compresor:sistemaarchivos:tamañoKB." +MSG_HELP_ogGetImageProgram="Devuelve el programa usado para crear la imagen." MSG_HELP_ogGetImageSize="Return the system image size." +MSG_HELP_ogGetImageType="Devuelve el sistema de ficheros de la imagen." +MSG_HELP_ogGetIpAddress="Return the client's IP address." MSG_HELP_ogGetLastSector="Return the last available sector for a disc o partition." MSG_HELP_ogGetMacAddress="Return the client Ethernet address." MSG_HELP_ogGetMountImageDir="Return the image mount directory." MSG_HELP_ogGetMountPoint="Return the local filesystem mount point." +MSG_HELP_ogGetNetInterface="" MSG_HELP_ogGetOsType="Return the operating system type." +MSG_HELP_ogGetOsUuid="" MSG_HELP_ogGetOsVersion="Return the operating system version." -MSG_HELP_ogGetParentPath=$"Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnSys." +MSG_HELP_ogGetParentPath=$"Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnsys." MSG_HELP_ogGetPartitionActive="Return the active partitión of the disk." MSG_HELP_ogGetPartitionId="Return the partition type identifier." MSG_HELP_ogGetPartitionSize="Return the partition size." +MSG_HELP_ogGetPartitionsNumber="" MSG_HELP_ogGetPartitionTableType="Return the disc partiton table type." MSG_HELP_ogGetPartitionType="Return the partition type." MSG_HELP_ogGetPath="Return the file full path." MSG_HELP_ogGetRegistryValue="Return a data value from the Windows registry." MSG_HELP_ogGetRepoIp="Return the IP address of an OpenGnsys Repository." -MSG_HELP_ogGetServerIp="Return the main OpenGnSys Server IP address." +MSG_HELP_ogGetSerialNumber="Return the client's serial number." +MSG_HELP_ogGetServerIp="Return the main OpenGnsys Server IP address." MSG_HELP_ogGetSizeParameters="Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido." MSG_HELP_ogGetWindowsName="Return the client name saved in the Windows registry." -MSG_HELP_ogGrubAddOgclient="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubAddOgLive="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubDefaultEntry="Configura la entrada por defecto de GRUB." MSG_HELP_ogGrubDeleteEntry="Borra en el grub del MBR las entradas para el inicio en una particion." MSG_HELP_ogGrubHidePartitions="Configura el grub del MBR para que oculte las particiones de windows que no se esten iniciando." +MSG_HELP_ogGrubInstallMbr="Install the GRUB boot loader on the MBR of the first hard disk" +MSG_HELP_ogGrubInstallPartition="Install the BURG boot loader on the BootSector" +MSG_HELP_ogGrubOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de GRUB." MSG_HELP_ogHelp="Show the help menssages for functions." MSG_HELP_ogHidePartition="Hide a Windows partition." MSG_HELP_ogIdToType="Devuelve el mnemónico asociado al identificador de tipo de partición." -MSG_HELP_ogInstallLinuxClient="Installs OpenGnSys agent in a GNU/Linux operating system." +MSG_HELP_ogInstallFirstBoot="Crea un archivo que se ejecutará en el primer arranque de Windows." +MSG_HELP_ogInstallLaunchDaemon="Instala un archivo que se ejecutará en el arranque de macOS." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." MSG_HELP_ogInstallMiniSetup="Instala un archivo que se ejecutará en el arranque de Windows." -MSG_HELP_ogInstallWindowsClient="Installs OpenGnSys agent in a Windows operating system." +MSG_HELP_ogInstallRunonce="Crea archivo que se ejecutará en el inicio de un usuario administrador de Windows." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." MSG_HELP_ogIsFormated="Comprueba si un sistema de archivos está formateado." MSG_HELP_ogIsImageLocked="Comprueba si una imagen está bloqueada por una operación de uso exclusivo." -MSG_HELP_ogIsLocked="Comprueba si una partición está bloqueada por una operación de uso exclusivo." +MSG_HELP_ogIsLocked="Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo." +MSG_HELP_ogIsDiskLocked="Comprueba si un disco está bloqueado por una operación de uso exclusivo." MSG_HELP_ogIsMounted="Comprueba si un sistema de archivos está montado." MSG_HELP_ogIsNewerFile="Comprueba si un fichero es más nuevo (se ha modificado después) que otro." MSG_HELP_ogIsPartitionLocked=$MSG_HELP_ogIsLocked +MSG_HELP_ogIsRepoLocked="" MSG_HELP_ogIsSyncImage="Comprueba si la imagen es sincronizable." -MSG_HELP_ogIsValidType="Comprueba si el tipo de sistema de archivos es válido para un identificador de partición." +MSG_HELP_ogIsVirtualMachine="" MSG_HELP_ogIsWritable="Comprueba si un sistema de archivos está montado con permiso de escritura." MSG_HELP_ogLinuxBootParameters="Devuelve los parámetros de arranque de un sistema operativo Linux instalado." MSG_HELP_ogListHardwareInfo="List the cleint hardware inventory." +MSG_HELP_ogListLogicalPartitions="" MSG_HELP_ogListPartitions="List the disk partitions table." +MSG_HELP_ogListPrimaryPartitions="" MSG_HELP_ogListRegistryKeys="Lista los nombres de las subclaves incluidas en una clave del registro de Windows." MSG_HELP_ogListRegistryValues="Lista los nombres de los valores incluidos en una clave del registro de Windows." MSG_HELP_ogListSoftware="Lista el inventario de programas instalados en un sistema operativo." MSG_HELP_ogLock="Bloquea una partición para operación de uso exclusivo." +MSG_HELP_ogLockDisk="Bloquea un disco para operación de uso exclusivo." MSG_HELP_ogLockImage="Bloquea una imagen para operación de uso exclusivo." MSG_HELP_ogLockPartition=$MSG_HELP_ogLock MSG_HELP_ogMakeChecksumFile="Store the file checksum." MSG_HELP_ogMakeDir="Make a directory." -MSG_HELP_ogMount="Mount a filesystem and display its mount point." +MSG_HELP_ogMakeGroupDir="Make the group (lab) directory in a repository." +MSG_HELP_ogMcastReceiverFile="" +MSG_HELP_ogMcastReceiverPartition="" +MSG_HELP_ogMcastRequest="" +MSG_HELP_ogMcastSendFile="" +MSG_HELP_ogMcastSendPartition="" +MSG_HELP_ogMcastSyntax="" MSG_HELP_ogMountCache="Mount the cache filesystem." -MSG_HELP_ogMountCdrom="" +MSG_HELP_ogMountCdrom="Mount default optical drive." MSG_HELP_ogMountFs=$MSG_HELP_ogMount MSG_HELP_ogMountImage="Monta una imagen sincronizable" +MSG_HELP_ogMount="Mount a filesystem and display its mount point." MSG_HELP_ogRaiseError="Muestra y registra mensajes de error y devuelve el código correspondiente." MSG_HELP_ogReduceFs="Reduce el tamaño del sistema de archivos al mínimo ocupado por sus datos." MSG_HELP_ogReduceImage="Reduce el tamaño de la imagen" +MSG_HELP_ogRestoreAclImage="Restaura las ACL de Windows (La informacion debe estar copiada en /tmp)." +MSG_HELP_ogRestoreBootLoaderImage="" +MSG_HELP_ogRestoreDiskImage="Restore a disk image." MSG_HELP_ogRestoreImage="Restore a filesystem image." MSG_HELP_ogRestoreInfoImage="Restablece informacion del sistema: acl y enlaces simbolicos" MSG_HELP_ogRestoreMbrImage="Restore the boot sector image (MBR)." +MSG_HELP_ogSetLinuxName="" MSG_HELP_ogSetPartitionActive="Establece el número de partición activa de un disco." MSG_HELP_ogSetPartitionId="Change the partition identification using mnemonic." MSG_HELP_ogSetPartitionSize="Set the partition size." @@ -195,24 +263,36 @@ MSG_HELP_ogSetWindowsName="Asign the Windows hostname." MSG_HELP_ogSetWinlogonUser="Asign the Windows default username." MSG_HELP_ogSyncCreate="Sincroniza los datos de la particion a la imagen" MSG_HELP_ogSyncRestore="Sincroniza los datos de la imagen a la particion" +MSG_HELP_ogTorrentStart="" MSG_HELP_ogTypeToId="Devuelve el identificador asociado al mnemónico de tipo de partición." +MSG_HELP_ogUcastReceiverPartition="" +MSG_HELP_ogUcastSendFile="" +MSG_HELP_ogUcastSendPartition="" +MSG_HELP_ogUcastSyntax="" MSG_HELP_ogUnhidePartition="Unhide a Windows partition." +MSG_HELP_ogUninstallLinuxClient="Uninstalls OpenGnSys agent in a Linux operating system." +MSG_HELP_ogUninstallWindowsClient="Uninstalls OpenGnSys agent in a Windows operating system." MSG_HELP_ogUnlock="Desbloquea una partición tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockDisk="Desbloquea un dicso tras finalizar una operación de uso exclusivo." MSG_HELP_ogUnlockImage="Desbloquea una imagen tras finalizar una operación de uso exclusivo." MSG_HELP_ogUnlockPartition=$MSG_HELP_ogUnlock -MSG_HELP_ogUnmount="Unmount a filesystem." MSG_HELP_ogUnmountAll="Unmount all filesystems." MSG_HELP_ogUnmountCache="Unmount the cache filesystem." MSG_HELP_ogUnmountFs=$MSG_HELP_ogUnmount MSG_HELP_ogUnmountImage="Desmonta la imagen" +MSG_HELP_ogUnmount="Unmount a filesystem." +MSG_HELP_ogUnsetDirtyBit= MSG_HELP_ogUpdateCacheIsNecesary="Comprueba si es necesario actualizar una archivo en la cache local." MSG_HELP_ogUpdatePartitionTable="Update info about disk partition table " -MSG_HELP_ogWaitMountImage="Se espera un tiempo estimado a que se monte la imagen en el servidor." +MSG_HELP_ogWaitSyncImage="" +MSG_HELP_ogWindowsBootParameters="" +MSG_HELP_ogWindowsRegisterPartition="" -# scripts +# Scripts MSG_HELP_configureOs="Post-configura de arranque del sistema" MSG_HELP_createBaseImage="Genera imagen basica de la particion" MSG_HELP_createDiffImage="Genera imagen diferencial de la particion respecto a la imagen basica" +MSG_HELP_installOfflineMode="Prepara el equipo cliente para el modo offline." MSG_HELP_partclone2sync="Convierte imagen de partclone en imagen sincronizable." MSG_HELP_restoreBaseImage="Restaura una imagen basica en una particion" MSG_HELP_restoreDiffImage="Restaura una imagen diferencial en una particion" @@ -259,12 +339,12 @@ MSG_SCRIPTS_TIME_PARTIAL="Part-time process" # HTTPLOG MSG_HTTPLOG_NOUSE="NOT POWEROFF THIS COMPUTER" -# mensajes syncronizadas +# Mensajes sincronizadas MSG_SYNC_RESIZE="Redimensiona la imagen al tamaño necesario" MSG_SYNC_RESTORE="Trae el listado ficheros y baja la imagen" MSG_SYNC_DELETE="Diferencial: Borra archivos antiguos" MSG_SYNC_SLEEP="Espera que se monte/reduzca la imagen" -# mensajes syncronizadas complementarios a errores +# Mensajes sincronizadas complementarios a errores MSG_SYNC_DIFFERENTFS="El sistema de ficheros de destino no coincide con el de la imagen" MSG_SYNC_EXTENSION="Las extensiones de la imagenes deben ser img o diff" MSG_SYNC_NOCHECK="La imagen esta montada por otro proceso, no podemos comprobarla" diff --git a/client/shared/etc/lang.es_ES.conf b/client/shared/etc/lang.es_ES.conf index b3c5b761..6798ba50 100644 --- a/client/shared/etc/lang.es_ES.conf +++ b/client/shared/etc/lang.es_ES.conf @@ -9,6 +9,7 @@ MSG_ERR_PARTITION="Partición errónea o desconocida" MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo" MSG_ERR_CACHE="Error en partición de caché local" MSG_ERR_NOGPT="El disco indicado no contiene una partición GPT" +MSG_ERR_REPO="Error al montar el repositorio de imágenes" MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar" MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar" MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema" @@ -40,11 +41,15 @@ MSG_ERR_SYNCHRONIZING="Error al sincronizar, puede afectar la creacion|restaurac # Mensajes de avisos. MSG_DONTMOUNT="Sistema de archivos no montado" +MSG_DONTUSE="NO USAR" MSG_DONTUNMOUNT="El sistema de archivos no se puede desmontar o no está montado" MSG_MOUNT="Sistema de archivos montado" +MSG_MOUNTREADONLY="Sistema de archivos montado solo de lectura" +MSG_OBSOLETE="EN DESUSO" # Mensajes complementarios para las ayudas. MSG_64BIT="64 bits" +MSG_DISK="disco" MSG_ERROR="Error" MSG_EXAMPLE="Ejemplo" MSG_FORMAT="Formato" @@ -54,10 +59,10 @@ MSG_IMAGE="imagen" MSG_INSTALLED="instalado" MSG_NOCACHE="sin caché local" MSG_NOEXTENDED="sin partición extendida" -MSG_NOFORMAT="sin formato" MSG_PARTITION="partición" MSG_PROTOCOL="protocolo" MSG_RESERVEDVALUE="Valor reservado" +MSG_SEE="Ver" MSG_UNKNOWN="Desconocido" MSG_WARNING="Aviso" @@ -88,20 +93,44 @@ MSG_HELP_ogAclFilter="Extrae las acl de los ficheros de la diferencial" MSG_HELP_ogAddCmd="Añade comandos al fichero creado por la función ogInstalMiniSetup." MSG_HELP_ogAddRegistryKey="Añade una nueva clave al registro de Windows." MSG_HELP_ogAddRegistryValue="Añade un nuevo valor al registro de Windows." +MSG_HELP_ogAddToLaunchDaemon="" MSG_HELP_ogBoot="Arranca un sistema operativo instalado." +MSG_HELP_ogBootLoaderDeleteEntry="$MSG_DONTUSE." +MSG_HELP_ogBootLoaderHidePartitions="$MSG_DONTUSE." +MSG_HELP_ogBootMbrGeneric="" +MSG_HELP_ogBootMbrXP="" +MSG_HELP_ogBurgDefaultEntry="Configura la entrada por defecto de Burg." +MSG_HELP_ogBurgDeleteEntry="Borra en el Burg del MBR las entradas para el inicio en una particion." +MSG_HELP_ogBurgHidePartitions="Configura el Burg del MBR para que oculte las particiones de windows que no se esten iniciando." +MSG_HELP_ogBurgInstallMbr="Instala el gestor de arranque BURG en el MBR del primer disco duro" +MSG_HELP_ogBurgOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de Burg." MSG_HELP_ogCalculateChecksum="Calcula la suma de comprobación (checksum) de un fichero." +MSG_HELP_ogCalculateFullChecksum="Calcula la suma de comprobación completa de un fichero." +MSG_HELP_ogChangeRepo="Cambia el repositorio para el recurso remoto images." MSG_HELP_ogCheckFs="Comprueba la consistencia de un sistema de archivos." +MSG_HELP_ogCheckIpAddress="" +MSG_HELP_ogCheckProgram="" +MSG_HELP_ogCheckStringInGroup="" +MSG_HELP_ogCheckStringInReg="" MSG_HELP_ogCheckSyncImage="Muestra el contenido de la imagen para comprobarla." +MSG_HELP_ogCleanLinuxDevices="" MSG_HELP_ogCleanOs="Elimina los archivos que no son necesarios en el sistema operativo." MSG_HELP_ogCompareChecksumFiles="Compara si coinciden las sumas de comprobación almacenadas de 2 ficheros." +MSG_HELP_ogConfigureFstab="" +MSG_HELP_ogConfigureOgagent="Configura el nuevo agente OGAgent para sistemas operativos." MSG_HELP_ogCopyFile="Copia un fichero a otro almacenamiento." +MSG_HELP_ogCreateBootLoaderImage="" MSG_HELP_ogCreateCache="Reserva espacio para la partición de caché al final del disco 1." +MSG_HELP_ogCreateDiskImage="Genera una imagen exacta de un disco completo." MSG_HELP_ogCreateFileImage="Crea/redimensiona el archivo de la imagen sincronizada" +MSG_HELP_ogCreateGptPartitions="" MSG_HELP_ogCreateImage="Genera una imagen exacta de un sistema operativo instalado localmente." +MSG_HELP_ogCreateImageSyntax="" MSG_HELP_ogCreateInfoImage="Crea información del contenido de la imagen" MSG_HELP_ogCreateMbrImage="Genera una imagen del sector de arranque (MBR)." MSG_HELP_ogCreatePartitions="Define la estructura de particiones de un disco." MSG_HELP_ogCreatePartitionTable="Genera una tabla de particiones en caso de que no sea valida." +MSG_HELP_ogCreateTorrent="" MSG_HELP_ogDeleteCache="Elimina la partición de caché local." MSG_HELP_ogDeleteFile="Borra un fichero de un espacio de almacenamiento." MSG_HELP_ogDeletePartitionTable="Elimina la tabla de particiones del disco" @@ -110,82 +139,121 @@ MSG_HELP_ogDeleteRegistryValue="Borra un valor del registro de Windows." MSG_HELP_ogDeleteTree="Borra un árbol de directorios de un espacio de almacenamiento." MSG_HELP_ogDevToDisk="Devuelve el nº de orden de disco o de partición correspondiente al camino del fichero de dispositivo." MSG_HELP_ogDiskToDev="Devuelve el camino del fichero de dispositivo correspondiente al nº de orden de disco o de partición." -MSG_HELP_ogEcho="" +MSG_HELP_ogDomainScript="" +MSG_HELP_ogEcho="Muestra un mensaje en pantalla y permite registrarlo en fichero de log" +MSG_HELP_ogExecAndLog="Ejecuta un comando y registra su salida en fichero de log" MSG_HELP_ogExtendFs="Extiende el tamaño de un sistema de archivo al máximo de su partición." MSG_HELP_ogFindCache="Indica la partición reservada para caché local." -MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos." +MSG_HELP_ogFixBootSector="" MSG_HELP_ogFormatCache="Formatea (inicia) el sistema de caché local." +MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos." MSG_HELP_ogFormatFs=$MSG_HELP_ogFormat MSG_HELP_ogGetArch="Devuelve el tipo de arquitectura del cliente." MSG_HELP_ogGetCacheSize="Devuelve el tamaño de la partición de caché local." MSG_HELP_ogGetCacheSpace="Devuelve el espacio máximo disponible que puede ser reservado para la partición de caché local." +MSG_HELP_ogGetCaller="Devuelve el programa o función que llama al actual" MSG_HELP_ogGetDiskSize="Devuelve el tamaño del disco." +MSG_HELP_ogGetDiskType="" +MSG_HELP_ogGetFreeSize="" MSG_HELP_ogGetFsSize="Devuelve el tamaño de un sistema de archivos." MSG_HELP_ogGetFsType="Devuelve el mnemónico de tipo de sistema de archivos." MSG_HELP_ogGetGroupDir="Devuelve el camino del directorio por defecto para el grupo del cliente." MSG_HELP_ogGetGroupName="Devuelve el nombre del grupo al que pertenece el cliente." MSG_HELP_ogGetHivePath="Devuelve el camino completo del fichero de una sección del registro de Windows." MSG_HELP_ogGetHostname="Devuelve el nombre de la máquina local." -MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente." +MSG_HELP_ogGetImageCompressor="Devuelve la herramienta de compresión de la imagen." +MSG_HELP_ogGetImageInfo="Muestra información sobre la imagen monolitica: clonacion:compresor:sistemaarchivos:tamañoKB." +MSG_HELP_ogGetImageProgram="Devuelve el programa usado para crear la imagen." MSG_HELP_ogGetImageSize="Devuelve el tamaño de una imagen de sistema." +MSG_HELP_ogGetImageType="Devuelve el sistema de ficheros de la imagen." +MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente." MSG_HELP_ogGetLastSector="Devuelve el último sector usable del disco o de una partición." MSG_HELP_ogGetMacAddress="Devuelve la dirección Ethernet del cliente." MSG_HELP_ogGetMountImageDir="Devuelve el directorio de montaje de una imagen." MSG_HELP_ogGetMountPoint="Devuelve el directorio donde está montado un sistema de archivos local." +MSG_HELP_ogGetNetInterface="" MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado." +MSG_HELP_ogGetOsUuid="Devuelve el UUID de un sistema operativo" MSG_HELP_ogGetOsVersion="Devuelve el tipo y la versión de un sistema operativo instalado." -MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnSys." +MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnsys." MSG_HELP_ogGetPartitionActive="Indica cual es la partición marcada como activa en un disco." MSG_HELP_ogGetPartitionId="Devuelve el identificador de tipo de una partición." MSG_HELP_ogGetPartitionSize="Devuelve el tamaño de una partición." +MSG_HELP_ogGetPartitionsNumber="Devuelve el número de particiones de un disco" MSG_HELP_ogGetPartitionTableType="Devuelve el tipo de tabla de particiones del disco" MSG_HELP_ogGetPartitionType="Devuelve el mnemónico de tipo de una partición." -MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnSys." +MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnsys." MSG_HELP_ogGetRegistryValue="Devuelve el dato de un valor del registro de Windows." MSG_HELP_ogGetRepoIp="Devuelve la dirección IP del repositorio de datos." +MSG_HELP_ogGetSerialNumber="Devuelve el número de serie del equipo" MSG_HELP_ogGetServerIp="Devuelve la dirección IP del servidor principal." MSG_HELP_ogGetSizeParameters="Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido." MSG_HELP_ogGetWindowsName="Devuelve el nombre del cliente guardado en el registro de Windows." -MSG_HELP_ogGrubAddOgclient="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubAddOgLive="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubDefaultEntry="Configura la entrada por defecto de GRUB." MSG_HELP_ogGrubDeleteEntry="Borra en el grub del MBR las entradas para el inicio en una particion." MSG_HELP_ogGrubHidePartitions="Configura el grub del MBR para que oculte las particiones de windows que no se esten iniciando." +MSG_HELP_ogGrubInstallMbr="Instala el gestor de arranque GRUB en el MBR del primer disco duro" +MSG_HELP_ogGrubInstallPartition="Instala el gestor de arranque GRUB en el BootSector" +MSG_HELP_ogGrubOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de GRUB." MSG_HELP_ogHelp="Muestra mensajes de ayudas para las funciones." MSG_HELP_ogHidePartition="Oculta una partición de Windows." MSG_HELP_ogIdToType="Devuelve el mnemónico asociado al identificador de tipo de partición." -MSG_HELP_ogInstallLinuxClient="Instala el cliente OpenGnSys en un sistema operativo GNU/Linux." +MSG_HELP_ogInstallFirstBoot="Crea un archivo que se ejecutará en el primer arranque de Windows." +MSG_HELP_ogInstallLaunchDaemon="Instala un archivo que se ejecutará en el arranque de macOS." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." MSG_HELP_ogInstallMiniSetup="Instala un archivo que se ejecutará en el arranque de Windows." -MSG_HELP_ogInstallWindowsClient="Instala el cliente OpenGnSys en un sistema operativo Windows." +MSG_HELP_ogInstallRunonce="Crea archivo que se ejecutará en el inicio de un usuario administrador de Windows." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." MSG_HELP_ogIsFormated="Comprueba si un sistema de archivos está formateado." MSG_HELP_ogIsImageLocked="Comprueba si una imagen está bloqueada por una operación de uso exclusivo." -MSG_HELP_ogIsLocked="Comprueba si una partición está bloqueada por una operación de uso exclusivo." +MSG_HELP_ogIsLocked="Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo." +MSG_HELP_ogIsDiskLocked="Comprueba si un disco está bloqueado por una operación de uso exclusivo." MSG_HELP_ogIsMounted="Comprueba si un sistema de archivos está montado." MSG_HELP_ogIsNewerFile="Comprueba si un fichero es más nuevo (se ha modificado después) que otro." MSG_HELP_ogIsPartitionLocked=$MSG_HELP_ogIsLocked +MSG_HELP_ogIsRepoLocked="" MSG_HELP_ogIsSyncImage="Comprueba si la imagen es sincronizable." -MSG_HELP_ogIsValidType="Comprueba si el tipo de sistema de archivos es válido para un identificador de partición." +MSG_HELP_ogIsVirtualMachine="Comprueba si el cliente es una máquina virtual" MSG_HELP_ogIsWritable="Comprueba si un sistema de archivos está montado con permiso de escritura." MSG_HELP_ogLinuxBootParameters="Devuelve los parámetros de arranque de un sistema operativo Linux instalado." MSG_HELP_ogListHardwareInfo="Lista el inventario de dispositivos del cliente." +MSG_HELP_ogListLogicalPartitions="Lista las particiones lógicas de un disco" MSG_HELP_ogListPartitions="Lista la estructura de particiones de un disco." +MSG_HELP_ogListPrimaryPartitions="Lista las particiones primarias de un disco" MSG_HELP_ogListRegistryKeys="Lista los nombres de las subclaves incluidas en una clave del registro de Windows." MSG_HELP_ogListRegistryValues="Lista los nombres de los valores incluidos en una clave del registro de Windows." MSG_HELP_ogListSoftware="Lista el inventario de programas instalados en un sistema operativo." MSG_HELP_ogLock="Bloquea una partición para operación de uso exclusivo." +MSG_HELP_ogLockDisk="Bloquea un disco para operación de uso exclusivo." MSG_HELP_ogLockImage="Bloquea una imagen para operación de uso exclusivo." MSG_HELP_ogLockPartition=$MSG_HELP_ogLock MSG_HELP_ogMakeChecksumFile="Almacena la suma de comprobación de un fichero." -MSG_HELP_ogMakeDir="Crea un directorio para OpenGnSys." -MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje." +MSG_HELP_ogMakeDir="Crea un directorio para OpenGnsys." +MSG_HELP_ogMakeGroupDir="Crea el directorio de grupo (aula) en un repositorio." +MSG_HELP_ogMcastReceiverFile="" +MSG_HELP_ogMcastReceiverPartition="" +MSG_HELP_ogMcastRequest="" +MSG_HELP_ogMcastSendFile="" +MSG_HELP_ogMcastSendPartition="" +MSG_HELP_ogMcastSyntax="" MSG_HELP_ogMountCache="Monta el sistema de archivos dedicado a caché local." -MSG_HELP_ogMountCdrom="" +MSG_HELP_ogMountCdrom="Monta dispositivo óptico por defecto." MSG_HELP_ogMountFs=$MSG_HELP_ogMount MSG_HELP_ogMountImage="Monta una imagen sincronizable" +MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje." MSG_HELP_ogRaiseError="Muestra y registra mensajes de error y devuelve el código correspondiente." MSG_HELP_ogReduceFs="Reduce el tamaño del sistema de archivos al mínimo ocupado por sus datos." MSG_HELP_ogReduceImage="Reduce el tamaño de la imagen" +MSG_HELP_ogRestoreAclImage="Restaura las ACL de Windows (La informacion debe estar copiada en /tmp)." +MSG_HELP_ogRestoreBootLoaderImage="" +MSG_HELP_ogRestoreDiskImage="Restaura una imagen de un disco completo." MSG_HELP_ogRestoreImage="Restaura una imagen de sistema operativo." MSG_HELP_ogRestoreInfoImage="Restablece información del sistema: ACL y enlaces simbolicos" MSG_HELP_ogRestoreMbrImage="Restaura una imagen del sector de arranque (MBR)." +MSG_HELP_ogSetLinuxName="" MSG_HELP_ogSetPartitionActive="Establece el número de partición activa de un disco." MSG_HELP_ogSetPartitionId="Modifica el tipo de una partición física usando el mnemónico del tipo." MSG_HELP_ogSetPartitionSize="Establece el tamaño de una partición." @@ -195,19 +263,30 @@ MSG_HELP_ogSetWindowsName="Asigna el nombre del cliente en el registro de Window MSG_HELP_ogSetWinlogonUser="Asigna el nombre de usuario por defecto para el gestor de entrada de Windows." MSG_HELP_ogSyncCreate="Sincroniza los datos de la partición a la imagen" MSG_HELP_ogSyncRestore="Sincroniza los datos de la imagen a la partición" +MSG_HELP_ogTorrentStart="" MSG_HELP_ogTypeToId="Devuelve el identificador asociado al mnemónico de tipo de partición." +MSG_HELP_ogUcastReceiverPartition="" +MSG_HELP_ogUcastSendFile="" +MSG_HELP_ogUcastSendPartition="" +MSG_HELP_ogUcastSyntax="" MSG_HELP_ogUnhidePartition="Hace visible una partición de Windows." +MSG_HELP_ogUninstallLinuxClient="Desinstala el antiguo cliente OpenGnSys en un sistema operativo Linux." +MSG_HELP_ogUninstallWindowsClient="Desinstala el antiguo cliente OpenGnSys en un sistema operativo Windows." MSG_HELP_ogUnlock="Desbloquea una partición tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockDisk="Desbloquea un disco tras finalizar una operación de uso exclusivo." MSG_HELP_ogUnlockImage="Desbloquea una imagen tras finalizar una operación de uso exclusivo." MSG_HELP_ogUnlockPartition=$MSG_HELP_ogUnlock -MSG_HELP_ogUnmount="Desmonta un sistema de archivos." MSG_HELP_ogUnmountAll="Desmonta todos los sistemas de archivos." MSG_HELP_ogUnmountCache="Desmonta el sistema de archivos de caché local." +MSG_HELP_ogUnmount="Desmonta un sistema de archivos." MSG_HELP_ogUnmountFs=$MSG_HELP_ogUnmount -MSG_HELP_ogUnmountImage="Desmonta la imagen" +MSG_HELP_ogUnmountImage="Desmonta la imagen." +MSG_HELP_ogUnsetDirtyBit="" MSG_HELP_ogUpdateCacheIsNecesary="Comprueba si es necesario actualizar una archivo en la cache local." -MSG_HELP_ogUpdatePartitionTable="Actualiza información de la tabla de particiones del disco" -MSG_HELP_ogWaitMountImage="Se espera un tiempo estimado a que se monte la imagen en el servidor." +MSG_HELP_ogUpdatePartitionTable="Actualiza información de la tabla de particiones del disco." +MSG_HELP_ogWaitSyncImage="" +MSG_HELP_ogWindowsBootParameters="" +MSG_HELP_ogWindowsRegisterPartition="" # Scripts MSG_HELP_configureOs="Post-configura de arranque del sistema" @@ -260,12 +339,12 @@ MSG_SCRIPTS_TIME_PARTIAL="tiempo parcial del subproceso" # HTTPLOG MSG_HTTPLOG_NOUSE="No apague este ordenador por favor" -# Mensajes syncronizadas +# Mensajes sincronizadas MSG_SYNC_RESIZE="Redimensiona la imagen al tamaño necesario" MSG_SYNC_RESTORE="Trae el listado ficheros y baja la imagen" MSG_SYNC_DELETE="Diferencial: Borra archivos antiguos" MSG_SYNC_SLEEP="Espera que se monte/reduzca la imagen" -# mensajes syncronizadas complementarios a errores +# Mensajes sincronizadas complementarios a errores MSG_SYNC_DIFFERENTFS="El sistema de ficheros de destino no coincide con el de la imagen" MSG_SYNC_EXTENSION="Las extensiones de la imagenes deben ser img o diff" MSG_SYNC_NOCHECK="La imagen esta montada por otro proceso, no podemos comprobarla" diff --git a/client/shared/etc/preinit/default.sh b/client/shared/etc/preinit/default.sh index 2624edc4..e5d1d0b1 100755 --- a/client/shared/etc/preinit/default.sh +++ b/client/shared/etc/preinit/default.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Cargar entorno de OpenGnSys +# Cargar entorno de OpenGnsys set -a source /opt/opengnsys/etc/preinit/loadenviron.sh @@ -10,7 +10,7 @@ for f in fileslinks loadmodules metadevs mountrepo poweroff otherservices; do done unset f -if [ -f $OGETC/init/$OG_IP.sh ]; then +if [ -f $OGETC/init/$IPV4ADDR.sh ]; then $OGETC/init/$OG_IP.sh elif [ -f $OGETC/init/$OGGROUP.sh ]; then diff --git a/client/shared/etc/preinit/fileslinks.sh b/client/shared/etc/preinit/fileslinks.sh index 2e71340d..b6fc7e2f 100755 --- a/client/shared/etc/preinit/fileslinks.sh +++ b/client/shared/etc/preinit/fileslinks.sh @@ -12,7 +12,7 @@ #*/ -# Si está configurado OpenGnSys ... +# Si está configurado OpenGnsys ... if [ -n "$OPENGNSYS" ]; then echo "${MSG_MAKELINKS:-.}" @@ -43,8 +43,8 @@ if [ -n "$OPENGNSYS" ]; then done else - # FIXME Error: entorno de OpenGnSys no configurado. - echo "Error: OpenGnSys environment is not configured." # FIXME: definir mensaje. + # FIXME Error: entorno de OpenGnsys no configurado. + echo "Error: OpenGnsys environment is not configured." # FIXME: definir mensaje. exit 1 fi diff --git a/client/shared/etc/preinit/loadenviron.sh b/client/shared/etc/preinit/loadenviron.sh index b165ecfd..314fb872 100755 --- a/client/shared/etc/preinit/loadenviron.sh +++ b/client/shared/etc/preinit/loadenviron.sh @@ -1,7 +1,7 @@ #!/bin/bash #/** #@file loadenviron.sh -#@brief Script de carga de la API de funciones de OpenGNSys. +#@brief Script de carga de la API de funciones de OpenGnsys. #@warning License: GNU GPLv3+ #@version 0.9 #@author Ramon Gomez, ETSII Universidad de Sevilla @@ -16,8 +16,9 @@ # Idioma por defecto. export LANG="${LANG:-es_ES}" +locale-gen $LANG -# Directorios del projecto OpenGnSys. +# Directorios del proyecto OpenGnsys. export OPENGNSYS="${OPENGNSYS:-/opt/opengnsys}" if [ -d $OPENGNSYS ]; then export OGBIN=$OPENGNSYS/bin @@ -116,6 +117,7 @@ export OG_ERR_OUTOFLIMIT=19 # Valor fuera de rango o no válido. export OG_ERR_FILESYS=20 # Sistema de archivos desconocido o no se puede montar export OG_ERR_CACHE=21 # Error en partición de caché local export OG_ERR_NOGPT=22 # El disco indicado no contiene una particion GPT +export OG_ERR_REPO=23 # Error al montar el repositorio de imagenes export OG_ERR_IMGSIZEPARTITION=30 # Error al restaurar partición más pequeña que la imagen export OG_ERR_UPDATECACHE=31 # Error al realizar el comando updateCache diff --git a/client/shared/etc/preinit/metadevs.sh b/client/shared/etc/preinit/metadevs.sh index d9b12d45..e2454c57 100755 --- a/client/shared/etc/preinit/metadevs.sh +++ b/client/shared/etc/preinit/metadevs.sh @@ -13,7 +13,7 @@ #*/ -# Si está configurado OpenGNSys ... +# Si está configurado OpenGnsys ... if [ -n "$OPENGNSYS" ]; then echo "$MSG_DETECTLVMRAID" # Detectar metadispositivos LVM. @@ -21,8 +21,8 @@ if [ -n "$OPENGNSYS" ]; then # Detectar metadispositivos RAID. dmraid -ay &>/dev/null else - # FIXME Error: entorno de OpenGNSys no configurado. - echo "Error: OpenGNSys environment is not configured." # FIXME: definir mensaje. + # FIXME Error: entorno de OpenGnsys no configurado. + echo "Error: OpenGnsys environment is not configured." # FIXME: definir mensaje. exit 1 fi diff --git a/client/shared/etc/preinit/mountrepo.sh b/client/shared/etc/preinit/mountrepo.sh index 62b1107e..e1c18fec 100755 --- a/client/shared/etc/preinit/mountrepo.sh +++ b/client/shared/etc/preinit/mountrepo.sh @@ -17,13 +17,14 @@ if [ "$ogactiveadmin" == "true" ]; then umount $OGIMG 2>/dev/null protocol=${ogprotocol:-"smb"} + [ "$ogunit" != "" ] && OGUNIT="/$ogunit" printf "$MSG_MOUNTREPO\n" "$protocol" "$boot" case "$ogprotocol" in - nfs) mount.nfs ${ROOTREPO}:$OGIMG $OGIMG -o rw,nolock ;; + nfs) mount.nfs ${ROOTREPO}:$OGIMG$OGUNIT $OGIMG -o rw,nolock ;; smb) PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \ sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') PASS=${PASS:-"og"} - mount.cifs //${ROOTREPO}/ogimages $OGIMG -o rw,serverino,acl,username=opengnsys,password=$PASS + mount.cifs //${ROOTREPO}/ogimages$OGUNIT $OGIMG -o rw,serverino,acl,username=opengnsys,password=$PASS ;; local) # TODO: hacer funcion dentro de este script que monte smb # Comprobamos que estatus sea online. diff --git a/client/shared/etc/preinit/otherservices.sh b/client/shared/etc/preinit/otherservices.sh index c9086ad4..8c7d4cef 100755 --- a/client/shared/etc/preinit/otherservices.sh +++ b/client/shared/etc/preinit/otherservices.sh @@ -19,7 +19,7 @@ PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \ sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') PASS=${PASS:-"og"} echo -ne "$PASS\n$PASS\n" | passwd root 2>/dev/null -# Cargar el entorno OpenGnSys en conexión SSH. +# Cargar el entorno OpenGnsys en conexión SSH. cp -a $OPENGNSYS/etc/preinit/loadenviron.sh /etc/profile.d/ # Arrancar SSH. /usr/sbin/sshd 2>/dev/null @@ -28,7 +28,7 @@ cp -a $OPENGNSYS/etc/preinit/loadenviron.sh /etc/profile.d/ #setterm -blank 0 -powersave off -powerdown 0 < /dev/console > /dev/console 2>&1 # Activado WOL en la interfaz usada en arranque PXE. -#ethtool -s $DEVICE wol g 2>/dev/null +ethtool -s $DEVICE wol g 2>/dev/null # TODO Localizar correctamente el script de arranque. [ -f /opt/opengnsys/scripts/runhttplog.sh ] && /opt/opengnsys/scripts/runhttplog.sh 2>/dev/null diff --git a/client/shared/etc/preinit/poweroff.sh b/client/shared/etc/preinit/poweroff.sh index 9a9f7b2b..f5f9f986 100755 --- a/client/shared/etc/preinit/poweroff.sh +++ b/client/shared/etc/preinit/poweroff.sh @@ -10,16 +10,21 @@ #*/ -# Si está configurado OpenGnSys ... +# Si está configurado OpenGnsys ... if [ -n "$OPENGNSYS" ]; then echo "${MSG_POWEROFFCONF:-.}" + # Sincronización horaria con servidor NTP. + [ -n "$ogntp" -a "$status" != "offline" ] && ntpdate $ogntp + # Crear fichero de configuración por defecto (30 min. de espera). POWEROFFCONF=/etc/poweroff.conf cat << FIN > $POWEROFFCONF POWEROFFSLEEP=30 POWEROFFTIME= FIN + # Incluir zona horaria en el fichero de configuración. + awk 'BEGIN {RS=" "} /^TZ=/ {print}' /proc/cmdline >> $POWEROFFCONF # Lanzar el proceso "cron". cron -l @@ -28,8 +33,8 @@ FIN echo "* * * * * [ -x $OGBIN/poweroffconf ] && $OGBIN/poweroffconf" | crontab - else - # FIXME Error: entorno de OpenGnSys no configurado. - echo "Error: OpenGnSys environment is not configured." # FIXME: definir mensaje. + # FIXME Error: entorno de OpenGnsys no configurado. + echo "Error: OpenGnsys environment is not configured." # FIXME: definir mensaje. exit 1 fi diff --git a/client/shared/lib/burg/themes/OpenGnsys/background-original.png b/client/shared/lib/burg/themes/OpenGnsys/background-original.png new file mode 100644 index 00000000..57861def Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/background-original.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/background.png b/client/shared/lib/burg/themes/OpenGnsys/background.png new file mode 100755 index 00000000..8150330b Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/background.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/extended b/client/shared/lib/burg/themes/OpenGnsys/extended new file mode 100644 index 00000000..c61e14a0 --- /dev/null +++ b/client/shared/lib/burg/themes/OpenGnsys/extended @@ -0,0 +1,79 @@ +include "theme" + +screen { + background = "$$/background.png" + + panel { + halign = center + attach_vcenter = 0 + height = 19 + # Flip so the cursor defaults to the main menu + direction = bottom_to_top + + ### Main Menu ### + panel { + height = 15 + max_width = 120 + margin_top = 1 + class = container-body + # No need for a min width and centering panel because extended width > min width + + direction = left_to_right + anchor = 1 + id = __menu__ + } + + panel { + height = 4 + width = 100% + class = container-title + + direction = left_to_right + + image { + image = "$$/images/txt-select.png" + attach_top = 0 + attach_left = 0 + } + + ### Tools Menu ### + image { + attach_right = 2 + image = "$$/images/button-tools.png:$$/images/button-tools-hover.png" + command = "menu_popup tools_menu" + } + } + } + + ### Progress Bar ### + panel { + halign = center + attach_vcenter = 20 + width = 80 + class = progressbar-background + id = __timeout__ + + progressbar { } + } +} + +template_menuitem { + panel { + width = 40 + height = 12 + + parameters = "class=image.class:title=panel.text.text" + + image { + attach_vcenter = 0 + attach_hcenter = 0 + } + + panel { + attach_vcenter = 0 + attach_hcenter = 0 + class = text-line + text { font = "Helvetica Regular 22" } + } + } +} diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_debian.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_debian.png new file mode 100644 index 00000000..55d7ce09 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_debian.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_elementary.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_elementary.png new file mode 100644 index 00000000..a2bc2b26 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_elementary.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_freebsd.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_freebsd.png new file mode 100644 index 00000000..eedade73 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_freebsd.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_haiku.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_haiku.png new file mode 100644 index 00000000..f6b21d65 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_haiku.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_linux.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_linux.png new file mode 100644 index 00000000..5064c4a9 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_linux.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_opengnsys.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_opengnsys.png new file mode 100644 index 00000000..aea9bfea Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_opengnsys.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_opensuse.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_opensuse.png new file mode 100644 index 00000000..bdc548be Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_opensuse.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_os.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_os.png new file mode 100644 index 00000000..abb4b296 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_os.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_osx.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_osx.png new file mode 100644 index 00000000..8a1c8f51 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_osx.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_recovery.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_recovery.png new file mode 100644 index 00000000..d9144a6c Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_recovery.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_restart.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_restart.png new file mode 100644 index 00000000..9c30c232 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_restart.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_shutdown.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_shutdown.png new file mode 100644 index 00000000..39b123f3 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_shutdown.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_ubuntu.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_ubuntu.png new file mode 100644 index 00000000..d1cda270 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_ubuntu.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows.png new file mode 100644 index 00000000..96e11c87 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows10.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows10.png new file mode 100644 index 00000000..0eabef70 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows10.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows7.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows7.png new file mode 100644 index 00000000..95d9e189 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows7.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows_metro.png b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows_metro.png new file mode 100644 index 00000000..7ace114e Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/hover_windows_metro.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/icons b/client/shared/lib/burg/themes/OpenGnsys/icons/icons new file mode 100644 index 00000000..15d5bec3 --- /dev/null +++ b/client/shared/lib/burg/themes/OpenGnsys/icons/icons @@ -0,0 +1,21 @@ ++class +{ + -opengnsys { image = "$$/normal_opengnsys.png:$$/hover_opengnsys.png" } + -windows10 { image = "$$/normal_windows10.png:$$/hover_windows10.png" } + -windows7 { image = "$$/normal_windows7.png:$$/hover_windows7.png" } + -windows { image = "$$/normal_windows.png:$$/hover_windows.png" } + -elementary { image = "$$/normal_elementary.png:$$/hover_elementary.png" } + -elementaryos { image = "$$/normal_elementary.png:$$/hover_elementary.png" } + -recovery { image = "$$/normal_recovery.png:$$/hover_recovery.png" } + -shutdown { image = "$$/normal_shutdown.png:$$/hover_shutdown.png" } + -restart { image = "$$/normal_restart.png:$$/hover_restart.png" } + -linux { image = "$$/normal_linux.png:$$/hover_linux.png" } + -ubuntu { image = "$$/normal_ubuntu.png:$$/hover_ubuntu.png" } + -debian { image = "$$/normal_debian.png:$$/hover_debian.png" } + -suse { image = "$$/normal_opensuse.png:$$/hover_opensuse.png" } + -freebsd { image = "$$/normal_freebsd.png:$$/hover_freebsd.png" } + -macosx { image = "$$/normal_osx.png:$$/hover_osx.png" } + -haiku { image = "$$/normal_haiku.png:$$/hover_haiku.png" } + -image { image = "$$/normal_os.png:$$/hover_os.png" } + -os { image = "$$/normal_os.png:$$/hover_os.png" } +} diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_debian.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_debian.png new file mode 100644 index 00000000..88b19a3f Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_debian.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_elementary.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_elementary.png new file mode 100644 index 00000000..31863eca Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_elementary.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_freebsd.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_freebsd.png new file mode 100644 index 00000000..1162e534 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_freebsd.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_haiku.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_haiku.png new file mode 100644 index 00000000..cab9bfd8 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_haiku.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_linux.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_linux.png new file mode 100644 index 00000000..8e215df0 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_linux.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_opengnsys.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_opengnsys.png new file mode 100644 index 00000000..687f1800 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_opengnsys.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_opensuse.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_opensuse.png new file mode 100644 index 00000000..6ab2c372 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_opensuse.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_os.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_os.png new file mode 100644 index 00000000..7d33f4d2 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_os.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_osx.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_osx.png new file mode 100644 index 00000000..5955b677 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_osx.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_recovery.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_recovery.png new file mode 100644 index 00000000..a1c6db34 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_recovery.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_restart.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_restart.png new file mode 100644 index 00000000..1f0e69f7 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_restart.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_shutdown.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_shutdown.png new file mode 100644 index 00000000..21766601 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_shutdown.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_ubuntu.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_ubuntu.png new file mode 100644 index 00000000..becf7799 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_ubuntu.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows.png new file mode 100644 index 00000000..9609364d Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows10.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows10.png new file mode 100644 index 00000000..8caf5c79 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows10.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows7.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows7.png new file mode 100644 index 00000000..34d50eb6 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows7.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows_metro.png b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows_metro.png new file mode 100644 index 00000000..8d4974eb Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/icons/normal_windows_metro.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/000-70opaque.png b/client/shared/lib/burg/themes/OpenGnsys/images/000-70opaque.png new file mode 100644 index 00000000..8f92c2fe Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/000-70opaque.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-bg.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-bg.png new file mode 100644 index 00000000..a3ee24e3 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-bg.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-bg.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-bg.png new file mode 100644 index 00000000..cd88d067 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-bg.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-l.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-l.png new file mode 100644 index 00000000..1a9a5163 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-l.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-r.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-r.png new file mode 100644 index 00000000..a8befbb5 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-hover-r.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-l.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-l.png new file mode 100644 index 00000000..34b3bf08 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-l.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-r.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-r.png new file mode 100644 index 00000000..0cb01e81 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-r.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-tools-hover.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-tools-hover.png new file mode 100644 index 00000000..a8c74b1f Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-tools-hover.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/button-tools.png b/client/shared/lib/burg/themes/OpenGnsys/images/button-tools.png new file mode 100644 index 00000000..1cef0557 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/button-tools.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-b.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-b.png new file mode 100644 index 00000000..54b59997 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-b.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-bg.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-bg.png new file mode 100644 index 00000000..9d1a6253 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-bg.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-bl.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-bl.png new file mode 100644 index 00000000..aaadeae9 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-bl.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-br.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-br.png new file mode 100644 index 00000000..eb2fbcb2 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-br.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-l.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-l.png new file mode 100644 index 00000000..d2bda89d Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-l.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-r.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-r.png new file mode 100644 index 00000000..741e2bad Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-r.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-t.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-t.png new file mode 100644 index 00000000..2ab4a00e Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-t.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-title-bg.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-bg.png new file mode 100644 index 00000000..e2693959 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-bg.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-title-l.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-l.png new file mode 100644 index 00000000..eb805223 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-l.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-title-r.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-r.png new file mode 100644 index 00000000..41958921 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-r.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-title-t.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-t.png new file mode 100644 index 00000000..6c56bf8e Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-t.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-title-tl.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-tl.png new file mode 100644 index 00000000..1d2ad5e5 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-tl.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-title-tr.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-tr.png new file mode 100644 index 00000000..dbd43df8 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-title-tr.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-tl.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-tl.png new file mode 100644 index 00000000..b12e7041 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-tl.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/container-tr.png b/client/shared/lib/burg/themes/OpenGnsys/images/container-tr.png new file mode 100644 index 00000000..92ed2661 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/container-tr.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-b.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-b.png new file mode 100644 index 00000000..7fdf4d34 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-b.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bg.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bg.png new file mode 100644 index 00000000..373414b6 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bg.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.png new file mode 100644 index 00000000..1ef93ff4 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.xcf b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.xcf new file mode 100644 index 00000000..e2b417d9 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-bl.xcf differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-br.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-br.png new file mode 100644 index 00000000..b8778394 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-br.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-lr.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-lr.png new file mode 100644 index 00000000..9ebb1ba1 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-lr.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-spacer.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-spacer.png new file mode 100644 index 00000000..e96e6642 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-spacer.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-t.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-t.png new file mode 100644 index 00000000..05720e68 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-t.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-tl.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-tl.png new file mode 100644 index 00000000..d9554e67 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-tl.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/dialog-tr.png b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-tr.png new file mode 100644 index 00000000..9d4123e4 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/dialog-tr.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-b.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-b.png new file mode 100644 index 00000000..c8295bb4 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-b.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-bl.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-bl.png new file mode 100644 index 00000000..18542290 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-bl.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-br.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-br.png new file mode 100644 index 00000000..ff8871c7 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-br.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-l.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-l.png new file mode 100644 index 00000000..3a4fc40a Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-l.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-r.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-r.png new file mode 100644 index 00000000..dadd4ac5 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-r.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-t.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-t.png new file mode 100644 index 00000000..cd994856 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-t.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tl.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tl.png new file mode 100644 index 00000000..8341760d Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tl.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tr.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tr.png new file mode 100644 index 00000000..72a05f67 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg-tr.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg.png b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg.png new file mode 100644 index 00000000..92db1e08 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/progressbar-bg.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/text-line-l.png b/client/shared/lib/burg/themes/OpenGnsys/images/text-line-l.png new file mode 100644 index 00000000..ed1852c6 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/text-line-l.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/text-line-r.png b/client/shared/lib/burg/themes/OpenGnsys/images/text-line-r.png new file mode 100644 index 00000000..5c9f49ab Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/text-line-r.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/tick.png b/client/shared/lib/burg/themes/OpenGnsys/images/tick.png new file mode 100644 index 00000000..292ceb88 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/tick.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/txt-about.png b/client/shared/lib/burg/themes/OpenGnsys/images/txt-about.png new file mode 100644 index 00000000..f104c821 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/txt-about.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/txt-help.png b/client/shared/lib/burg/themes/OpenGnsys/images/txt-help.png new file mode 100644 index 00000000..6fad7720 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/txt-help.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/txt-select.png b/client/shared/lib/burg/themes/OpenGnsys/images/txt-select.png new file mode 100644 index 00000000..d459597a Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/txt-select.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/txt-tools.png b/client/shared/lib/burg/themes/OpenGnsys/images/txt-tools.png new file mode 100644 index 00000000..d8eadd70 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/txt-tools.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/images/ubuntu-glow-96.png b/client/shared/lib/burg/themes/OpenGnsys/images/ubuntu-glow-96.png new file mode 100644 index 00000000..b8fd92c8 Binary files /dev/null and b/client/shared/lib/burg/themes/OpenGnsys/images/ubuntu-glow-96.png differ diff --git a/client/shared/lib/burg/themes/OpenGnsys/menus b/client/shared/lib/burg/themes/OpenGnsys/menus new file mode 100644 index 00000000..f9a13fd6 --- /dev/null +++ b/client/shared/lib/burg/themes/OpenGnsys/menus @@ -0,0 +1,188 @@ +tools_menu { + panel { + class = overlay + + panel { + attach_hcenter = 0 + attach_vcenter = 0 + width = 30 + + panel { + class = dialog-title + image { image = "$$/images/txt-tools.png" attach_left = 0 } + } + + panel { + class = dialog-body + + text { class = br } + + text { + text = "Toggle Mode" + command = "menu_toggle_mode" + class = text-menu-item + } + text { + text="Terminal" + command = "menu_popup term_window" + class = text-menu-item + } + text { + text = "Restart" + command = reboot + class = text-menu-item + } + text { + text = "Shutdown" + command = halt + class = text-menu-item + } + text { + text = "Help" + command = "menu_popup help" + class = text-menu-item + } + text { + text = "About" + command = "menu_popup about" + class = text-menu-item + } + } + } + } +} + +about { + panel { + class = overlay + + panel { + attach_hcenter = 0 + attach_vcenter = 0 + margin_left = 2 + width = 60 + + panel { + class = dialog-title + image { image = "$$/images/txt-about.png" attach_left = 0 } + } + + panel { + class = dialog-body + + text { class = br } + text { text = "Darkness" class = "dialog-text" } + text { class = br } + text { text = "Designed & Created by LuxieRayku(luksi.reiku@gmail.com)" class = "dialog-text" } + text { text = "Darkness theme is designed to feel clean," class = "dialog-text" } + text { text = "light, modern & minimal." class = dialog-text } + text { class = br } + + panel { + halign = center + class = button + command = true + + text { text = OK class = button-text } + } + } + } + } +} + +help { + panel { + class = overlay + + panel { + attach_hcenter = 0 + attach_vcenter = 0 + margin_left = 2 + width = 48 + + panel { + class = dialog-title + image { image = "$$/images/txt-help.png" attach_left = 0 } + } + + panel { + class = dialog-body + + text { text = "F1/h - Help" class = dialog-text } + text { text = "F2/t - Change theme" class = dialog-text } + text { text = "F3/r - Change resolution" class = dialog-text } + text { text = "F5/ctrl-x - Finish edit" class = dialog-text } + text { text = "F6 - Next window" class = dialog-text } + text { text = "F7 - Show folded items" class = dialog-text } + text { text = "F8 - Toggle between text and graphic mode" class = dialog-text } + text { text = "F9 - Shutdown" class = dialog-text } + text { text = "F10 - Reboot" class = dialog-text } + text { text = "f - Toggle between folded and unfolded mode" class = dialog-text } + text { text = "c - Open terminal" class = dialog-text } + text { text = "2 - Open two terminals" class = dialog-text } + text { text = "e - Edit current command" class = dialog-text } + text { text = "q - Quit graphic mode" class = dialog-text } + text { text = "i - Show theme information" class = dialog-text } + text { text = "n - Next item with the same class" class = dialog-text } + text { text = "w - Next windows item" class = dialog-text } + text { text = "u - Next ubuntu item" class = dialog-text } + text { text = "ESC - Exit from window or menu" class = dialog-text } + + panel { + halign = center + class = button + command = true + + text { text = OK class = button-text } + } + } + } + } +} + +term_window { + panel { + class = terminal + width = 100% + height = 100% + term { + width=100% + height=100% + } + } +} + +two_term { + panel { + width = 100% + height = 100% + direction = left_to_right + + panel { + class = terminal + extend = 1 + + term { + width=100% + height=100% + } + } + + panel { + class = terminal + extend = 1 + + term { + width=100% + height=100% + } + } + } +} +/*menu { + Shutdown { + class = "shutdown" + group = "group_main" + command = "halt" + } +}*/ diff --git a/client/shared/lib/burg/themes/OpenGnsys/style b/client/shared/lib/burg/themes/OpenGnsys/style new file mode 100644 index 00000000..325e503b --- /dev/null +++ b/client/shared/lib/burg/themes/OpenGnsys/style @@ -0,0 +1,158 @@ ++class { + ### Default Elements ### + screen { + background = "#250040" + } + + text { + color = "#4d0085:#ffffff" + font = "Sans Bold 16" + } + + progressbar { + width = 80% + height = 4/1 + color = "#ffffff:#4d0085" + } + + edit { + color = "white" + } + + password { + color = "white" + } + + term { + color = "white" + } + + ### Text Styles ### + br { + text = "- " + font = "Sans Bold 16" + } + + text-menu-item { + color = "white" + font = "Sans Bold 16" + } + + dialog-title-text { + halign = center + color = "black" + } + + dialog-text { + color = "white" + font = "Sans Bold 16" + } + + button-text { + font = "Sans Bold 16" + color = "white" + } + + ### Panel Styles ### + text-line { + left = ",,,#0x0020:$$/images/text-line-l.png" + background = ",,,#0x0020:$$/images/dialog-bg.png" + right = ",,,#0x0020:$$/images/text-line-r.png" + } + + button { + left = "$$/images/button-l.png:$$/images/button-hover-l.png" + background = "$$/images/button-bg.png:$$/images/button-hover-bg.png" + right = "$$/images/button-r.png:$$/images/button-hover-r.png" + margin_left = 2 + margin_right = 2 + margin_top = 3/0 + margin_bottom = 3/0 + } + + terminal { + top_left = ",,light-gray/black,#0x2554:,,white/black,#0x250F" + top = ",,light-gray/black,#0x2550:,tiling,white/black,#0x2501" + top_right = ",,light-gray/black,#0x2557:,,white/black,#0x2513" + left = ",,light-gray/black,#0x2551:,tiling,white/black,#0x2503" + background="$$/images/000-70opaque.png" + right = ",,light-gray/black,#0x2551:,tiling,white/black,#0x2503" + bottom_left = ",,light-gray/black,#0x255A:,,white/black,#0x2517" + bottom = ",,light-gray/black,#0x2550:,tiling,white/black,#0x2501" + bottom_right = ",,light-gray/black,#0x255D:,tiling,white/black,#0x251B" + } + + progressbar-background { + top_left = "$$/images/progressbar-bg-tl.png" + top = "$$/images/progressbar-bg-t.png" + top_right = "$$/images/progressbar-bg-tr.png" + left = "$$/images/progressbar-bg-l.png" + background = "$$/images/progressbar-bg.png" + right = "$$/images/progressbar-bg-r.png" + bottom_left = "$$/images/progressbar-bg-bl.png" + bottom = "$$/images/progressbar-bg-b.png" + bottom_right = "$$/images/progressbar-bg-br.png" + } + + + dialog { + top_left = "$$/images/dialog-tl.png" + top = "$$/images/dialog-t.png" + top_right = "$$/images/dialog-tr.png" + left = "$$/images/dialog-lr.png" + background = "$$/images/dialog-bg.png" + right = "$$/images/dialog-lr.png" + bottom_left = "$$/images/dialog-bl.png" + bottom = "$$/images/dialog-b.png" + bottom_right = "$$/images/dialog-br.png" + } + + dialog-title { + top_left = "$$/images/dialog-tl.png" + top = "$$/images/dialog-t.png" + top_right = "$$/images/dialog-tr.png" + left = "$$/images/dialog-lr.png" + background = "$$/images/dialog-bg.png" + right = "$$/images/dialog-lr.png" + bottom_left = "$$/images/dialog-spacer.png" + bottom = "$$/images/dialog-spacer.png" + bottom_right = "$$/images/dialog-spacer.png" + } + + dialog-body { + left = "$$/images/dialog-lr.png" + background = "$$/images/dialog-bg.png" + right = "$$/images/dialog-lr.png" + bottom_left = "$$/images/dialog-bl.png" + bottom = "$$/images/dialog-b.png" + bottom_right = "$$/images/dialog-br.png" + } + +# container-title { +# top_left = "$$/images/container-title-tl.png" +# top = "$$/images/container-title-t.png" +# top_right = "$$/images/container-title-tr.png" +# left = "$$/images/container-title-l.png" +# background = "$$/images/container-title-bg.png" +# right = "$$/images/container-title-r.png" +# } + + container-body { + top_left = "$$/images/container-tl.png" + top = "$$/images/container-t.png" + top_right = "$$/images/container-tr.png" + left = "$$/images/container-l.png" + background = "$$/images/container-bg.png" + right = "$$/images/container-r.png" + bottom_left = "$$/images/container-bl.png" + bottom = "$$/images/container-b.png" + bottom_right = "$$/images/container-br.png" + } + + overlay { + height = 100% + width = 100% + absolute = 1 + background="$$/images/000-70opaque.png" + } +} diff --git a/client/shared/lib/burg/themes/OpenGnsys/theme b/client/shared/lib/burg/themes/OpenGnsys/theme new file mode 100644 index 00000000..4307c18b --- /dev/null +++ b/client/shared/lib/burg/themes/OpenGnsys/theme @@ -0,0 +1,231 @@ +include "menus" +include "../icons/hover" +include "icons/icons" +include "style" + +screen { + background = "$$/background.png" + + panel { + halign = center + attach_vcenter = 0 + height = 19 + # Flip so the cursor defaults to the main menu + direction = bottom_to_top + + ### Main Menu ### + panel { + min_width = 36 + class = container-body + height = 14 +# margin_top = 0 + max_width = 128 + + panel { + halign = center + + space = 0 + direction = left_to_right + anchor = 1 + id = __menu__ + popup = bottom + } + } + + panel { + halign = center + height = 4 + min_width = 36 + class = container-title + + space = 0 + direction = left_to_right + anchor = 1 + + image { + halign=center + image = "$$/images/txt-select.png" + attach_top = 2 + attach_left = 2 + } + + ### Tools Menu ### +# image { +# attach_right = 2 +# image = "$$/images/button-tools.png:$$/images/button-tools-hover.png" +# command = "menu_popup tools_menu" +# } + } + } + + ### Progress Bar ### + panel { + halign = center + attach_bottom = 4 + width = 60 + class = progressbar-background + id = __timeout__ + + progressbar { } + } +} + +template_menuitem { + panel { + width = 20 + height = 10 + + parameters = "class=image.class:title=panel.text.text" + + ### Icon ### + image { + attach_vcenter = 0 + attach_hcenter = 0 + } + + ### Text ### +# panel { +# attach_vcenter = 0 +# attach_hcenter = 0 +# margin_left = 1 +# margin_right = 1 +# class = text-line +# text {} +# } + } +} + +template_submenu { + panel { + class = dialog + } +} + +template_subitem { + panel { + parameters = "title=text.text" + text {} + } +} + +template_popup { + panel { + attach_hcenter = 0 + attach_vcenter = 0 + class = dialog + } +} + +dialog_line { + panel { + parameters = "text=edit.text" + class = dialog + width = 60 + attach_hcenter = 0 + attach_vcenter = 0 + + edit { + lines = 1 + max_lines = 1 + } + } +} + +dialog_edit { + panel { + parameters = "text=edit.text" + class = dialog + width = 90 + attach_hcenter = 0 + attach_vcenter = 0 + + edit { + lines = 10 + } + } +} + +dialog_message { + panel { + parameters = "text=text.text" + class = dialog + margin_size = 1 + margin_bottom = 0 + space = 1 + attach_hcenter = 0 + attach_vcenter = 0 + text {} + panel { + class = button + command = true + halign = center + text { text = OK class = button-text } + } + } +} + +dialog_password { + panel { + parameters = "username=__user__.text:password=__pass__.text" + class = dialog + margin_size = 1 + margin_bottom = 0 + attach_hcenter = 0 + attach_vcenter = 0 + + panel { + direction = left_to_right + space = 1 + text { + extend = 1 + valign = center + text = Username + } + + panel { + margin_left = 1 + margin_right = 1 + edit { + id = __user__ + max_lines = 1 + } + } + } + + panel { + direction = left_to_right + space = 1 + text { + extend = 1 + valign = center + text = Password + } + panel { + margin_left = 1 + margin_right = 1 + password { + id = __pass__ + } + } + } + + panel { + class = button + command = true + halign = center + margin_left = 1 + margin_right = 1 + text { + text = OK + class = button-text + } + } + } +} +menu { + +# Shutdown { +# command = "halt" +# class = "shutdown" +# } +} diff --git a/client/shared/lib/engine/tests/Modify/Cache.shtest b/client/shared/lib/engine/tests/Modify/Cache.shtest index b449a80c..de7ab669 100644 --- a/client/shared/lib/engine/tests/Modify/Cache.shtest +++ b/client/shared/lib/engine/tests/Modify/Cache.shtest @@ -14,7 +14,7 @@ $ AUX=$(ogListPartitions 1) ; echo ${AUX##*CACHE:} | sed s/\ .*\$//g # Comprobamos que no esta formateada $ ogCheckFs 1 4 -OpenGnSys error: ogCheckFs: "1, 4, CACHE" +OpenGnsys error: ogCheckFs: "1, 4, CACHE" $ ogFormatCache|tail -1 ReiserFS is successfully created on /dev/sda4. @@ -60,13 +60,13 @@ $ rm $OGCAC$OGIMG/lll Comprobamos los errores de las entradas de datos ================================================ $ ogCreateCache -OpenGnSys error: ogCreateCache: "" +OpenGnsys error: ogCreateCache: "" $ ogCreateCache -1 -OpenGnSys error: ogCreateCache: "-1" +OpenGnsys error: ogCreateCache: "-1" $ ogCreateCache 0 -OpenGnSys error: ogCreateCache: "0" +OpenGnsys error: ogCreateCache: "0" # cuando se está usando la cuarta partitión no debe crearse la cache #$ ogCreatePartition 1 NTFS:200000 EXT3:2000000 EXT3:2000000 NTFS:30000000 diff --git a/client/shared/lib/engine/tests/NoModify/Lock1.shtest b/client/shared/lib/engine/tests/NoModify/Lock1.shtest index 39bac3eb..eb4ead75 100644 --- a/client/shared/lib/engine/tests/NoModify/Lock1.shtest +++ b/client/shared/lib/engine/tests/NoModify/Lock1.shtest @@ -33,7 +33,7 @@ $ ogUnmount 1 1 >/dev/null 2>&1 $ ogLock 1 1 $ ogCheckFs 1 1 -OpenGnSys error: ogCheckFs: "1 1" +OpenGnsys error: ogCheckFs: "1 1" $ ogUnlock 1 1 @@ -70,16 +70,16 @@ $ rm $OGIMG/_test_.* # Comprobando los errores (FALTA) $ ogLock -OpenGnSys error: ogLockPartition: "" +OpenGnsys error: ogLockPartition: "" $ ogLock 1 10 -OpenGnSys error: ogDiskToDev: "" +OpenGnsys error: ogDiskToDev: "" $ ogIsLocked -OpenGnSys error: ogIsLocked: "" +OpenGnsys error: ogIsLocked: "" $ ogIsLocked 1 10 -OpenGnSys error: ogDiskToDev: "" +OpenGnsys error: ogDiskToDev: "" diff --git a/client/shared/lib/engine/tests/crearTestLock2 b/client/shared/lib/engine/tests/crearTestLock2 index 49e3604d..c3ac2cde 100755 --- a/client/shared/lib/engine/tests/crearTestLock2 +++ b/client/shared/lib/engine/tests/crearTestLock2 @@ -29,11 +29,11 @@ $ ogUnmountAll 1 2>/dev/null $ ogLock 1 1 $ ogExtendFs 1 1 -OpenGnSys error: ogExtendFs: "1 1" +OpenGnsys error: ogExtendFs: "1 1" $ ogFormatFs 1 1 -OpenGnSys error: ogFormatFs: "1 1" +OpenGnsys error: ogFormatFs: "1 1" ############################################################################# # Los dos comandos siguientes dan error. Los comentamos por ahora diff --git a/client/shared/lib/httpd/httpd-log.sh b/client/shared/lib/httpd/httpd-log.sh index d357a6ed..4dce863f 100755 --- a/client/shared/lib/httpd/httpd-log.sh +++ b/client/shared/lib/httpd/httpd-log.sh @@ -1,13 +1,12 @@ - #!/bin/bash + echo "Content-type: text/html" echo "" -#echo "Bash as CGI" echo "<html><head><title>OpenGnsys Client" echo " " echo "" -echo "

$(./httpd-runengine.sh 'ogEcho $MSG_HTTPLOG_NOUSE' ) .
host $(hostname -s)

" +echo "

$(./httpd-runengine.sh 'ogEcho $MSG_HTTPLOG_NOUSE').
host $(hostname -s)

" echo " " echo "
" diff --git a/client/shared/lib/httpd/httpd-runengine.sh b/client/shared/lib/httpd/httpd-runengine.sh index aa145078..a3fc3e66 100755 --- a/client/shared/lib/httpd/httpd-runengine.sh +++ b/client/shared/lib/httpd/httpd-runengine.sh @@ -1,3 +1,4 @@ +#!/bin/bash # Exportar parámetros del kernel. for i in $(cat /proc/cmdline); do diff --git a/client/shared/lib/locale/ca/LC_MESSAGES/browser.mo b/client/shared/lib/locale/ca/LC_MESSAGES/browser.mo new file mode 100644 index 00000000..eda51ffb Binary files /dev/null and b/client/shared/lib/locale/ca/LC_MESSAGES/browser.mo differ diff --git a/client/shared/lib/locale/en/LC_MESSAGES/browser.mo b/client/shared/lib/locale/en/LC_MESSAGES/browser.mo new file mode 100644 index 00000000..9ac0ebbe Binary files /dev/null and b/client/shared/lib/locale/en/LC_MESSAGES/browser.mo differ diff --git a/client/shared/lib/os-probes/10zvol-test b/client/shared/lib/os-probes/10zvol-test new file mode 100755 index 00000000..cdbe7a5f --- /dev/null +++ b/client/shared/lib/os-probes/10zvol-test @@ -0,0 +1,14 @@ +#!/bin/sh +# Sub-test to exclude ZVOLs +set -e +partition="$1" + +. /usr/share/os-prober/common.sh + +if [ "$(stat -L -c %t "$partition")" = "e6" ] ; then + debug "$1 is a ZVOL; skipping" + exit 0 +fi + +# No ZVOLs found +exit 1 diff --git a/client/shared/lib/os-probes/50mounted-tests b/client/shared/lib/os-probes/50mounted-tests new file mode 100755 index 00000000..6f4d7afd --- /dev/null +++ b/client/shared/lib/os-probes/50mounted-tests @@ -0,0 +1,99 @@ +#!/bin/sh +# Sub-tests that require a mounted partition. +set -e +partition="$1" + +. /usr/share/os-prober/common.sh + +types="$(fs_type "$partition")" || types=NOT-DETECTED +if [ "$types" = NOT-DETECTED ] || [ -z "$types" ]; then + debug "$1 type not recognised; skipping" + exit 0 +elif [ "$types" = swap ]; then + debug "$1 is a swap partition; skipping" + exit 0 +elif [ "$types" = LVM2_member ]; then + debug "$1 is a LVM member partition; skipping" + exit 0 +elif [ "$types" = crypto_LUKS ]; then + debug "$1 is a LUKS partition; skipping" + exit 0 +elif [ "$types" = ntfs ]; then + if type ntfs-3g >/dev/null 2>&1; then + types='ntfs-3g ntfs' + fi +elif [ -z "$types" ]; then + if type cryptsetup >/dev/null 2>&1 && \ + cryptsetup luksDump "$partition" >/dev/null 2>&1; then + debug "$1 is a LUKS partition; skipping" + exit 0 + fi + for type in $(grep -v nodev /proc/filesystems); do + # hfsplus filesystems are mountable as hfs. Try hfs last so + # that we can tell the difference. + if [ "$type" = hfs ]; then + delaytypes="${delaytypes:+$delaytypes }$type" + elif [ "$type" = fuseblk ]; then + if type ntfs-3g >/dev/null 2>&1; then + types="${types:+$types }ntfs-3g" + fi + else + types="${types:+$types }$type" + fi + done +fi + +tmpmnt=/var/lib/os-prober/mount +if [ ! -d "$tmpmnt" ]; then + mkdir "$tmpmnt" +fi + +mounted= +if type grub-mount >/dev/null 2>&1 && \ + type grub-probe >/dev/null 2>&1 && \ + grub-mount "$partition" "$tmpmnt" 2>/dev/null; then + mounted=1 + type="$(grub-probe -d "$partition" -t fs)" || true + if [ "$type" ]; then + debug "mounted using GRUB $type filesystem driver" + else + debug "mounted using GRUB, but unknown filesystem?" + type=fuseblk + fi +else + echo "Failed to probe $partition for filesystem type" >&2 + exit 1 +fi + +if [ "$mounted" ]; then + for test in /usr/lib/os-probes/mounted/*; do + debug "running subtest $test" + if [ -f "$test" ] && [ -x "$test" ]; then + if "$test" "$partition" "$tmpmnt" "$type"; then + debug "os found by subtest $test" + if ! umount "$tmpmnt"; then + warn "failed to umount $tmpmnt" + fi + case "$type" in + btrfs) + # umount to account for the bind-mount + if [ -x "$tmpmnt/@/lib" ] && \ + ! umount $tmpmnt; then + warn "failed to umount $tmpmnt" + fi + ;; + esac + rmdir "$tmpmnt" || true + exit 0 + fi + fi + done + if ! umount "$tmpmnt"; then + warn "failed to umount $tmpmnt" + fi +fi + +rmdir "$tmpmnt" || true + +# No tests found anything. +exit 1 diff --git a/client/shared/lib/os-probes/init/10filesystems b/client/shared/lib/os-probes/init/10filesystems new file mode 100755 index 00000000..f50e55ed --- /dev/null +++ b/client/shared/lib/os-probes/init/10filesystems @@ -0,0 +1,39 @@ +#!/bin/sh +# Make sure filesystems are available. +set +e # ignore errors from modprobe + +FILESYSTEMS='ext2 ext3 ext4 xfs jfs msdos vfat ntfs minix hfs hfsplus qnx4 ufs btrfs' +# fuse is needed to make grub-mount work. +FILESYSTEMS="$FILESYSTEMS fuse" +# The Ubuntu kernel udebs put a number of filesystem modules in +# fs-{core,secondary}-modules. It's fairly cheap to check for these too. +FILESYSTEMS="$FILESYSTEMS fs-core fs-secondary" + +if [ ! -e /var/lib/os-prober/modules ]; then + # Check for anna-install to make it easier to use os-prober outside + # d-i. + if type anna-install >/dev/null 2>&1 && [ -d /lib/debian-installer ]; then + for fs in $FILESYSTEMS; do + ANNA_QUIET=1 DEBIAN_FRONTEND=none \ + log-output -t os-prober \ + anna-install "$fs-modules" || true + done + depmod -a >/dev/null 2>&1 || true + fi + + for fs in $FILESYSTEMS; do + case "$fs" in + fs-*) + ;; + *) + modprobe "$fs" 2>/dev/null | logger -t os-prober + ;; + esac + done + + # We only want to keep this state inside d-i, so this is as good a + # check as any. + if type anna-install >/dev/null 2>&1 && [ -d /lib/debian-installer ]; then + touch /var/lib/os-prober/modules + fi +fi diff --git a/client/shared/lib/os-probes/mounted/05efi b/client/shared/lib/os-probes/mounted/05efi new file mode 100755 index 00000000..93309ce3 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/05efi @@ -0,0 +1,71 @@ +#!/bin/sh +# Detects all Microsoft OSes on a collection of partitions. + +. /usr/share/os-prober/common.sh + +partition="$1" +mpoint="$2" +type="$3" + +# This file is for UEFI platform only +if [ ! -d /sys/firmware/efi ] || [ -f /var/lib/partman/ignore_uefi ]; then + debug "Not on UEFI platform" + exit 1 +fi + +# Weed out stuff that doesn't apply to us +case "$type" in + vfat) debug "$1 is a FAT32 partition" ;; + msdos) debug "$1 is a FAT16 partition" ;; + fat) debug "$1 is a FAT partition (mounted by GRUB)" ;; + *) debug "$1 is $type partition: exiting"; exit 1 ;; +esac + +if type udevadm > /dev/null 2>&1; then + udevinfo () { + udevadm info "$@" + } +fi + +if type udevinfo > /dev/null 2>&1; then + # Skip virtual devices + if udevinfo -q path -n $partition | grep -q /virtual/; then + debug "$1 is virtual device: exiting" + exit 1 + fi + + eval "$(udevinfo -q property -n "$partition" | grep -E '^ID_PART_ENTRY_(TYPE|SCHEME)=')" + debug "$partition partition scheme is $ID_PART_ENTRY_SCHEME" + debug "$partition partition type is $ID_PART_ENTRY_TYPE" + + if [ -z "$ID_PART_ENTRY_TYPE" -o -z "$ID_PART_ENTRY_SCHEME" -o \ + \( "$ID_PART_ENTRY_SCHEME" != gpt -a "$ID_PART_ENTRY_SCHEME" != msdos \) -o \ + \( "$ID_PART_ENTRY_SCHEME" = gpt -a "$ID_PART_ENTRY_TYPE" != c12a7328-f81f-11d2-ba4b-00a0c93ec93b \) -o \ + \( "$ID_PART_ENTRY_SCHEME" = msdos -a "$ID_PART_ENTRY_TYPE" != 0xef \) ]; then + debug "$partition is not a ESP partition: exiting" + exit 1 + fi +else + debug "udevinfo and udevadm missing - cannot check partition type" +fi + +efi=$(item_in_dir efi "$mpoint") +if [ -z "$efi" ]; then + debug "$mpoint does not have /EFI directory: exiting" + exit 1 +fi + +ret=1 +for test in /usr/lib/os-probes/mounted/efi/*; do + debug "running subtest $test" + if [ -f "$test" ] && [ -x "$test" ]; then + entry=$("$test" "$mpoint/$efi") + if [ -n "$entry" ]; then + debug "bootloader $entry found by subtest $test" + ret=0 + result "${partition}@/$efi/${entry}:efi" + fi + fi +done + +exit $ret diff --git a/client/shared/lib/os-probes/mounted/10freedos b/client/shared/lib/os-probes/mounted/10freedos new file mode 100755 index 00000000..94388f30 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/10freedos @@ -0,0 +1,23 @@ +#!/bin/sh + +. /usr/share/os-prober/common.sh + +partition="$1" +mpoint="$2" +type="$3" + +# Weed out stuff that doesn't apply to us +case "$type" in + vfat) debug "$1 is a FAT32 partition" ;; + msdos) debug "$1 is a FAT16 partition" ;; + fat) debug "$1 is a FAT partition (mounted by GRUB)" ;; + *) debug "$1 is not a FAT partition: exiting"; exit 1 ;; +esac + +if item_in_dir -q kernel.sys "$2" && item_in_dir -q command.com "$2"; then + label="$(count_next_label FreeDOS)" + result "$1:FreeDOS:$label:chain" + exit 0 +else + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/10qnx b/client/shared/lib/os-probes/mounted/10qnx new file mode 100755 index 00000000..8d40398f --- /dev/null +++ b/client/shared/lib/os-probes/mounted/10qnx @@ -0,0 +1,21 @@ +#!/bin/sh + +. /usr/share/os-prober/common.sh + +partition="$1" +mpoint="$2" +type="$3" + +# Weed out stuff that doesn't apply to us +case "$type" in + qnx4) debug "$partition is a QNX4 partition" ;; + *) debug "$partition is not a QNX4 partition: exiting"; exit 1 ;; +esac + +if [ -e "$mpoint/.boot" ]; then + label="$(count_next_label QNX)" + result "$partition:QNX:$label:chain" + exit 0 +else + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/20macosx b/client/shared/lib/os-probes/mounted/20macosx new file mode 100755 index 00000000..dd4207fe --- /dev/null +++ b/client/shared/lib/os-probes/mounted/20macosx @@ -0,0 +1,30 @@ +#!/bin/sh -e +# Detects Mac OS X. I don't yet know how Mac OS <= 9 fits into this. +. /usr/share/os-prober/common.sh + +partition="$1" +mpoint="$2" +type="$3" + +debug() { + logger -t macosx-prober "debug: $@" +} + +# Weed out stuff that doesn't apply to us +case "$type" in + hfsplus) debug "$1 is an HFS+ partition" ;; + *) debug "$1 is not an HFS+ partition: exiting"; exit 1 ;; +esac + +# Could use a better test than this. +# /System/Library/CoreServices/SystemVersion.plist has version information, +# but I don't think it exists on Mac OS <= 9, and it's XML so parsing in +# shell will be nasty. + +if [ -e "$2/mach_kernel" ]; then + label="$(count_next_label MacOSX)" + result "$1:Mac OS X:$label:macosx" + exit 0 +else + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/20microsoft b/client/shared/lib/os-probes/mounted/20microsoft new file mode 100755 index 00000000..65b38bfe --- /dev/null +++ b/client/shared/lib/os-probes/mounted/20microsoft @@ -0,0 +1,140 @@ +#!/bin/sh +# Detects all Microsoft OSes on a collection of partitions. + +. /usr/share/os-prober/common.sh + +partition="$1" +mpoint="$2" +type="$3" + +# This script looks for legacy BIOS bootloaders only. Skip if running UEFI +if [ -d /sys/firmware/efi ] && [ ! -f /var/lib/partman/ignore_uefi ] && [ -z "$WINOSDATA" ]; then + debug "Skipping legacy bootloaders on UEFI system" + exit 1 +fi + +# Weed out stuff that doesn't apply to us +case "$type" in + ntfs|ntfs-3g) debug "$1 is a NTFS partition" ;; + vfat) debug "$1 is a FAT32 partition" ;; + msdos) debug "$1 is a FAT16 partition" ;; + fat) debug "$1 is a FAT partition (mounted by GRUB)" ;; + fuse|fuseblk) debug "$1 is a FUSE partition" ;; # might be ntfs-3g + *) debug "$1 is not a MS partition: exiting"; exit 1 ;; +esac + +found= +# Vista (previously Longhorn) +if item_in_dir -q bootmgr "$2"; then + # there might be different boot directories in different case as: + # boot Boot BOOT + for boot in $(item_in_dir boot "$2"); do + bcd=$(item_in_dir bcd "$2/$boot") + if [ -n "$bcd" ]; then + if grep -aqs "W.i.n.d.o.w.s. .1.0" "$2/$boot/$bcd"; then + long="Windows 10 (loader)" + elif grep -aqs "W.i.n.d.o.w.s. .8" "$2/$boot/$bcd"; then + long="Windows 8 (loader)" + elif grep -aqs "W.i.n.d.o.w.s. .7" "$2/$boot/$bcd"; then + long="Windows 7 (loader)" + elif grep -aqs "W.i.n.d.o.w.s. .V.i.s.t.a" "$2/$boot/$bcd"; then + long="Windows Vista (loader)" + elif grep -aqs "W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8. .R.2." "$2/$boot/$bcd"; then + long="Windows Server 2008 R2 (loader)" + elif grep -aqs "W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8." "$2/$boot/$bcd"; then + long="Windows Server 2008 (loader)" + elif grep -aqs "W.i.n.d.o.w.s. .R.e.c.o.v.e.r.y. .E.n.v.i.r.o.n.m.e.n.t" "$2/$boot/$bcd"; then + long="Windows Recovery Environment (loader)" + elif grep -aqs "W.i.n.d.o.w.s. .S.e.t.u.p" "$2/$boot/$bcd"; then + long="Windows Recovery Environment (loader)" + else + long="Windows Vista (loader)" + fi + short=Windows + + found=true + + break + fi + done +fi + +# 2000/XP/NT4.0 +if [ -z "$found" ] && item_in_dir -q ntldr "$2" && item_in_dir -q ntdetect.com "$2"; then + long="Windows NT/2000/XP" + short=Windows + ini=$(item_in_dir boot.ini "$2") + if [ -n "$ini" ]; then + multicount="$(grep -e "^multi" "$2/$ini" | wc -l)" + scsicount="$(grep -e "^scsi" "$2/$ini" | wc -l)" + msoscount="$(expr "${multicount}" + "${scsicount}")" + if [ "$msoscount" -eq 1 ]; then + # We need to remove a Carriage Return at the end of + # the line... + defaultmspart="$(grep -e "^default=" "$2/$ini" | cut -d '=' -f2 | tr -d '\r')" + # Escape any backslashes in defaultmspart + grepexp="^$(echo "$defaultmspart" | sed -e 's/\\/\\\\/')=" + # Colons not allowed; replace by spaces + # Accented characters (non UTF-8) cause debconf to + # hang, so we fall back to the default if the name + # contains any weird characters. + long="$(grep -e "$grepexp" "$2/$ini" | cut -d '"' -f2 | \ + tr ':' ' ' | LC_ALL=C grep -v '[^a-zA-Z0-9 &()/_-]')" + if [ -z "$long" ]; then + long="Windows NT/2000/XP" + fi + else + long="Windows NT/2000/XP (loader)" + fi + + found=true + fi +fi + +# MS-DOS +if [ -z "$found" ] && item_in_dir -q dos "$2"; then + long="MS-DOS 5.x/6.x/Win3.1" + short=MS-DOS + + found=true +fi + +# 95/98/Me +if [ -z "$found" ] && item_in_dir -q windows "$2" && + item_in_dir -q win.com "$2"/"$(item_in_dir windows "$2")"; then + long="Windows 95/98/Me" + short=Windows9xMe + + found=true +fi + + +# Restrict to partitions containing the OS +if [ -n "$WINOSDATA" ]; then + found= + if [ -d "$2/ProgramData/Microsoft/Windows/Start Menu/Programs/StartUp" ]; then + long=${long:-"Windows 8 (data)"} + short=${short:-"Windows"} + found=true + elif [ -d "$2/ProgramData/Microsoft/Windows/Start Menu/Programs/Startup" ]; then + long=${long:-"Windows 7 (data)"} + short=${short:-"Windows"} + found=true + elif [ -d "$2/Documents and Settings/All Users/Start Menu/Programs/Startup" ]; then + long=${long:-"Windows XP/Vista (data)"} + short=${short:-"Windows"} + found=true + elif [ -d "$2/Winnt/Profiles/All Users/Start Menu/Programs/Startup" ]; then + long=${long:-"Windows NT (data)"} + short=${short:-"Windows"} + found=true + fi +fi + +if [ -z "$found" ]; then + exit 1 +fi + +label="$(count_next_label "$short")" +result "${partition}:${long}:${label}:chain" +exit 0 diff --git a/client/shared/lib/os-probes/mounted/30utility b/client/shared/lib/os-probes/mounted/30utility new file mode 100755 index 00000000..af48d307 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/30utility @@ -0,0 +1,33 @@ +#!/bin/sh +# Detects utility (hw vendor recovery) partitions. + +. /usr/share/os-prober/common.sh + +partition="$1" +mpoint="$2" +type="$3" + +# Weed out stuff that doesn't apply to us +case "$type" in + vfat) debug "$1 is a FAT32 partition" ;; + msdos) debug "$1 is a FAT16 partition" ;; + fat) debug "$1 is a FAT partition (mounted by GRUB)" ;; + *) debug "$1 is not a FAT partition: exiting"; exit 1 ;; +esac + +# Dell Utility partitions have partition type 0xde, but no idea how to +# cleanly detect that from shell +if item_in_dir -q dellbio.bin "$2" && \ + (item_in_dir -q delldiag.exe "$2" || item_in_dir -q delldiag.com "$2"); then + long="Dell Utility Partition" + short=DellUtility +elif item_in_dir -q f11.sys "$2"; then + long="Acronis Secure Zone" + short=AcroneZone +else + exit 1 +fi + +label="$(count_next_label "$short")" +result "${partition}:${long}:${label}:chain" +exit 0 diff --git a/client/shared/lib/os-probes/mounted/40lsb b/client/shared/lib/os-probes/mounted/40lsb new file mode 100755 index 00000000..ce8d4e1f --- /dev/null +++ b/client/shared/lib/os-probes/mounted/40lsb @@ -0,0 +1,48 @@ +#!/bin/sh +# Test for LSB systems. +set -e + +. /usr/share/os-prober/common.sh + +partition="$1" +dir="$2" +type="$3" + +lsb_field () { + file="$1" + field="$2" + grep ^"$field" "$file" | cut -d = -f 2 | sed 's/^"//' | sed 's/"$//' | sed 's/:/ /g' +} + +file="$dir/etc/lsb-release" +if [ ! -e "$file" ]; then + exit 1 +fi + +release=$(lsb_field "$file" DISTRIB_RELEASE) +if [ -z "$release" ]; then + release=$(lsb_field "$file" DISTRIB_CODENAME) +fi +description=$(lsb_field "$file" DISTRIB_DESCRIPTION) +if [ -z "$description" ]; then + description=$(lsb_field "$file" DISTRIB_CODENAME) +fi + +if [ -n "$description" ]; then + if [ -n "$release" ]; then + long="$description ($release)" + else + long="$description" + fi +else + exit 1 +fi + +short=$(lsb_field "$file" DISTRIB_ID | sed 's/ //g') +if [ -z "$short" ]; then + short="UnknownLSB" +fi + +label="$(count_next_label "$short")" +result "$partition:$long:$label:linux" +exit 0 diff --git a/client/shared/lib/os-probes/mounted/70hurd b/client/shared/lib/os-probes/mounted/70hurd new file mode 100755 index 00000000..af29ff55 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/70hurd @@ -0,0 +1,16 @@ +#!/bin/sh +set -e + +. /usr/share/os-prober/common.sh + +partition="$1" +dir="$2" +type="$3" + +if [ -d "$dir/servers" ] && [ -d "$dir/hurd" ]; then + label="$(count_next_label Hurd)" + result "$partition:GNU/Hurd:$label:hurd" + exit 0 +else + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/80minix b/client/shared/lib/os-probes/mounted/80minix new file mode 100755 index 00000000..e01f6695 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/80minix @@ -0,0 +1,28 @@ +#!/bin/sh +set -e + +. /usr/share/os-prober/common.sh + +partition="$1" +dir="$2" +type="$3" + +# Weed out stuff that doesn't apply to us +case "$type" in + minix|minix2|ext2) ;; + *) exit 1 ;; +esac + +if [ -f "$dir/minix" ] || [ -e "$dir/boot/image_big" ]; then + if [ -e "$dir/boot/image_latest" ]; then + boot="minix" + else + boot="chain" + fi + + label="$(count_next_label Minix)" + result "$partition:Minix:$label:$boot" + exit 0 +else + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/83haiku b/client/shared/lib/os-probes/mounted/83haiku new file mode 100755 index 00000000..6de7a1d4 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/83haiku @@ -0,0 +1,35 @@ +#!/bin/sh +# Detects Haiku on BeFS partitions. + +. /usr/share/os-prober/common.sh + +partition="$1" +mpoint="$2" +type="$3" + +# Weed out stuff that doesn't apply to us +case "$type" in + befs|befs_be) debug "$partition is a BeFS partition" ;; + *) debug "$partition is not a BeFS partition: exiting"; exit 1 ;; +esac + +if head -c 512 "$partition" | grep -qs "system.haiku_loader"; then + debug "Stage 1 bootloader found" +else + debug "Stage 1 bootloader not found: exiting" + exit 1 +fi + +if system="$(item_in_dir "system" "$mpoint")" && + item_in_dir -q "haiku_loader" "$mpoint/$system" && + (item_in_dir -q "kernel_x86" "$mpoint/$system" || + item_in_dir -q "kernel_x86_64" "$mpoint/$system") +then + debug "Stage 2 bootloader and kernel found" + label="$(count_next_label Haiku)" + result "$partition:Haiku:$label:chain" + exit 0 +else + debug "Stage 2 bootloader and kernel not found: exiting" + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/90linux-distro b/client/shared/lib/os-probes/mounted/90linux-distro new file mode 100755 index 00000000..6678f22e --- /dev/null +++ b/client/shared/lib/os-probes/mounted/90linux-distro @@ -0,0 +1,138 @@ +#!/bin/sh +# Test for linux distributions. +set -e + +. /usr/share/os-prober/common.sh + +partition="$1" +dir="$2" +type="$3" + +# This test is inaccurate, but given separate / and /boot partitions and the +# fact that only some architectures have ld-linux.so, I can't see anything +# better. Make sure this test has a high number so that more accurate tests +# can come first. +# Unless volumes to checked are already mounted, they will be mounted using +# GRUB's own filesystems through FUSE. Since these ATM doesn't support +# symlinks we need to also check in $dir/usr/lib* for distributions that +# moved /lib* to /usr and only left symlinks behind. +# TODO: look for ld-linux.so on arches that have it +if (ls "$dir"/lib*/ld*.so* || ls "$dir"/usr/lib*/ld*.so*) >/dev/null 2>/dev/null; then + if [ -e "$dir/etc/debian_version" ]; then + short="Debian" + long="$(printf "Debian GNU/Linux (%s)\n" "$(cat "$dir/etc/debian_version")")" + # RPM derived distributions may also have a redhat-release or + # mandrake-release, so check their files first. + elif [ -e "$dir/etc/altlinux-release" ]; then + short="ALTLinux" + long="$(cat "$dir/etc/altlinux-release")" + elif [ -e "$dir/etc/magic-release" ]; then + short="Magic" + long="$(cat "$dir/etc/magic-release")" + elif [ -e "$dir/etc/blackPanther-release" ]; then + short="blackPanther" + long="$(cat "$dir/etc/blackPanther-release")" + elif [ -e "$dir/etc/ark-release" ]; then + short="Ark" + long="$(cat "$dir/etc/ark-release")" + elif [ -e "$dir/etc/arch-release" ]; then + short="Arch" + long="$(cat "$dir/etc/arch-release")" + elif [ -e "$dir/etc/asplinux-release" ]; then + short="ASPLinux" + long="$(cat "$dir/etc/asplinux-release")" + elif [ -e "$dir/etc/lvr-release" ]; then + short="LvR" + long="$(cat "$dir/etc/lvr-release")" + elif [ -e "$dir/etc/caos-release" ]; then + short="cAos" + long="$(cat "$dir/etc/caos-release")" + elif [ -e "$dir/etc/aurox-release" ]; then + short="Aurox" + long="$(cat "$dir/etc/aurox-release")" + elif [ -e "$dir/etc/engarde-release" ]; then + short="EnGarde" + long="$(cat "$dir/etc/engarde-release")" + elif [ -e "$dir/etc/vine-release" ]; then + short="Vine" + long="$(cat "$dir/etc/vine-release")" + elif [ -e "$dir/etc/whitebox-release" ]; then + short="WhiteBox" + long="$(cat "$dir/etc/whitebox-release")" + elif [ -e "$dir/etc/pld-release" ]; then + short="PLD" + long="$(cat "$dir/etc/pld-release")" + elif [ -e "$dir/etc/startcom-release" ]; then + short="StartCom" + long="$(cat "$dir/etc/startcom-release")" + elif [ -e "$dir/etc/trustix-release" ]; then + short="Trustix" + long="$(cat "$dir/etc/trustix-release")" + elif [ -e "$dir/etc/openna-release" ]; then + short="OpenNA" + long="$(cat "$dir/etc/openna-release")" + elif [ -e "$dir/etc/conectiva-release" ]; then + short="Conectiva" + long="$(cat "$dir/etc/conectiva-release")" + elif [ -e "$dir/etc/mandrake-release" ]; then + short="Mandrake" + long="$(cat "$dir/etc/mandrake-release")" + elif [ -e "$dir/etc/fedora-release" ]; then + short="Fedora" + long="$(cat "$dir/etc/fedora-release")" + elif [ -e "$dir/etc/redhat-release" ]; then + short="RedHat" + long="$(cat "$dir/etc/redhat-release")" + elif [ -e "$dir/etc/SuSE-release" ]; then + short="SuSE" + long="$(head -n 1 "$dir/etc/SuSE-release")" + elif [ -e "$dir/etc/gentoo-release" ]; then + short="Gentoo" + long="$(cat "$dir/etc/gentoo-release")" + elif [ -e "$dir/etc/cobalt-release" ]; then + short="Cobalt" + long="$(cat "$dir/etc/cobalt-release")" + elif [ -e "$dir/etc/yellowdog-release" ]; then + short="YellowDog" + long="$(cat "$dir/etc/yellowdog-release")" + elif [ -e "$dir/etc/turbolinux-release" ]; then + short="Turbolinux" + long="$(cat "$dir/etc/turbolinux-release")" + elif [ -e "$dir/etc/pardus-release" ]; then + short="Pardus" + long="$(cat "$dir/etc/pardus-release")" + elif [ -e "$dir/etc/kanotix-version" ]; then + short="Kanotix" + long="$(cat "$dir/etc/kanotix-version")" + elif [ -e "$dir/etc/slackware-version" ]; then + short="Slackware" + long="$(printf "Slackware Linux (%s)\n" "$(cat "$dir/etc/slackware-version")")" + elif [ -e "$dir/sbin/pkgtool" ]; then + short="Slackware" + long="Slackware Linux" + elif grep -qs OpenLinux "$dir/etc/issue"; then + short="Caldera" + long="Caldera OpenLinux" + elif [ -e "$dir/etc/frugalware-release" ]; then + short="Frugalware Linux" + long="$(cat "$dir/etc/frugalware-release")" + elif [ -e "$dir/etc/kdemar-release" ]; then + short="K-DEMar" + long="$(printf "K-DEMar GNU/Linux (%s)\n" "$(cat "$dir/etc/kdemar-release")")" + elif [ -e "$dir/etc/lfs-release" ]; then + short="LFS" + long="$(printf "Linux From Scratch (%s)\n" "$(cat "$dir/etc/lfs-release")")" + elif [ -e "$dir/etc/meego-release" ]; then + short="MeeGo" + long="$(head -1 "$dir/etc/meego-release")" + else + short="Linux" + long="unknown Linux distribution" + fi + + label="$(count_next_label "$short")" + result "$partition:$long:$label:linux" + exit 0 +else + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/90solaris b/client/shared/lib/os-probes/mounted/90solaris new file mode 100755 index 00000000..0e9148ce --- /dev/null +++ b/client/shared/lib/os-probes/mounted/90solaris @@ -0,0 +1,19 @@ +#!/bin/sh +# Attempt to check if solaris is installed in this system +# looking at the /etc/system parameters file and /etc/vfstab. + +set -e + +. /usr/share/os-prober/common.sh + +partition="$1" +dir="$2" +type="$3" + +if [ -f "$dir/etc/system" ] && [ -f "$dir/etc/vfstab" ]; then + label="$(count_next_label Solaris)" + result "$partition:Solaris/IA32:$label:chain" + exit 0 +else + exit 1 +fi diff --git a/client/shared/lib/os-probes/mounted/efi/10elilo b/client/shared/lib/os-probes/mounted/efi/10elilo new file mode 100755 index 00000000..72dc4627 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/efi/10elilo @@ -0,0 +1,24 @@ +#!/bin/sh +# Detects ELILO bootloader on a EFI System Partition + +. /usr/share/os-prober/common.sh + +efi="$1" + +found= + +elilo=`find $1 -name "elilo.efi"` +if [ -n "$elilo" ]; then + bdir=`dirname $elilo` + bdir=`basename $bdir` + long="ELILO Boot Manager" + short="ELILO" + path=${bdir}/elilo.efi + found=true +fi + +if [ -n "$found" ]; then + label="$(count_next_label "$short")" + result "${path}:${long}:${label}" +fi +exit 0 diff --git a/client/shared/lib/os-probes/mounted/efi/20microsoft b/client/shared/lib/os-probes/mounted/efi/20microsoft new file mode 100755 index 00000000..95320814 --- /dev/null +++ b/client/shared/lib/os-probes/mounted/efi/20microsoft @@ -0,0 +1,28 @@ +#!/bin/sh +# Detects Microsoft bootloader on a EFI System Partition + +. /usr/share/os-prober/common.sh + +efi="$1" + +found= +for microsoft in $(item_in_dir microsoft "$efi"); do + for boot in $(item_in_dir boot "$efi/$microsoft"); do + bcd=$(item_in_dir bcd "$efi/$microsoft/$boot") + bootmgfw=$(item_in_dir bootmgfw.efi "$efi/$microsoft/$boot") + if [ -n "$bcd" -a -n "$bootmgfw" ]; then + long="Windows Boot Manager" + short=Windows + path="$microsoft/$boot/$bootmgfw" + found=true + break + fi + done +done + + +if [ -n "$found" ]; then + label="$(count_next_label "$short")" + result "${path}:${long}:${label}" +fi +exit 0 diff --git a/client/shared/lib/pictures/oglogo.png b/client/shared/lib/pictures/oglogo.png new file mode 100644 index 00000000..b55a4cf6 Binary files /dev/null and b/client/shared/lib/pictures/oglogo.png differ diff --git a/client/shared/scripts/ImagenesSincronizadas.lib b/client/shared/scripts/ImagenesSincronizadas.lib index d28cb9b7..717d052d 100755 --- a/client/shared/scripts/ImagenesSincronizadas.lib +++ b/client/shared/scripts/ImagenesSincronizadas.lib @@ -21,7 +21,7 @@ #echo "[START Interface ] Run this command: $0 $*" | tee -a $OGLOGSESSION $OGLOGFILE echo "$MSG_INTERFACE_START $0 $*" | tee -a $OGLOGSESSION $OGLOGFILE - # Solo ejecutable por OpenGnSys Client. + # Solo ejecutable por OpenGnsys Client. PATH=$PATH:$(dirname $0) PROG=$(basename $0) diff --git a/client/shared/scripts/README.es.txt b/client/shared/scripts/README.es.txt index 7bfb31ba..933bdcaf 100644 --- a/client/shared/scripts/README.es.txt +++ b/client/shared/scripts/README.es.txt @@ -1,4 +1,4 @@ -OpenGnSys Client (Scripts) README +OpenGnsys Client (Scripts) README ==================================== @@ -9,7 +9,7 @@ las operaciones más comunes de gestión de clientes. Dichos scripts están desarrollados en BASH y utilizan las funciones básicas del motor de clonación. -OpenGnSys Client Cloning Engine incluye un completo conjunto de +OpenGnsys Client Cloning Engine incluye un completo conjunto de funiones para que el administrador pueda personalizar sus scripts de gestión. Sin embargo, estos ejemplos son completamente operativos y pueden ser utilizados directamente. @@ -20,9 +20,11 @@ Scripts distribuidos: - bootLinux arranca un sistema Linux con partición de inicio. - bootOs arranca un sistema operativo instalado. - bootWindows arranca un sistema Windows con partición de inicio. +- configureOs ejecuta tereas de postconfiguración de un sistema operativo. - createImage genera una imagen de un sistema operativo. - createLogicalPartitions define las particiones primarias del disco. - createPrimaryPartitions define las particiones lógicas del disco. +- deployImage restaura una imagen y postconfigura su sistema operativo. - formatFs formatea un sistema de archivos. - getFsType muestra el tipo (mnemónico) de una partición. - getIpAddress muestra la IP local del cliente. @@ -36,3 +38,16 @@ Scripts distribuidos: - reboot desmonta los sistemas de archivos y reinicia el equipo. - restoreImage restaura una imagen de sistema operativo. + +Plantillas para personalización de operaciones: + +Se han generado varios scripts de ejemplo para personalizar ciertas operaciones +importantes. Para activar una plantilla debe renombrase el ficheros quitando la +extensión ".template" y añadir permisos de ejecución. Las plantillas activadas +no seránn modificadas por el actualizador de OpenGnsys. + +- bootOsCustom.template arranque personalizado de sistema operativo. +- configureOsCustom.template postconfiguración personalizada de sistema operativo. +- createImageCustom.template creación personalizada de imagen. +- restoreImageCustom.template restauración personalizada de imagen. + diff --git a/client/shared/scripts/bootOs b/client/shared/scripts/bootOs index 90e5006c..c976a5d0 100755 --- a/client/shared/scripts/bootOs +++ b/client/shared/scripts/bootOs @@ -1,54 +1,30 @@ #!/bin/bash -# Scirpt de ejemplo para arancar un sistema operativo instalado. -# (puede usarse como base para el programa de arranque usado por OpenGNSys Admin). +# Script de ejemplo para arancar un sistema operativo instalado. +# Nota: se usa como base para el programa de arranque de OpenGnsys Admin. PROG="$(basename $0)" -if [ $# -ne 2 ]; then - ogRaiseError $OG_ERR_FORMAT "Formato: $PROG ndisco nparticion" +if [ $# -lt 2 -o $# -gt 3 ]; then + ogRaiseError $OG_ERR_FORMAT "Formato: $PROG ndisco nfilesys [str_kernel str_initrd str_kernelparams]" exit $? fi # Comprobar errores. PART=$(ogDiskToDev "$1" "$2") || exit $? -ogMount $1 $2 || exit $? +ogMount $1 $2 &>/dev/null || exit $? echo "[0] Inicio del proceso de arranque." -NAME="$(ogGetHostname)" -NAME=${NAME:-"pc"} -OSTYPE=$(ogGetOsType $1 $2) -# Borrar marcas de arrranque de todos los Windows instalados en el disco. -if [ "$OSTYPE" == "Windows" ]; then - for (( i=1; i<=$(ogGetPartitionsNumber $1); i++ )); do - [ "$(ogGetOsType $1 $i)" == "Windows" ] && ogMount $1 $i &>/dev/null - done - rm -f /mnt/*/ogboot.* + +if which bootOsCustom &>/dev/null; then + echo "[10] Configuración personalizada del inicio." + bootOsCustom $@ fi -echo "[10] Desmontar todos los sistemas de archivos." +echo "[70] Desmontar todos los sistemas de archivos." sync for (( i=1; i <= $(ogDiskToDev | wc -w); i++ )); do ogUnmountAll $i &>/dev/null done -case "$OSTYPE" in - Windows) - echo "[30] Mostrar y activar particion de Windows $PART." - [ $(ogGetPartitionType $1 $2) == "HNTFS" ] && ogUnhidePartition $1 $2 - ;; - Linux) - echo "[30] Asignar nombre Linux \"$NAME\"." - ETC=$(ogGetPath $1 $2 /etc) - [ -d "$ETC" ] && echo "$NAME" >$ETC/hostname 2>/dev/null - if [ -f "$ETC/fstab" ]; then - # Sustituir UUID o LABEL por su dispositivo en definición de sistema de archivo raíz. - echo "[50] Actaualizar fstab con particion raiz \"$PART\"." - awk -v P="$PART " '{ if ($2=="/" && $1!~/^#/) {sub(/^.*$/, P, $1)} - print }' $ETC/fstab >/tmp/fstab - mv /tmp/fstab $ETC/fstab - fi - ;; -esac -echo "[70] Desmontar cache local." +echo "[80] Desmontar cache local." ogUnmountCache echo "[90] Arrancar sistema operativo." -ogBoot $1 $2 - +ogBoot "$@" diff --git a/client/shared/scripts/bootOsCustom.template b/client/shared/scripts/bootOsCustom.template new file mode 100755 index 00000000..b457fde4 --- /dev/null +++ b/client/shared/scripts/bootOsCustom.template @@ -0,0 +1,83 @@ +#!/bin/bash +#/** +# bootOsCustom +#@brief Plantilla para script de configuración personalizada de sistema operativo restaurado. +#@param $1 nº de disco +#@param $2 nº de partición +#@warning Renombrar este fichero como "bootOsCustom" para personalizar el script estándar "bootOs". +#@note La partición a inicializar debe estar montada +#**/ +# CONFIGURAR: Partición de datos de Windows que no queremos ocultar +PARTDATA=0 + +PROG="$(basename $0)" +# Control de errores +if [ $# -lt 2 ]; then + ogRaiseError $OG_ERR_FORMAT "Formato: $PROG ndisco nparticion" + exit $? +fi + +# Parámetros obligatorios. +DISK="$1" # Nº de disco. +PART="$2" # Nº de partición. + +# Paso 0: Añadir código para realizar control de errores de los parámetros de entrada (recomendado). + +# Paso 1: Adaptar el código de ejemplo para postconfiguración personalizada. +# Nota: el script "bootOs" llama al script "bootOsCustom" después de realizar la operaciones de inicio estándar y antes de desmontar las particiones e iniciar el sistema operativo. + + +MNTDIR=$(ogMount $DISK $PART) +NAME="$(ogGetHostname)" +NAME=${NAME:-"pc"} +OSTYPE=$(ogGetOsType $DISK $PART) + +case "$OSTYPE" in + Windows) + ## Borrar marcas de arrranque de todos los Windows instalados en el disco. + #echo "[30] Borrar marcas de arrranque de todos los Windows instalados en el disco." + #for (( i=1; i<=$(ogGetPartitionsNumber $1); i++ )); do + # [ "$(ogGetOsType $1 $i)" == "Windows" ] && ogMount $1 $i &>/dev/null + #done + #rm -f /mnt/*/ogboot.* + + ## Mostrar las particiones NTFS de sistema (dos opciones) + ## Opción 1: SIN ocultar las demás. + #echo "[40] Mostrar y activar particion de Windows $PART." + #[ $(ogGetPartitionType $1 $2) == "HNTFS" ] && ogUnhidePartition $1 $2 + + ## Opción 2: Ocultamos las demás. + #echo "[40] Activar particion de Windows $PART y ocultar las demás." + #for (( i=1; i<=$(ogGetPartitionsNumber $DISK); i++ )); do + # if [ $i == $PART -o $i == $PARTDATA ]; then + # [ $(ogGetPartitionType $DISK $PART) == "HNTFS" ] && ogUnhidePartition $1 $PART + # # Activo la particion si no es de datos + # [ $i -ne $PARTDATA ] && ogSetPartitionActive $DISK $i + # else + # [ "$(ogGetPartitionType $DISK $i)" == NTFS ] && ogHidePartition $DISK $i + # fi + #done + ;; + Linux) + ## Modificar el nombre del equipo + #echo "[30] Asignar nombre Linux \"$NAME\"." + #ETC=$(ogGetPath $1 $2 /etc) + #[ -d "$ETC" ] && echo "$NAME" >$ETC/hostname 2>/dev/null + + ## Sustituir UUID o LABEL por su dispositivo en definición de sistema de archivo raíz. + #if [ -f "$ETC/fstab" ]; then + # echo "[40] Actualizar fstab con particion raiz \"$PART\"." + # awk -v P="$PART " '{ if ($2=="/" && $1!~/^#/) {sub(/^.*$/, P, $1)} + # print }' $ETC/fstab >/tmp/fstab + # mv /tmp/fstab $ETC/fstab + #fi + + ## Cambiar claves usuarios, copiando fichero /etc/passwd + ## En el servidor el nuevo fichero debe situarse en el directorio del grupo: + ## /opt/opengnsys/images/groups/nombre_aula + #if [ -r $(ogGetGroupDir)/passwd ]; then + # echo "[65] Cambiar claves de usuarios." + # cp $(ogGetGroupDir)/passwd $MNTDIR/etc + #fi + ;; +esac diff --git a/client/shared/scripts/configureOs b/client/shared/scripts/configureOs index 6eaab870..a19bf4ed 100755 --- a/client/shared/scripts/configureOs +++ b/client/shared/scripts/configureOs @@ -26,9 +26,13 @@ #@version 1.0.5 - Postconfiguración para Mac OS X. #@author Ramon Gomez, ETSII Universidad de Sevilla #@date 2013-10-11 -#@version 1.0.6b - Pasar las opciones no usadas al configureOsCustom.templates -#@author +#@version 1.1.0 - Postconfiguración para agente de sistema operativo basado en REST. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-08-16 +#@version 1.0.6b - llamadas opcionales para mejoras varias. Descomentar la instruccion para su activacion. ogConfigureFstab +#@author Antonio J. Doblas Viso. Universidad de Malaga. #@date 2016-11-03 +#*/ ## # Carga el configurador del engine y los parámetros de red. [ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg @@ -66,21 +70,24 @@ case "$OSTYPE" in # Configurar el boot sector de la partición Windows. ogFixBootSector $1 $2 # Configurar el gestor de arranque de Windows XP/Vista/7. - ogWindowsBootParameters $1 $2 + ogWindowsBootParameters $1 $2 # Registrar en Windows que la partición indicada es su nueva unidad C:\ ogWindowsRegisterPartition $1 $2 C $1 $2 - # Instalar cliente para Windows si se indica en la variable INSTALLOSCLIENT. - if [ "${INSTALLOSCLIENT^^}" == "TRUE" ]; then - ogInstallMiniSetup $1 $2 postconf.cmd - ogInstallWindowsClient $1 $2 postconf.cmd - fi + # Eliminar el antiguo cliente de Windows. + if [ -n "$(ogGetPath $MNTDIR/windows/ogAdmWinClient.exe)$(ogGetPath $MNTDIR/winnt/ogAdmWinClient.exe)" ]; then + ogInstallMiniSetup $1 $2 postconf.cmd + ogUninstallWindowsClient $1 $2 postconf.cmd + fi + # Configurar nuevo agente OGAgent. + ogConfigureOgagent $1 $2 ;; Linux) # Postconfiguración de GNU/Linux. - ## Instala (no configura) el codigo de arranque del Grub en la partición (no lo configura, se mantiene el original de la imagen) + ## Instala (no configura) el codigo de arranque del Grub en la partición (no lo configura, se mantiene el original de la imagen) ogGrubInstallPartition $1 $2 - if [ "${INSTALLOSCLIENT^^}" == "TRUE" ]; then - ogInstallLinuxClient $1 $2 - fi + # Eliminar el antiguo cliente de Linux. + [ -n "$(find $MNTDIR/usr/sbin $MNTDIR/sbin $MNTDIR/usr/local/sbin -name ogAdmLnxClient -print)" ] && ogUninstallLinuxClient $1 $2 + # Configurar nuevo agente OGAgent. + ogConfigureOgagent $1 $2 ;; MacOS) # Postconfiguración de Mac OS X. # Fichero indicador de activación de postconfiguración. @@ -139,11 +146,14 @@ if [ -e /osxpostconf ]; then # Descromprimir ficheros de versión para obtener inventario de aplicaciones. find /Applications -type d -name "*.app" -prune -exec \ ditto --nopreserveHFSCompression "{}/Contents/version.plist" "{}/Contents/version.plist.uncompress" - rm -f /osxpostconf # Borrar fichero indicador de psotconfiguración + rm -f /osxpostconf # Borrar fichero indicador de psotconfiguración fi EOT # Dar permiso de ejecución. chmod 700 $MNTDIR/var/root/postconfd.sh + # Configurar nuevo agente OGAgent de sistema operativo. + ogConfigureOgagent $1 $2 ;; esac +exit 0 diff --git a/client/shared/scripts/createBaseImage b/client/shared/scripts/createBaseImage index ed9255b4..c367e930 100755 --- a/client/shared/scripts/createBaseImage +++ b/client/shared/scripts/createBaseImage @@ -3,7 +3,7 @@ #/** # createBaseImage #@brief Script de ejemplo para crear una imagen de un sistema de archivos. -#@brief (puede usarse como base para el programa de creación de imágenes usado por OpenGnSys Admin). +#@brief Se usa como base para el programa de creación de imágenes de OpenGnsys Admin). #@param 1 disco #@param 2 particion #@param 3 REPO|CACHE @@ -22,6 +22,9 @@ #@version 1.0 - creación imagen con btrfs #@author #@date 2012-12-04 +#@version 1.1.0 - Se muestra el espacio necesario para alojar la imagen y el disponible (ticket #771) +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2017-03-28 #*/ ## trap "onexit $1 $2 $3 \"$4\"" 1 2 3 6 9 14 15 EXIT @@ -87,9 +90,9 @@ ORIG=$(ogMount $1 $2) || exit $(ogRaiseError session $OG_ERR_PARTITION "$1 $2" ; ogCleanOs $1 $2 #Comprobar espacio que requerira la imagen para ser almacenada -read SIZEDATA SIZEREQUIRED ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$3" SYNC) +read SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$3" "$4" SYNC) -ogEcho log session "[16] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED" +ogEcho log session "[16] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED $SIZEFREE" [ "$ISENOUGHSPACE" == "TRUE" ] || exit $(ogRaiseError session $OG_ERR_CACHESIZE "$3"; echo $?) IMGDIR="$(ogGetParentPath "$3" "/$4")" @@ -133,6 +136,7 @@ ogReduceImage $3 "$4" $IMGEXT ogWaitSyncImage "$3" "$4" $IMGEXT "reduced" $SIZEREQUIRED || exit $(ogRaiseError session $OG_ERR_DONTMOUNT_IMAGE "$3 $4 $IMGEXT: time_out."; echo $?) echo " " > $OGLOGCOMMAND +sleep 2 # Comprobamos que la imagen esta bien detectacdo que es un sistema de ficheros. ogEcho log session "[95] $MSG_HELP_ogCheckSyncImage" ogCheckSyncImage $3 "$4" "img" || exit $(ogRaiseError session $OG_ERR_IMAGE "$3 $4 img" ; echo $?) diff --git a/client/shared/scripts/createDiffImage b/client/shared/scripts/createDiffImage index 862c05c8..d5f897be 100755 --- a/client/shared/scripts/createDiffImage +++ b/client/shared/scripts/createDiffImage @@ -3,7 +3,7 @@ #/** # createDiffImage #@brief Script de ejemplo para crear una imagen diferencial de un sistema de archivos. -#@brief (puede usarse como base para el programa de creación de imágenes usado por OpenGnSys Admin). +#@brief Se usa como base para el programa de creación de imágenes de OpenGnsys Admin). #@param 1 disco #@param 2 particion #@param 3 REPO|CACHE @@ -25,6 +25,9 @@ #@version 1.0 - creacion de la diferencial con rsync y btrfs #@author #@date 2012-12-04 +#@version 1.1.0 - Se muestra el espacio necesario para alojar la imagen y el disponible (ticket #771) +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2017-03-28 #*/ ## trap "onexit $1 $2 $3 \"$4\" \"$5\"" 1 2 3 6 9 14 15 EXIT @@ -127,9 +130,9 @@ ogCreateInfoImage $1 $2 $3 "$4" "${DIFFTYPE}" [ $? -eq $OG_ERR_NOTDIFFERENT ] && exit $(ogRaiseError session $OG_ERR_NOTDIFFERENT; echo $?) #Comprobar espacio que requerira la imagen para ser almacenada -read SIZEDATA SIZEREQUIRED ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$3" DIFF) +read SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$3" "$5" DIFF) -ogEcho log session "[50] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED" +ogEcho log session "[50] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED $SIZEFREE" [ "$ISENOUGHSPACE" == "TRUE" ] || exit $(ogRaiseError session $OG_ERR_CACHESIZE "$3"; echo $?) #Calculamos el tamaño de la imagen: @@ -167,6 +170,7 @@ ogWaitSyncImage "$3" "$5" $DIFFTYPE "reduced" $SIZEREQUIRED || exit $(ogRaiseErr # TODO: necesaria funcion que espere a que se reduzca la imagen para continuar el script echo " " > $OGLOGCOMMAND +sleep 2 # Comprobamos que la imagen esta bien ogEcho log session "[95] $MSG_HELP_ogCheckSyncImage" ogCheckSyncImage $3 "$5" diff || exit $(ogRaiseError session $OG_ERR_IMAGE "$3 $5 diff"; echo $?) diff --git a/client/shared/scripts/createImage b/client/shared/scripts/createImage index 27a8abea..65da156b 100755 --- a/client/shared/scripts/createImage +++ b/client/shared/scripts/createImage @@ -3,7 +3,7 @@ #/** #@file createImage #@brief Scirpt de ejemplo para crear una imagen de un sistema de archivos. -#@brief (puede usarse como base para el programa de creación de imágenes usado por OpenGnSys Admin). +#@brief Se usa como base para el programa de creación de imágenes de OpenGnsys Admin). #@param 1 disco #@param 2 particion #@param 3 REPO|CACHE @@ -26,12 +26,15 @@ #@version 1.0.1 - Control de espacio requerido #@author Antonio J.Doblas Viso #@date 2011-05-10 - #@version 1.0.2 - Separacion de log +#@version 1.0.2 - Separacion de log #@author Antonio J.Doblas Viso #@date 2011-08-4 -#@version 1.0.6b - La copia de seguridad de la imagen antigua se hace después de las comprobaciones. +#@version 1.1.0 - La copia de seguridad de la imagen antigua se hace después de las comprobaciones. #@author Irina Gomez - ETSII Universidad de Sevilla #@date 2016-10-14 +#@version 1.1.0 - Se muestra el espacio necesario para alojar la imagen y el disponible (ticket #771) +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2017-03-28 #*/ ## # Test 1. crear una imagen en un REPO sin espacio libre. @@ -58,15 +61,32 @@ TIME1=$SECONDS #IMGCOMP="lzop" IMGEXT=${IMGEXT:-"img"} #IMGREDUCE="TRUE" +REPO="${3^^}" + +# Unidad organizativa +[ "$ogunit" != "" ] && OGUNIT="$ogunit" # Clear temporary file used as log track by httpdlog # Limpia los ficheros temporales usados como log de seguimiento para httpdlog -echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp +# salvo si es llamado desde createImageCustom +if [ "$(ogGetCaller)" != "createImageCustom" ]; then + echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp +fi ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" +# Si es una ip y es igual a la del equipo restaura desde cache +[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE" +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPO +if [ $? == 0 -o $REPO == "REPO" ] ; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?) + REPO="REPO" +fi + # Si el repositorio es CACHE comprobamos que exista -if [ "${3^^}" == "CACHE" ]; then +if [ "$REPO" == "CACHE" ]; then ! ogFindCache >/dev/null && exit $(ogRaiseError $OG_ERR_NOTCACHE "CACHE "; echo $?) fi @@ -75,14 +95,14 @@ PART=$(ogDiskToDev "$1" "$2" 2>/dev/null) || exit $(ogRaiseError $OG_ERR_PARTITI #Comprobamos acceso de escritura. DIRTEMP=$(date +%Y%m%d-%H%M%S) -ogMakeDir $3 /$4$DIRTEMP 2>/dev/null || exit $(ogRaiseError $OG_ERR_NOTWRITE "$3"; echo $?) && ogDeleteTree $3 /$4$DIRTEMP +ogMakeDir $REPO /$4$DIRTEMP 2>/dev/null || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO"; echo $?) && ogDeleteTree $REPO /$4$DIRTEMP -IMGDIR=$(ogGetParentPath "$3" "/$4") +IMGDIR=$(ogGetParentPath "$REPO" "/$4") # Si no existe, crear subdirectorio de la imagen. if [ $? != 0 ]; then - ogEcho log session "[5] $MSG_HELP_ogMakeDir \"$3 $(dirname "$4")." - ogMakeDir "$3" $(dirname "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$3 /$4"; echo $?) - IMGDIR=$(ogGetParentPath "$3" "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$3 /$4"; echo $?) + ogEcho log session "[5] $MSG_HELP_ogMakeDir \"$REPO $(dirname "$4")." + ogMakeDir "$REPO" $(dirname "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?) + IMGDIR=$(ogGetParentPath "$REPO" "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?) fi IMGFILE=$IMGDIR/$(basename "/$4").$IMGEXT @@ -91,10 +111,10 @@ echo " " > $OGLOGCOMMAND ogCleanOs $1 $2 #Comprobar espacio que requerira la imagen para ser almacenada -read SIZEDATA SIZEREQUIRED ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$3") +read SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$REPO" "$4") -ogEcho log session "[16] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED" -[ "$ISENOUGHSPACE" == "TRUE" ] || exit $(ogRaiseError session $OG_ERR_CACHESIZE "$3"; echo $?) +ogEcho log session "[16] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED $SIZEFREE" +[ "$ISENOUGHSPACE" == "TRUE" ] || exit $(ogRaiseError session $OG_ERR_CACHESIZE "$REPO"; echo $?) # Comprobar consistencia del sistema de archivos. echo " " > $OGLOGCOMMAND @@ -125,8 +145,8 @@ fi # Crear la imagen. echo " " > $OGLOGCOMMAND TIME2=$SECONDS -ogEcho log session "[40] $MSG_HELP_ogCreateImage : ogCreateImage $1 $2 $3 $4 $IMGPROG $IMGCOMP" -ogCreateImage "$1" "$2" "$3" "/$4" "$IMGPROG" "$IMGCOMP" &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_IMAGE "ogCreteImage"; echo $?) +ogEcho log session "[40] $MSG_HELP_ogCreateImage : ogCreateImage $1 $2 $REPO $4 $IMGPROG $IMGCOMP" +ogCreateImage "$1" "$2" "$REPO" "/$4" "$IMGPROG" "$IMGCOMP" &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_IMAGE "ogCreteImage"; echo $?) RESUMECREATEIMAGE=$(grep "Total Time:" $OGLOGCOMMAND) TIMEAUX2=$[SECONDS-TIME2] ogEcho log session " $RESUMECREATEIMAGE " @@ -143,8 +163,8 @@ ogEcho log session " $MSG_HELP_ogExtendFs $NEWSIZEFS -> $SIZEFS = $SIZEFS #TODO que hacer si error al extender sistemade archivos #resumen de la operacion -IMGSIZE=$(ls -s `ogGetPath $3 /$4.$IMGEXT`| cut -f1 -d" ") -IMGOS=$(ogGetImageInfo `ogGetPath $3 /$4.$IMGEXT`) +IMGSIZE=$(ls -s `ogGetPath $REPO /$4.$IMGEXT`| cut -f1 -d" ") +IMGOS=$(ogGetImageInfo `ogGetPath $REPO /$4.$IMGEXT`) TIME=$[SECONDS-TIME1] ogEcho log session "[100] $MSG_SCRIPTS_TIME_TOTAL $[TIME/60]m $[TIME%60]s" diff --git a/client/shared/scripts/deployImage b/client/shared/scripts/deployImage index 3be16e92..51847110 100755 --- a/client/shared/scripts/deployImage +++ b/client/shared/scripts/deployImage @@ -31,6 +31,12 @@ #@version 1.0.6 - Se añade la gestión de errores de la CACHE cuando en el engine.cfg se define RESTOREPROTOCOLNOCACHE=NONE. #@author Antonio J. Doblas Viso. #@date 2015-02-23 +#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-06-16 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 #**/ @@ -57,6 +63,8 @@ PART="$4" PROTO="${5^^}" PROTO="${PROTO:-"UNICAST"}" PROTOOPT="$6" +# Unidad organizativa. +[ "$ogunit" != "" ] && OGUNIT="$ogunit" #Load engine configurator from engine.cfg file. #Carga el configurador del engine desde el fichero engine.cfg @@ -77,17 +85,25 @@ ogEcho log session "$MSG_HELP_ogUnmount $DISK $PART" ogUnmount $DISK $PART 2>/dev/null # Valor por defecto para el repositorio. -[ "$REPO" == "$(ogGetRepoIp)" ] && REPO="REPO" -[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE" +if [ "$REPO" == "$(ogGetIpAddress)" -o "$REPO" == "CACHE" ]; then + MODE="CACHE" +else + ogCheckIpAddress "$REPO" + if [ $? == 0 -o "$REPO" == "REPO" ]; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO ${OGUNIT} || exit $(ogRaiseError $OG_ERR_NOTFOUND "$REPO $OGUNIT"; echo $?) + MODE="REPO" + fi +fi #Informacioin previa de la imagen -IMGOS=$(ogGetImageInfo `ogGetPath $REPO $IMGNAME.img`) || exit $(ogRaiseError session $OG_ERR_NOTFOUND "$REPO $2"; echo $?) -IMGSIZE=$(ls -s `ogGetPath $REPO $IMGNAME.img`| cut -f1 -d" ") +IMGOS=$(ogGetImageInfo `ogGetPath $MODE $IMGNAME.img`) || exit $(ogRaiseError session $OG_ERR_NOTFOUND "$REPO $2"; echo $?) +IMGSIZE=$(ls -s `ogGetPath $MODE $IMGNAME.img`| cut -f1 -d" ") ogEcho log session "[1] REPO=$REPO IMG-FILE=$IMGNAME.img SIZE=$IMGSIZE (KB) METADATA=$IMGOS" # Procesar repositorio. -case "$REPO" in +case "$MODE" in CACHE) # Repositorio en caché local. NEXTOPERATION=CACHE ;; @@ -102,9 +118,9 @@ case "$REPO" in # Si protocolo es torrent|torrent-cache o multicast|multicast-cache TORRENT|TORRENT-CACHE|MULTICAST|MULTICAST-CACHE|UNICAST|UNICAST-CACHE) - ogEcho log session "[2] updateCache REPO \"/$IMGNAME.img\" $PROTO $PROTOOPT" + ogEcho log session "[2] updateCache "$REPO" \"/$IMGNAME.img\" $PROTO $PROTOOPT" TIME2=$SECONDS - updateCache REPO "/$IMGNAME.img" "$PROTO" "$PROTOOPT" + updateCache "$REPO" "/$IMGNAME.img" "$PROTO" "$PROTOOPT" RETVAL=$? TIME2=$[SECONDS-TIME2] ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL updateCache $[TIME2/60]m $[TIME2%60]s" @@ -144,6 +160,10 @@ case "$REPO" in ;; esac # del RESTOREPROTOCOLNOTCACHE ;; + 57|60) + # Time-out en la transferencia multicast (El mensaje de error está enviado) + exit $RETVAL + ;; esac ;; *) # Error: protocolo desconocido. @@ -165,9 +185,9 @@ case "$NEXTOPERATION" in CACHE) PARAMS="CACHE $IMGNAME $DISK $PART" ;; UNICAST) - PARAMS="REPO $IMGNAME $DISK $PART" ;; + PARAMS="$REPO $IMGNAME $DISK $PART" ;; MULTICAST) - PARAMS="REPO $IMGNAME $DISK $PART $PROTO $PROTOOPT" ;; + PARAMS="$REPO $IMGNAME $DISK $PART $PROTO $PROTOOPT" ;; esac # Si existe, ejecuta script personalizado "restoreImageCustom"; si no, llama al genérico "restoreImage". diff --git a/client/shared/scripts/formatFs b/client/shared/scripts/formatFs index 832592fb..1147f255 100755 --- a/client/shared/scripts/formatFs +++ b/client/shared/scripts/formatFs @@ -1,6 +1,6 @@ #!/bin/bash # Scirpt de ejemplo para formatear un sistema de archivos. -# (puede usarse como base para el programa de formateo de OpenGnSys Admin). +# Nota: se usa como base para el programa de formateo de OpenGnsys Admin). TIME1=$SECONDS PROG="$(basename $0)" diff --git a/client/shared/scripts/grubSyntax b/client/shared/scripts/grubSyntax index 4d91e308..209cfc00 100755 --- a/client/shared/scripts/grubSyntax +++ b/client/shared/scripts/grubSyntax @@ -1,7 +1,16 @@ -#! /bin/sh +#!/bin/bash set -e -grub_probe=$OGBIN/grub-probe1.99 +#grubSyntax +#version 1.1.0 +#autoconfigurador de items de menu para grub/brg +#basado en scripts del paquete de grub +#Antonio Doblas Viso +#Universidad de Málaga + +DISK= +PART= + if [ $# == 3 ]; then @@ -17,6 +26,29 @@ if [ $# == 1 ]; then fi +#Versión de scripts compatible con la versión 1.99 de grub-probe +#Uso del grub-probe 1.99 según arquitectura +grub_probe=${grub_probe:-$OGBIN/grub-probe1.99_$(arch)} + +#librerias del osProber para kernel antiguos: detecta e identifica sistema operativos. +grub-install --version | grep 1.99 && cp -r /opt/opengnsys/lib/os-probes/* /usr/lib/os-probes/ + + +#Autoreconocimiento del ogLive en cache +#fichero de reconocimeinto de grub +#fichero de lsb-release en la cache (al final de este scripts se elimina esta entrada para que el browser no lo muestre + +if [ $(ls /opt/opengnsys/cache/boot/$oglivedir/ogvmlinuz 2>/dev/null) ]; then + sed -i 's|/boot/\${oglivedir}/ogvmlinuz |/vmlinuz |i' /usr/lib/linux-boot-probes/mounted/90fallback + sed -i 's|/vmlinuz |/vmlinuz /boot/\${oglivedir}/ogvmlinuz |1' /usr/lib/linux-boot-probes/mounted/90fallback + mkdir -p /opt/opengnsys/cache/etc/ + echo "DISTRIB_ID=Ubuntu" > /opt/opengnsys/cache/etc/lsb-release + echo "DISTRIB_RELEASE= " >> /opt/opengnsys/cache/etc/lsb-release + echo $oglivedir | awk -F- ' {print "DISTRIB_CODENAME="$2 }' >> /opt/opengnsys/cache/etc/lsb-release + echo "DISTRIB_DESCRIPTION=OpenGnsys Live" >> /opt/opengnsys/cache/etc/lsb-release +fi + +#ver linea 195 detección de los os en variable OSPROBED OG_prepare_grub_to_access_device () { @@ -80,11 +112,7 @@ OG_prepare_grub_to_access_device () -# ADV buscar os-prober -#Si $DISK no definido usar 1 -DISK=${DISK:-"1"} -OSSEARCH=$(ogDiskToDev $DISK $PART) -#echo $OSSEARCH + # grub-mkconfig helper script. # Copyright (C) 2006,2007,2008,2009 Free Software Foundation, Inc. @@ -178,8 +206,22 @@ case "$1" in esac - -OSPROBED="`os-prober | grep $OSSEARCH | tr ' ' '^' | paste -s -d ' '`" + + + +# ADV OSPROBED +if [ -n "${DISK}" ]; then + #Si $DISK esta definido buscar en el disco y la particion parametro 1 y 2 + OSSEARCH=$(ogDiskToDev $DISK $PART) + OSPROBED="`os-prober | grep $OSSEARCH | tr ' ' '^' | paste -s -d ' '`" +else + #si no esta definido + OSPROBED="`os-prober | tr ' ' '^' | paste -s -d ' '`" +fi + +#DISK=${DISK:-"1"} +#echo $OSSEARCH +#echo "$OSPROBED" if [ -z "${OSPROBED}" ] ; then @@ -273,10 +315,12 @@ for OS in ${OSPROBED} ; do fi ;; esac + #adv + LABELCLASS=$(echo "${LONGNAME}" | awk '{print tolower($1$2);}') found_other_os=1 cat << EOF -menuentry "${LONGNAME} (on ${DEVICE})" --class windows --class os { +menuentry "${LONGNAME} (on ${DEVICE})" --class $LABELCLASS --class windows { EOF save_default_entry | sed -e "s/^/\t/" #ADV prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" @@ -298,17 +342,22 @@ EOF EOF ;; linux) + KERNELPARAM="" + #linuxprobed detecta todos los kernels de una partición. LINUXPROBED="`linux-boot-prober ${DEVICE} 2> /dev/null | tr ' ' '^' | paste -s -d ' '`" +#esta opcion de linuxprobe solo interpreta el primer kernel detectado de la partición +#Si queremos que autoincluya todos los kernels hay que comentar esta filtrado de LINUXPROBED + LINUXPROBED=$(echo $LINUXPROBED | awk '{ print $1}') prepare_boot_cache= - + # echo "ADV listado de los kerenel encontrados linux-boot-prober ${DEVICE} $LINUXPROBED" for LINUX in ${LINUXPROBED} ; do + LINUX=$LINUXPROBED LROOT="`echo ${LINUX} | cut -d ':' -f 1`" LBOOT="`echo ${LINUX} | cut -d ':' -f 2`" LLABEL="`echo ${LINUX} | cut -d ':' -f 3 | tr '^' ' '`" LKERNEL="`echo ${LINUX} | cut -d ':' -f 4`" LINITRD="`echo ${LINUX} | cut -d ':' -f 5`" LPARAMS="`echo ${LINUX} | cut -d ':' -f 6- | tr '^' ' '`" - if [ -z "${LLABEL}" ] ; then LLABEL="${LONGNAME}" fi @@ -319,8 +368,9 @@ EOF fi found_other_os=1 + LABELCLASS=$(echo "${LLABEL}" | awk '{print tolower($1);}') cat << EOF -menuentry "${LLABEL} (on ${DEVICE})" --class gnu-linux --class gnu --class os { +menuentry "${LLABEL} (on ${DEVICE})" --class $LABELCLASS --class linux --class os { EOF save_default_entry | sed -e "s/^/\t/" if [ -z "${prepare_boot_cache}" ]; then @@ -328,6 +378,9 @@ EOF prepare_boot_cache="$(OG_prepare_grub_to_access_device ${LBOOT} | sed -e "s/^/\t/")" fi printf '%s\n' "${prepare_boot_cache}" + if [ "$LABELCLASS" == "opengnsys" ]; then + KERNELPARAM=$(cat /proc/cmdline) + fi cat << EOF linux ${LKERNEL} ${LPARAMS} ${KERNELPARAM} EOF @@ -339,7 +392,7 @@ EOF cat << EOF } EOF - done + done ;; macosx) OSXUUID="`grub-probe --target=fs_uuid --device ${DEVICE} 2> /dev/null`" @@ -379,3 +432,5 @@ EOF done adjust_timeout + +rm /opt/opengnsys/cache/etc/lsb-release &>/dev/null diff --git a/client/shared/scripts/initCache b/client/shared/scripts/initCache index d5fba1e7..796ab84f 100755 --- a/client/shared/scripts/initCache +++ b/client/shared/scripts/initCache @@ -1,35 +1,55 @@ #!/bin/bash # Scirpt de iniciación de la caché local de disco. -# (puede usarse como base para el programa de restauración de imágenes usado por OpenGnSys Admin). +# Nota: se usa como base para el programa de configuración de equipos de OpenGnsys Admin). +# Formato: initCache [int_ndisk [int_npart]] {-1 | 0 | int_size} [NOMOUNT] # Versión: 0.9.1, 2009/03/17, - Ramón Gómez, Univ. Sevilla - Versión inicial. # Versión: 0.9.2, 2010/07/27, - Ramón Gómez, Univ. Sevilla - redefinir parámetro. # Version: 1.0.5, 2012/09/18, - Univ. Huelva - Nuevo parametro para indicar el disco donde se creara la CACHE, si no se indica, se usa 1 +# Version: 1.1.0, 2016/06/16, - Ramón Gómez, Univ. Sevilla - Nuevos parámetros: partición de caché (por defecto, 4) y cadena opcional "NOMOUNT" para dejar la caché sin montar. TIME1=$SECONDS PROG="$(basename $0)" -# Si el numero de parametros es 1, es el tamano de la CACHE -if [ $# == 1 ] -then +EXECFORMAT="$PROG [int_ndisk [int_npart]] {-1 | 0 | int_size} [NOMOUNT]" + +# Si el último parámetro es la cadena "NOMOUNT", marcar para no montar y descartarlo. +if [[ "${*^^}" =~ \ NOMOUNT$ ]]; then + MOUNT=0 + PARAMS=$[$#-1] +else + MOUNT=1 + PARAMS=$# +fi +# Tomar valores según el número de parámetros restantes. +case $PARAMS in + 1) # Por defecto, disco 1 partición 4. NDISK=1 + NPART=4 SIZE=$1 -elif [ $# == 2 ] -then + ;; + 2) # Elegir disco y partición 4 por defecto. NDISK=$1 + NPART=4 SIZE=$2 -else - ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG [int_ndisk] -1 | 0 | size" - exit $? -fi + ;; + 3) # Elegir disco y partición. + NDISK=$1 + NPART=$2 + SIZE=$3 + ;; + *) # Error de formato. + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT" + exit $? + ;; +esac -# Si disco no es mayor o igual que 1, error. -if [ -n "${NDISK//[-0-9]/}" ] || [ $NDISK -lt 1 ]; then - ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG [int_ndisk] -1 | 0 | size" +# Si disco o partición no son mayores o iguales que 1, error. +if [ -n "${NDISK//[-0-9]/}${NPART//[-0-9]/}" ] || [ $NDISK -lt 1 ] || [ $NPART -lt 1 ] ; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT" exit $? fi - # Si tamaño no es numérico o tamaño<-1, error. if [ -n "${SIZE//[-0-9]/}" ] || [ $SIZE -lt -1 ]; then - ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG int_ndisk [-1 | 0 | size]" + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT" exit $? fi # Si tamaño=0, no hacer nada. @@ -43,21 +63,14 @@ if [ $SIZE -eq -1 ]; then ogUnmountCache 2>/dev/null ogDeleteCache else - # Comprobar disco y particion donde se aloja la cache actualmente, si la hay - FINDCACHE=`ogFindCache` - echo "[5] ogFindCache: "$FINDCACHE - CACHEDISK=${FINDCACHE% *} - PART=${FINDCACHE#* } - - # Si la CACHE actual esta definida en otro disco, se elimina - if [ -n "$CACHEDISK" -a "$NDISK" != "$CACHEDISK" ] - then - echo "[10] Detectada cache en otro disco, eliminarla" + # Si la caché actual está definida en otro disco y partición, se elimina. + if [ -n "$(ogFindCache)" -a "$NDISK $NPART" != "$(ogFindCache)" ]; then + echo "[10] Detectada otra caché, eliminarla" ogUnmountCache 2>/dev/null ogDeleteCache fi - # Si tamaño>0, ... + # Error si tamaño definido no es >0. if [ ! $SIZE -gt 0 ]; then ogRaiseError $OG_ERR_FORMAT "$MSG_ERR_FORMAT: !($SIZE>0)" exit $? @@ -67,7 +80,8 @@ else if [ "$SIZE" != "$CACHESIZE" ]; then echo "[10] Crar partición de caché local." ogUnmountCache 2>/dev/null - ogCreateCache $NDISK "$SIZE" + ogCreateCache $NDISK $NPART $SIZE + ogUpdatePartitionTable $NDISK fi # Si caché no montada y no formateada, formatear. CACHE=$(ogFindCache) || exit $? @@ -75,14 +89,19 @@ else echo "[50] Formatear caché local." ogFormatCache fi - echo "[70] Montar caché local." + echo "[70] Comprobar montaje de caché local." ogMountCache 2>/dev/null # Si error al montar, chequear sistema de archivos y volver a montar. if [ $? != 0 ]; then - echo "[80] Comprobar y montar caché local." + echo "[80] Comprobar consistencia y volver a montar caché local." ogCheckFs $CACHE ogMountCache || exit $? fi + # Dejar desmontada la caché si se ha solicitado. + if [ $MOUNT == 0 ]; then + echo "[90] Dejar desmontada la caché local." + ogUnmountCache 2>/dev/null + fi fi # Duración del proceso. TIME=$[SECONDS-TIME1] diff --git a/client/shared/scripts/launchOgagentInstaller b/client/shared/scripts/launchOgagentInstaller new file mode 100755 index 00000000..58d63dde --- /dev/null +++ b/client/shared/scripts/launchOgagentInstaller @@ -0,0 +1,147 @@ +#!/bin/bash +# #/** +# launchOgagentInstaller ndisk npart [windowsadmin] +#@brief Scheduling OpenGnsys Agent installation at next boot or administrator session. +#@param integer ndsik disk number +#@param integer npart partition number +#@param string windowsadmin administrator user (only for Windows) +#@author Ramón M. Gómez, ETSII Univ. Sevilla +#@version 1.1.0 - Initial version. +#@date 2018-02-16 +#*/ ## + +# Global variables. +PROG="$(basename "$0")" +if which curl &>/dev/null; then + DOWNLOAD="curl -k --timeout 1 -o" +else + DOWNLOAD="wget --no-check-certificate -T 1 -O" +fi + +# Show help. +if [ "$*" == "help" ]; then + echo "$PROG: scheduling OpenGnsys Agent installation." + echo "Format: $PROG ndisk npart [windowsadmin]" + exit 0 +fi +# Error control. +if ! typeset -Fp ogRaiseError &>/dev/null; then + echo "$PROG: it can only be executed by an ogLive client." >&2 + exit 1 +fi +[ $# == 2 -o $# == 3 ] || ogRaiseError $OG_ERR_FORMAT "$PROG ndisk npart [adminuser]" || exit $OG_ERR_FORMAT +MNTDIR=$(ogMount "$1" "$2") || exit $? +OGVERSION=$($DOWNLOAD - https://$(ogGetServerIp)/opengnsys/rest/info 2>/dev/null | jq -r .version) +[ -n "$OGVERSION" ] || ogRaiseError $OG_ERR_NOTFOUND "GET /rest/info" || exit $OG_ERR_NOTFOUND + +case "$(ogGetOsType $1 $2)" in + Windows) # OGAgent for Windows. + HIVE="$(ogGetHivePath "$MNTDIR" "$3")" + [ -n "$HIVE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 $3/NTUSER.DAT" || exit $OG_ERR_NOTFOUND + # Downloading OGAgent installer for Windows. + OGAGENTFILE="OGAgentSetup-${OGVERSION/pre/}.exe" + TMPDIR="$(ogGetPath "$MNTDIR/Windows/Temp")" + eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null + if ogListSoftware $1 $2 | grep -qi "opengnsys agent"; then + echo "OGAgent for Windows is already installed, you need to uninstall it before re-install." + else + if [ -s "$TMPDIR/$OGAGENTFILE" ]; then + # Run once OGAgent Installer. + if hivexsh -w << EOT 2>/dev/null; then +load $HIVE +cd \\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce +setval 1 +Install OGAgent +string:C:\\Windows\\Temp\\$OGAGENTFILE" +commit +close +exit +EOT + echo "Scheduled OGAgent installation after \"$3\" logon" + echo " (edit config file after finish)." + else + ogRaiseError $OG_ERR_NOTWRITE "$1 $2 .../$3/NTUSER.DAT" + exit $OG_ERR_NOTWRITE + fi + else + ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /Windows/Temp/$OGAGENTFILE" + exit $OG_ERR_NOTFOUND + fi + fi + ;; + Linux) # OGAgent for Linux (only deb and redhat-based backages; TODO suse-based package). + if ogListSoftware $1 $2 | grep -qi "ogagent"; then + echo "OGAgent for Linux is already installed, you need to uninstall it before re-install." + else + SYSTEMDDIR="$MNTDIR/lib/systemd" + [ -d "$SYSTEMDDIR" -a -d "${SYSTEMDDIR/lib/etc}" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 systemd" || exit $OG_ERR_NOTFOUND + # Downloading OGAgent installer for Linux. + if [ -e $MNTDIR/etc/debian_version ]; then # Debian-based + OGAGENTFILE="ogagent_${OGVERSION/pre/}_all.deb" + CODE="if ! dpkg -l ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then apt-get update; apt-get install -y /var/tmp/$OGAGENTFILE; fi" + fi + if [ -e $MNTDIR/etc/redhat-release ]; then # RedHat-based + OGAGENTFILE="ogagent-${OGVERSION/pre/}-1.noarch.rpm" + CODE="if ! rpm -q ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then yum install -y /var/tmp/$OGAGENTFILE; fi" + fi + [ -n "$OGAGENTFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 ogagent" || exit $OG_ERR_NOTFOUND + TMPDIR="$MNTDIR/var/tmp" + eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null + if [ -s "$TMPDIR/$OGAGENTFILE" ]; then + # Creating systemd script. + cat << EOT > $SYSTEMDDIR/systemd-launchogagent +#!/bin/bash +[ $EUID = 0 ] || exit 4 +start() { + $CODE + sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg + service ogagent start +} +restart() { + service ogagent stop + if [ -f /var/tmp/$OGAGENTFILE ]; then + apt-get update + apt-get install -y --reinstall /var/tmp/$OGAGENTFILE + fi + sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg + service ogagent start +} + +case "\$1" in + start|restart) "\$1" ;; +esac +EOT + chmod +x $SYSTEMDDIR/systemd-launchogagent + # Creating systemd service. + cat << EOT > $SYSTEMDDIR/system/launchogagent.service +[Unit] +Description=Installing and configuring OGAgent + +[Service] +Type=oneshot +RemainAfterExit=yes +ExecStart=/lib/systemd/systemd-launchogagent start +TimeoutStartSec=5min + +[Install] +WantedBy=multi-user.target +EOT + ln -fs /lib/systemd/system/launchogagent.service \ + ${SYSTEMDDIR/lib/etc}/system/multi-user.target.wants + echo "Scheduled OGAgent installation at next boot" + echo " (process will be executed in the background, do not shutdown until finish)." + else + ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /var/tmp/$OGAGENTFILE" + exit $OG_ERR_NOTFOUND + fi + fi + ;; + MacOS) # OGAgent for macOS (TODO). + echo "OGAgent installer for macOS is not implemented yet." + ;; + *) # OS not detected or OGAgent not implemented. + ogRaiseError $OG_ERR_NOTOS "$1 $2" + exit $OG_ERR_NOTOS + ;; +esac + diff --git a/client/shared/scripts/listHardwareInfo b/client/shared/scripts/listHardwareInfo index c38f35f9..34679a03 100755 --- a/client/shared/scripts/listHardwareInfo +++ b/client/shared/scripts/listHardwareInfo @@ -1,9 +1,9 @@ #!/bin/bash # Scirpt de ejemplo para almacenear en fichero temporal el listado de hardware. -# (puede usarse como base para el programa de arranque usado por OpenGNSys Admin). +# Nota: se usa como base para el programa de recogida de listado de hardware de OpenGnsys Admin. # Formato: listHardwareInfo -PROG="$(basename $0)" +PROG=$(basename "$0") if [ $# -ne 0 ]; then ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG " exit $? diff --git a/client/shared/scripts/listSoftwareInfo b/client/shared/scripts/listSoftwareInfo index e5b0da1c..1b97294c 100755 --- a/client/shared/scripts/listSoftwareInfo +++ b/client/shared/scripts/listSoftwareInfo @@ -1,11 +1,15 @@ #!/bin/bash # Scirpt de ejemplo para almacenear en fichero temporal el listado de software. -# (puede usarse como base para el programa de arranque usado por OpenGNSys Admin). +# Nota: se usa como base para el programa de recogida de listado de software de OpenGnsys Admin. # Formato: listSoftwareInfo [-r] ndisk npart -# -r listado reducido (sin parches) +# -r listado reducido (sin parches de Windows) -PROG="$(basename $0)" +PROG=$(basename "$0") REDUCED="no" +if [ "$1" = "-r" ]; then + REDUCED="yes" + shift +fi if [ $# -ne 2 ]; then ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion" exit $? @@ -16,6 +20,7 @@ SERVERLOGDIR=$(mount | awk -v d=$OGLOG ' BEGIN {FS="[: ]"} {if ($4==d) dir=$2} END {print dir}') + # Fichero de listado: soft-IP-ndisco-npart SOFTFILE="soft-$(ogGetIpAddress)-$1-$2" # Redirigir salida al fichero de listado. diff --git a/client/shared/scripts/menuBrowser b/client/shared/scripts/menuBrowser index 164d5314..f544215d 100755 --- a/client/shared/scripts/menuBrowser +++ b/client/shared/scripts/menuBrowser @@ -1,8 +1,7 @@ #!/bin/bash # Scirpt de ejemplo para iniciar el browser del cliente con un menú predefinido -# (puede usarse como base para el programa de arranque usado por OpenGNSys Admin). -PROG="$(basename $0)" +PROG=$(basename "$0") if [ $# -ne 1 ]; then ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG urlmenu" exit $? diff --git a/client/shared/scripts/poweroff b/client/shared/scripts/poweroff index c108e08e..42330589 100755 --- a/client/shared/scripts/poweroff +++ b/client/shared/scripts/poweroff @@ -1,16 +1,28 @@ #!/bin/bash # Scirpt de ejemplo para apagar un ordenador -# (puede usarse como base para el programa de apagado usado por OpenGNSys Admin). +# Nota: se usa como base para el programa de apagado de OpenGnsys Admin. +# Registrar ejecución manual de script. +case "$(ogGetCaller)" in + browser|bash) ogEcho log info "Script: $0" ;; +esac + +# No registrar errores. +export DEBUG="no" + # Desmontar los sistemas de archivos y la caché local. echo "[10] Desmontar todos los sistemas de archivos." sync for (( i=1; i <= $(ogDiskToDev | wc -w); i++ )); do - ogUnmountAll $i 2>/dev/null + ogUnmountAll $i &>/dev/null done echo "[50] Desmontar cache local." -ogUnmountCache 2>/dev/null +ogUnmountCache &>/dev/null + +# Volver a registrar errores. +unset DEBUG + echo "[70] Apagando el equipo." # Estado correcto de Wake-On-Lan antes de apagar. ethtool -s $DEVICE wol g 2>/dev/null diff --git a/client/shared/scripts/reboot b/client/shared/scripts/reboot index 87e30e21..689da672 100755 --- a/client/shared/scripts/reboot +++ b/client/shared/scripts/reboot @@ -1,6 +1,12 @@ #!/bin/bash # Script de ejemplo para reiniciar un ordenador -# (puede usarse como base para el programa de reinicio usado por OpenGNSys Admin). +# Nota: se usa como base para el programa de reinicio de OpenGnsys Admin. + + +# Registrar ejecución manual de script. +case "$(ogGetCaller)" in + browser|bash) ogEcho log info "Script: $0" ;; +esac # Cargamos el valor por defecto del tiempo de sleep [ -z $OGSLEEP ] && source /opt/opengnsys/etc/engine.cfg @@ -16,14 +22,21 @@ else echo "[5] No se ha introducido un retardo, $TIME segundos para reiniciar" fi +# No registrar errores. +export DEBUG="no" + # Desmontar los sistemas de archivos y la caché local. echo "[10] Desmontar todos los sistemas de archivos." sync for (( i=1; i <= $(ogDiskToDev | wc -w); i++ )); do - ogUnmountAll $i 2>/dev/null + ogUnmountAll $i &>/dev/null done echo "[50] Desmontar cache local." -ogUnmountCache 2>/dev/null +ogUnmountCache &>/dev/null + +# Volver a registrar errores. +unset DEBUG + echo "[90] Reiniciar el equipo." # Estado correcto de Wake-On-Lan antes de reiniciar. ethtool -s $DEVICE wol g 2>/dev/null diff --git a/client/shared/scripts/restoreBaseImage b/client/shared/scripts/restoreBaseImage index c4e87ba4..2d7e46de 100755 --- a/client/shared/scripts/restoreBaseImage +++ b/client/shared/scripts/restoreBaseImage @@ -2,7 +2,7 @@ #/** # restoreBaseImage #@brief Script de ejemplo para restaurar una imagen -#@brief (puede usarse como base para el programa de restauración de imágenes usado por OpenGNSys Admin). +#@brief Se usa como base para el programa de restauración de imágenes de OpenGnsys Admin). #@param 1 REPO|CACHE #@param 2 imagen #@param 3 disco diff --git a/client/shared/scripts/restoreDiffImage b/client/shared/scripts/restoreDiffImage index 6bd7b1df..bf333bd8 100755 --- a/client/shared/scripts/restoreDiffImage +++ b/client/shared/scripts/restoreDiffImage @@ -2,7 +2,7 @@ #/** # restoreDiffImage #@brief Script de ejemplo para restaurar una imagen diferencial. -#@brief (puede usarse como base para el programa de restauración de imágenes usado por OpenGNSys Admin). +#@brief Se usa como base para el programa de restauración de imágenes de OpenGnsys Admin). #@param 1 REPO|CACHE #@param 2 imagen basica #@param 3 imagen diferencial diff --git a/client/shared/scripts/restoreImage b/client/shared/scripts/restoreImage index 6d5198aa..d9e7f584 100755 --- a/client/shared/scripts/restoreImage +++ b/client/shared/scripts/restoreImage @@ -1,6 +1,25 @@ #!/bin/bash -# Script de ejemplo para restaurar una imagen. -# (puede usarse como base para el programa de restauración de imágenes usado por OpenGNSys Admin). +#/** +#@file restoreImage +#@brief Script de ejemplo para restaurar una imagen. +#@param $1 Repositorio (CACHE, REPO o dirección IP) +#@param $2 Nombre canónico de la imagen (sin extensión) +#@param $3 Número de disco +#@param $4 Número de particion +#@param $5 Protocolo (UNICAST, UNICAST-DIRECT, MULTICAST o MULTICAST-DIRECT) +#@param $6 Opciones del protocolo +#@exception OG_ERR_FORMAT 1 formato incorrecto. +#@exception OG_ERR_NOTFOUND 2 cambio de repositorio: repositorio no encontrado +#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados. +#@exception $OG_ERR_MCASTRECEIVERFILE 57 Error en la recepción Multicast de un fichero +#@exception $OG_ERR_PROTOCOLJOINMASTER 60 Error en la conexión de una sesión Unicast|Multicast con el Master +#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-06-16 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 +#**/ TIME1=$SECONDS PROG="$(basename $0)" @@ -17,7 +36,7 @@ fi # Clear temporary file used as log track by httpdlog # Limpia los ficheros temporales usados como log de seguimiento para httpdlog echo " " > $OGLOGCOMMAND -[ "$(ogGetCaller)" == "deployImage" ] || echo -n "" > $OGLOGSESSION; +ogCheckStringInGroup "$(ogGetCaller)" "deployImage restoreImageCustom" || echo -n "" > $OGLOGSESSION; ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" @@ -29,7 +48,25 @@ PART="$4" PROTO="${5^^}" PROTO=${PROTO:-"UNICAST"} PROTOOPT="$6" +# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento +if [ "${PROTO%-*}" == "MULTICAST" ] && [[ ${PROTOOPT##*:} =~ ^-?[0-9]+$ ]]; then + [ ${MCASTWAIT:-0} -lt ${PROTOOPT##*:} ] && let MCASTWAIT=${PROTOOPT##*:}+5 +fi IMGTYPE="${IMGTYPE:-"img"}" + +# Unidad organizativa +[ "$ogunit" != "" ] && OGUNIT="$ogunit/" + +# Si es una ip y es igual a la del equipo restaura desde cache +[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE" +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPO +if [ $? == 0 -o $REPO == "REPO" ] ; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO ${OGUNIT%/} || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO $OGUNIT'; echo $?) + REPO="REPO" +fi + # Comprobar que existe la imagen del origen. IMGFILE=$(ogGetPath "$REPO" "$IMGNAME.$IMGTYPE") IMGDIR=$(ogGetParentPath "$REPO" "$IMGNAME") @@ -52,7 +89,7 @@ case "$PROTO" in COMPRESS=$(ogGetImageCompressor REPO $IMGNAME) #TODO comprobar parametros anteriores ogEcho log session "[40] ogMcastReceiverPartition $DISK $PART $PORT $TOOL $COMPRESS" - ogMcastRequest "$IMGNAME.img" "$PROTOOPT" + ogMcastRequest "$IMGNAME.img" "$PROTOOPT" || exit $? ogExecAndLog command ogMcastReceiverPartition "$DISK" "$PART" "$PORT" "$TOOL" "$COMPRESS" RETVAL=$? ;; diff --git a/client/shared/scripts/restoreImageCustom.template b/client/shared/scripts/restoreImageCustom.template index da32779c..bb94ad10 100644 --- a/client/shared/scripts/restoreImageCustom.template +++ b/client/shared/scripts/restoreImageCustom.template @@ -11,13 +11,16 @@ # Control de parámetros. -[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: createImageCustom int_ndisc int_npart str_repo str_imgname" || exit $? +[ $# -ge 4 -a $# -le 6 ] || ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: restoreImageCustom str_repo str_imagen int_ndisco int_npart [ str_proto [\"str_opciones\"] ]" || exit $? # Toma de parámetros. -DISK="$1" # Nº de disco. -PART="$2" # Nº de partición. -REPO="${3^^}" # Repositorio (en mayúsculas). -IMGNAME="$4" # Nombre canónico de imagen (sin extensión). +REPO="${1^^}" # Repositorio (en mayúsculas). +IMGNAME="$2" # Nombre canónico de imagen (sin extensión). +DISK="$3" # Nº de disco. +PART="$4" # Nº de partición. +PROTO="${5^^}" # Protocolo de comunicaciones (por defecto, UNICAST). +PROTO=${PROTO:-"UNICAST"} +PROTOOPT="$6" # Opciones del protocolo separadas por ":" (opcional). # Paso 0: Añadir código para realizar control de errores de los parámetros de entrada (recomendado). diff --git a/client/shared/scripts/setBootMode b/client/shared/scripts/setBootMode index 4ab9c816..81eec28c 100755 --- a/client/shared/scripts/setBootMode +++ b/client/shared/scripts/setBootMode @@ -4,32 +4,44 @@ #@brief Script to configure the PXE mode to client #@param 1 template #@date 2012-02-2-9 +#@version 1.0.1 - Recoge como parametro el nombre interno de la plantilla en vez del nombre de fichero para que funcione correctamente al llamar a setclientmode y anade un nuevo parametro de modo de trabajo (0 o 1) que indica que el cambio del fichero PXE del servidor sera temporal o permanente +#@author Juan Carlos Garcia - Univ. Zaragoza +#@date 2015-11-17 #*/ ## -REPOIP="$(ogGetRepoIp)" +#REPOIP="$(ogGetRepoIp)" + +# Asignamos la IP del servidor de administracion que es el destino del script +SERVERIP="$(ogGetServerIp)" PORT=2011 -TEMPLATE="/opt/oglive/tftpboot/menu.lst/templates/$1" +TEMPLATE=$(grep -l "^#.* $1 *$" /opt/oglive/tftpboot/menu.lst/templates/*) PCNAME="$(hostname)" PROG="$(basename $0)" if [ "$*" == "help" ]; then - ogHelp "$PROG" "$PROG template" \ - "$PROG pxe" \ - "$PROG 01" + ogHelp "$PROG" "$PROG template [ 0 | 1 ] (0 - Temporary 1, - Permanent) " \ + "$PROG ogLive 1" \ + "$PROG 1hd-1partition 0" exit fi # Control básico de errores. -if [ $# -ne 1 ]; then - ogRaiseError $OG_ERR_FORMAT "$MSG_ERR_FORMAT: $PROG TEMPLATE_NAME" +if [ $# -ne 2 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_ERR_FORMAT: $PROG TEMPLATE_NAME [ 0 | 1 ] (0 - Temporary, 1 - Permanent)" exit $? fi -if [ ! -e $TEMPLATE ]; then - ogRaiseError $OG_ERR_NOTFOUND "$MSG_ERR_NOTFOUND: $TEMPLATE" + +if [ -z "$TEMPLATE" ]; then + ogRaiseError $OG_ERR_NOTFOUND "$MSG_ERR_NOTFOUND: $1" exit $? fi -hose $REPOIP $PORT --out sh -c "echo -ne SET_CLIENTMODE $1 $PCNAME" +if [ $2 != "0" ] && [ $2 != "1" ]; then + ogRaiseError $OG_ERR_NOTFOUND "$MSG_ERR_FORMAT: modo $2 no existe" + exit $? +fi +# Crea un pipe con el servidor de administracion que llama a setclientmode pasandole los parametros de nombre de plantilla, nombre PC y modo de trabajo (0 o 1) +hose $SERVERIP $PORT --out sh -c "echo -ne SET_CLIENTMODE $1 $PCNAME $2" diff --git a/client/shared/scripts/updateBootCache b/client/shared/scripts/updateBootCache index f45e9344..f2e4e72b 100755 --- a/client/shared/scripts/updateBootCache +++ b/client/shared/scripts/updateBootCache @@ -6,28 +6,41 @@ #@param 1 #@param ejemplo: #@return -#@exception OG_ERR_FORMAT formato incorrecto. +#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15 +#@exception OG_ERR_NOTFOUND=2 # Fichero o dispositivo no encontrado. #@note #@todo: #@version 1.0.1 - requiere el gestor de arranque grub2dos #@author Antonio J. Doblas Viso. Universidad de Malaga. #@date 2010/07/27 +#@version 1.1.0 - Permite varios ogLive dentro de subdirectorios +#@author Irina Gómez. ETSII Universidad de Sevilla +#@date 2017/04/27 +#@version 1.1.0 - Se permite varios ogLives en la CACHE +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2017/05/31 +#@version 1.1.0 - Limpieza de codigo, control errores +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2018-01-21 #*/ ## +OGLIVEDIR=${oglivedir:-"ogLive"} +OGBTFTP="/opt/oglive/tftpboot/$OGLIVEDIR" +OGBCACHE="$OGCAC/boot/$OGLIVEDIR" +#control de errores +[ -d "$OGBTFTP" ] || exit $(ogRaiseError $OG_ERR_NOTFOUND "$OGBTFTP"; echo $?) +ogMountCache || exit $(ogRaiseError $OG_ERR_NOTCACHE "CACHE "; echo $?) -OGBTFTP="/opt/oglive/tftpboot/ogclient" -ogMountCache || exit 1 - -[ -d $OGCAC/boot ] || mkdir -p $OGCAC/boot +[ -d $OGBCACHE ] || mkdir -p $OGBCACHE # comparamos los del server - SERVERVMLINUZ=`cat ${OGBTFTP}/ogvmlinuz.sum` - SERVERINITRD=`cat ${OGBTFTP}/oginitrd.img.sum` + SERVERVMLINUZ=`cat ${OGBTFTP}/ogvmlinuz.sum 2>/dev/null` + SERVERINITRD=`cat ${OGBTFTP}/oginitrd.img.sum 2>/dev/null` #comparamos los de la cache - CACHEVMLINUZ=`cat ${OGCAC}/boot/ogvmlinuz.sum` - CACHEINITRD=`cat ${OGCAC}/boot/oginitrd.img.sum` + CACHEVMLINUZ=`cat ${OGBCACHE}/ogvmlinuz.sum 2>/dev/null` + CACHEINITRD=`cat ${OGBCACHE}/oginitrd.img.sum 2>/dev/null` echo "MD5 on SERVER: $SERVERVMLINUZ $SERVERINITRD" echo "MD5 on CACHE: $CACHEVMLINUZ $CACHEINITRD" @@ -36,25 +49,17 @@ ogMountCache || exit 1 if [ "$CACHEVMLINUZ" != "$SERVERVMLINUZ" ] then echo "ogvmlinuz updating" - cp ${OGBTFTP}/ogvmlinuz ${OGCAC}/boot/ogvmlinuz - cp ${OGBTFTP}/ogvmlinuz.sum ${OGCAC}/boot/ogvmlinuz.sum + cp "${OGBTFTP}/ogvmlinuz" "${OGBCACHE}/ogvmlinuz" + cp "${OGBTFTP}/ogvmlinuz.sum" "${OGBCACHE}/ogvmlinuz.sum" DOREBOOT=true fi if [ "$CACHEINITRD" != "$SERVERINITRD" ] then echo "oginitrd updating" - cp ${OGBTFTP}/oginitrd.img ${OGCAC}/boot/oginitrd.img - cp ${OGBTFTP}/oginitrd.img.sum ${OGCAC}/boot/oginitrd.img.sum + cp "${OGBTFTP}/oginitrd.img" "${OGBCACHE}/oginitrd.img" + cp "${OGBTFTP}/oginitrd.img.sum" "${OGBCACHE}/oginitrd.img.sum" DOREBOOT=true fi echo $DOREBOOT # [ "$DOREBOOT" == "true" ] && busybox reboot -f - -#TODO: Comprobar si es necesario -#cp -prv cp ${OGBTFTP}/ ${OGCAC}/boot/ - -#TODO -#/opt/opengnsys/lib/grub4dos/bootlace.com /dev/sda - - diff --git a/client/shared/scripts/updateCache b/client/shared/scripts/updateCache index 8760ddd2..7c3f4534 100755 --- a/client/shared/scripts/updateCache +++ b/client/shared/scripts/updateCache @@ -12,6 +12,8 @@ #@exception OG_ERR_FORMAT formato incorrecto. #@exception OG_ERR_NOTCACHE No existe cache -15- #@exception $OG_ERR_CACHESIZE Tamaño de la paticion menor al archivo a descargar -16- +#@exception $OG_ERR_MCASTRECEIVERFILE Error en la recepción Multicast de un fichero -57- +#@exception $OG_ERR_PROTOCOLJOINMASTER Error en la conexión de una sesión Unicast|Multicast con el Master -60- #@note #@todo: #@version 0.9.1 - integracion EAC @@ -27,7 +29,12 @@ #@date 2013-02-20 #@version 1.0.5 - uso de md5 full para las transferencias torrent, en la llamada => ogUpdateCacheIsNecesary #@date 2014-07-09 - +#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-06-16 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 #*/ ## PROG="$(basename $0)" @@ -42,11 +49,32 @@ fi # Clear temporary file used as log track by httpdlog # Limpia los ficheros temporales usados como log de seguimiento para httpdlog echo " " > $OGLOGCOMMAND -[ "$(ogGetCaller)" == "deployImage" -o "$(ogGetCaller)" == "restoreBaseImage" -o "$(ogGetCaller)" == "restoreDiffImage" ] || echo -n "" > $OGLOGSESSION; + +if ! [ "$(ogGetCaller)" == "deployImage" -o "$(ogGetCaller)" == "restoreBaseImage" -o "$(ogGetCaller)" == "restoreDiffImage" ]; then + echo -n "" > $OGLOGSESSION; + + # Registro de inicio de ejecución + ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" +fi REPOSITORIO="${1^^}" PROTOCOLO="${3^^}" OPTPROTOCOLO="$4" +# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento +if [ "${PROTOCOLO%-*}" == "MULTICAST" ] && [[ ${OPTPROTOCOLO##*:} =~ ^-?[0-9]+$ ]]; then + [ ${MCASTWAIT:0} -lt ${OPTPROTOCOLO##*:} ] && let MCASTWAIT=${OPTPROTOCOLO##*:}+5 +fi + +# Unidad organizativa. +[ "$ogunit" != "" ] && OGUNIT="$ogunit/" + +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPOSITORIO +if [ $? == 0 -o $REPOSITORIO == "REPO" ] ; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPOSITORIO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND $REPOSITORIO; echo $?) + REPOSITORIO="REPO" +fi REPOIP=$(ogGetRepoIp) ogEcho log session $REPOSITORIO $REPOIP $PROTOCOLO $OPTPROTOCOLO @@ -75,7 +103,7 @@ else # Si la imagen es monolitica y ha elegido protocolo = RSYNC salimos con error. [ $PROTOCOLO == "RSYNC" ] && exit $(ogRaiseError session $OG_ERR_DONTSYNC_IMAGE "REPO $2"; echo $?) IMGSYNC=FALSE - ogUpdateCacheIsNecesary "$1" "$2" "$PROTOCOLO" + ogUpdateCacheIsNecesary "$REPOSITORIO" "$2" "$PROTOCOLO" RETVAL=$? fi # si RETVAL=0 => actualizamos si RETVAL=1 no actaulizasmo-exit 0 || si RETVAL>2 exit 1 @@ -174,7 +202,7 @@ TIME1=$SECONDS case "$PROTOCOLO" in TORRENT) - ogEcho log session "ogCopyFile $1 $2.torrent absolute $OGCAC/$OGIMG" + ogEcho log session "ogCopyFile $REPOSITORIO $2.torrent absolute $OGCAC/$OGIMG" # tiempos timewait=$(expr $(printf '%d\n' 0x$(ogGetMacAddress | awk -F: '{print $5$6}')) \* 120 / 65535) ogExecAndLog command ogCopyFile $REPOSITORIO "$2.torrent" "$IMGDIR" @@ -182,7 +210,7 @@ case "$PROTOCOLO" in #TODO comprobar que el fichero torrent está en cache # retardamos el inicio -aleatorio de 0 a 120 segundos- al tracker para gestionar mas de +-40 equipos P2PWAIT=$[ ( $RANDOM % 120 ) + 1 ] - ogEcho log session " [ ] $MSG_SCRIPTS_TASK_SLEEP : $P2PWAIT seconds ogTorrentStart CACHE $2.torrent $4" + ogEcho log session " [ ] $MSG_SCRIPTS_TASK_SLEEP : $P2PWAIT seconds" sleep $P2PWAIT ogEcho log session " [ ] $MSG_SCRIPTS_TASK_START: ogTorrentStart CACHE $2.torrent $4" ogExecAndLog command ogTorrentStart CACHE "$2.torrent" $4 @@ -193,34 +221,15 @@ case "$PROTOCOLO" in fi ;; MULTICAST) - PORT=$(echo $OPTPROTOCOLO | cut -f1 -d":") - let PORTAUX=$PORT+1 ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION : $REPOIP:$PORTAUX:$PORT" #TODO: ticket 379 NUMBER=$[ ( $RANDOM % 30 ) + 1 ] sleep $NUMBER #FIN TODO - if (nmap -n -sU -p $PORTAUX $REPOIP | grep open) - then - ogExecAndLog command ogMcastReceiverFile $PORT CACHE "$2" - - else - # TODO ticket 379 Realizar la petición basada en identificador de operacion - ogEcho log session "$MSG_SCRIPTS_TASK_START : hose $REPOIP 2009 --out sh -c \"echo -ne START_MULTICAST $2 $OPTPROTOCOLO\"" - hose $REPOIP 2009 --out sh -c "echo -ne START_MULTICAST $2 $OPTPROTOCOLO" - #echo "espero y llamo a: ogMcastReceiverFile $PORT CACHE $2" - sleep 10 - if (nmap -n -sU -p $PORTAUX $REPOIP | grep open) - then - ogExecAndLog command ogMcastReceiverFile $PORT CACHE "$2" - else - ogEcho log session "$MSG_SCRIPTS_TASK_ERR : hose $REPOIP 2009 --out sh -c echo -ne START_MULTICAST $2 $OPTPROTOCOLO" - exit $OG_ERR_UPDATECACHE - fi - fi - #cat $OGLOGCOMMAND.tmp | grep -B1 "Transfer complete" - sleep 5 - #cat $OGLOGCOMMAND.tmp | grep -B1 "Transfer complete" + ogEcho log session ogMcastRequest "$2" $OPTPROTOCOLO + ogExecAndLog command ogMcastRequest "$2" $OPTPROTOCOLO || exit $? + ogEcho log session ogMcastReceiverFile ${OPTPROTOCOLO%%:*} CACHE "$2" + ogExecAndLog command ogMcastReceiverFile ${OPTPROTOCOLO%%:*} CACHE "$2" || exit $? RESUMEUPDATECACHE=$(grep -m 1 -B1 "Transfer complete" $OGLOGCOMMAND.tmp) ;; UNICAST) @@ -242,8 +251,8 @@ case "$PROTOCOLO" in if [ -d $REPOFILE ]; then # Si es sincronizada tipo directorio. [ -d "$OGCAC$OGIMG/$2" ] || mkdir "$OGCAC$OGIMG/$2" - ogEcho log session "rsync -aHAX$OPTRSYNC $USERRSYNC@$REPOIP::ogimages/$2/ $OGCAC$OGIMG/$2" - rsync -aHAX$OPTRSYNC $PASSWORD "$USERRSYNC@$REPOIP::ogimages/$2/" "$OGCAC$OGIMG/$2" 2>> $OGLOGCOMMAND | egrep "^sent|^sending|^total%" >> $OGLOGCOMMAND + ogEcho log session "rsync -aHAX$OPTRSYNC $USERRSYNC@$REPOIP::ogimages/$OGUNIT$2/ $OGCAC$OGIMG/$2" + rsync -aHAX$OPTRSYNC $PASSWORD "$USERRSYNC@$REPOIP::ogimages/$OGUNIT$2/" "$OGCAC$OGIMG/$2" 2>> $OGLOGCOMMAND | egrep "^sent|^sending|^total%" >> $OGLOGCOMMAND else # Si es sincronizada tipo archivo. [ "${2##*.}" == "img" ] && IMGTYPE="img" || IMGTYPE="diff" @@ -273,7 +282,8 @@ case "$PROTOCOLO" in [ ${PIPESTATUS[0]} -eq 0 ] && RETVAL="1"|| RETVAL="2" # Desmonto las imagenes ogUnmountImage CACHE "$IMGNAME" $IMGTYPE - ogUnmountImage REPO "$IMGNAME" $IMGTYPE + ogUnmountImage REPO "$IMGNAME" $IMGTYPE + ogUnlockImage CACHE "$2" fi ;; esac diff --git a/doc/CHANGELOG.es.txt b/doc/CHANGELOG.es.txt index 94623a52..599d04eb 100644 --- a/doc/CHANGELOG.es.txt +++ b/doc/CHANGELOG.es.txt @@ -2,12 +2,121 @@ LISTA DE CAMBIOS CHANGELOG.es.txt ======================================== + +Lista de cambios incluidos en OpenGnsys 1.1.0 +--------------------------------------------- + +Tickets resueltos en módulo OpenGnsys Cloning Engine: +#141 Reconstruir función ogDiskToDev (resuelto en #748) +#544 Comprobar si Windows está en dominio antes de cambiar nombre en script de inicio de sesión (no se resolverá) +#676 Soportar sistema de ficheros ZFS +#678 Unidades organizativas con directorio de imágenes separado (mejora) +#716 Revisión ogCleanLinuxDevices +#722 Multicast entre subredes (mejora) +#726 Reducir el registro de errores y avisos en algunas operaciones +#727 ogGrubHidePartitions comprueba tipo de partición con blkid en vez revisar las entradas del Grub +#731 Soporte para cualquier versión de Windows +#740 Clonar disco completo en modo "raw" +#744 Gestionar bloqueos de disco +#748 Mejorar rendimiento usando fichero de configuración de discos (mejora) +#770 Imágenes sincronizadas: transferencia multicast (mejora) +#771 Crear imagen no muestra correctamente el espacio necesario y disponible +#781 Control de errores en la transferencia multicast +#790 ogLive Xenial no identifica el orden correcto de varios discos duros sata +#791 ogGrubInstallMBR con dos discos duros +#796 Burg como systemMenu gráfico +#815 Crear Imagen: cálculo del espacio libre en el repositorio (mejora) +#823 Mejorar el rendimiento al obtener el inventario de software de Windows (mejora) +#827 ogGrubInstallMbr debe mostrar entrada al ogLive, como ogBurgInstallMbr +#829 Funciones auxiliares de configuración de BURG +#832 Fallo en Autologon de Windows 10 + +Tickets resueltos en módulo OpenGnsys Client: +#233 Añadir reloj al cliente (resuelto en #746) +#244 Internacionalización de los mensajes del Browser (mejora) +#528 busybox tftp ogLive con acceso subdirectorio contenedor tftpd del server +#625 Modo offline: segundo sistema de ficheros en cache/USB (duplicado de #467) +#709 Script para instalar módulos del Kenrel en el cliente ogLive +#717 Indicar manualmente parámetros de arranque de un SO (mejora) +#724 Cliente ogLive 1.1.0 basado en Ubuntu 15.10 o Ubuntu 16.04 LTS +#725 Sincronización horaria de clientes con servidor NTP +#746 Reestructurar barra de estado del Browser del cliente (mejora) +#769 ogLive ampliar espacio de memoria para instalar software en "caliente" y exportar proxy de https(s) y ftp(s) +#773 Incluir script personalizado para bootOs (mejora) +#774 Soportar clientes ogLive de 64 bits +#783 Browser registra salida de comandos ejecutados al pulsar enlace (mejora) +#786 Adaptar el ogLive-precise-3.2.0-23-generic-r4820.iso como ogLive de 32 bits +#813 Restaurar Imagen no muestra el error en la cola de acciones + +Tickets resueltos en módulo OpenGnsys Server: +#234 Importar/Exportar base de datos (resuelto en #755) +#385 Servicios OpenGnsys para varias VLAN aisladas (no se resolverá) +#723 Cambio temporal de fichero de arranque PXE (mejora) +#736 Mejorar la seguridad del servidor (mejora) +#745 Depurar ogAdmServer (duplicado de #559) +#787 Todos los elementos del ogLive se localizan en el Server + +Tickets resueltos en módulo OpenGnsys Repository Server: +#379 Usar identificador de operación para el ogAdmRepoAux (no se resolverá) +#701 torrent-creator falla si el fichero de imagen a procesar no es válido +#743 Funcion en el webservice API REST para wakeonlan (mejora) +#810 API REST de respositorio para listado de imágenes +#820 checkperms da error al cambiar permisos sobre el directorio de agrupamiento de imágenes en el repo + +Tickets resueltos en módulo OpenGnsys Web Admin Console: +#372 Comandos y asistentes deberían limitar equipos de operación dentro de ámbito +#711 Mostrar porcentaje de uso de cada sistema de archivos (mejora) +#712 Formulario añadir nuevo ordenador no verifica la existencia previa del equipo +#713 Mejorar el inventario de hardware y obtener número de serie (mejora) +#714 Comando Particionar y Formatear no se ejecuta en ámbito superior a un ordenador +#720 Fallo en alerta de Unicast al restaurar imagen +#732 Ampliar el calendario de programación de acciones más allá de 2015 +#737 Incluir número de revisión de creación de imágenes (mejora) +#738 Se pierde nombre de la imagen restaurada +#747 Uso incorrecto del número de puestos de las propiedades del aula +#751 Asistente de particionado: particiones GPT (mejora) +#767 Revisar estabilidad del asistente de particionado +#775 Permitir mismo nombre de imagen en diferentes repositorios de imagen +#777 Error SQL al incluir caracteres espaciales en los comentarios +#778 Codificar claves de usuarios (mejora) +#779 Crear comando "Enviar mensaje" +#782 Crear registro de acciones para realizar informes +#789 Actualizar plantilla PXE al mover ordenador +#792 Incluir en los html personalizados de ejemplo los enlaces al acceso privado +#797 Revisar log en los procesos de restauración +#798 Mostrar imágenes en orden alfabético +#799 Consola web: estado de los equipos tarda en mostar +#806 Comando Particionar y Formatear: controlar que no se exceda el tamaño del disco +#807 Consola Web: Incorporar ordenadores da error de time-out +#814 Sustituir las etiquetas cortas de php por el formato largo +#817 Correcciones al formulario propiedades del aula +#818 Actualización ficheros PXE tras modificar propiedad de IP del repositorio +#819 Eliminar un objeto ordenador no elimina fichero PXE +#821 Comando Particionar sólo funciona correctamente en al ámbito de tipo ordenador +#822 Llamar al updateBootCache desde el particionado de la cache +#828 Identificador de perfil hardware disponible desde el ogLive y eliminación de winboot + +Tickets resueltos en módulo OpenGnsys Installer: +#755 Scripts para exportar e importar los datos de OpenGnsys +#765 Actualización incremental de la base de datos +#795 Script opengnsys_uninstall.sh deberia añadir mas información +#801 Script opengnsys_update.sh con URL de descarga incorrecto + +Tickets genéricos resueltos: +#679 Varios repositorios para un mismo cliente (tarea) +#708 Crear API REST para integración de OpenGnsys con UDS (tarea) +#718 Nuevo agente modular con comunicaciones REST (tarea) +#730 Integración de rama OpenGnsys 1.1.0 en rama principal (tarea) +#739 Estandarizar entornos virtuales de desarrollo con Vagrant (tarea) +#768 Ofrecer diferentes ogLive a los clientes (tarea) +#831 Manuel de usuario OpenGnsys 1.1.0 + + Lista de cambios incluidos en OpenGnSys 1.0.6b (versión de mantenimiento) ---------------------------------------------- Tickets resueltos en módulo OpenGnSys Cloning Engine: #715 Revisión ogConfigureFstab -#724 Compatible con ogLive basado en Ubuntu 15.10 y Ubuntu 16.04 LTS (parcial) #756 Comprobar cambios funciones en Disk.lib en el ogLive con kernel 3.2 #760 Eliminar CHKDSK en el primer arranque de un Windows restaurado #762 ogGetLastSector error en modelo HP 6300 con disco duro de 1 TB @@ -47,7 +156,6 @@ Tickets resueltos en módulo OpenGnSys Server: Tickets resueltos en módulo OpenGnSys Web Admin Console: #721 Consola Restaurar Imagen: falla el filtro de equipos -#732 Ampliar el calendario de programación de acciones más allá de 2015 (parcial) Tickets genéricos resueltos: #734 Liberar versión de mantenimiento OpenGnSys 1.0.6a en rama principal @@ -105,7 +213,7 @@ Tickets resueltos en módulo OpenGnSys Installer: Tickets resueltos en módulo OpenGnSys Web Admin Console: #512 Asistente particionado: comprobar que las particiones no sobrepasan disco (mejora) -#654 Eliminar imagen de caché duplica algunas imágenes. +#654 Eliminar imagen de caché duplica algunas imágenes #655 Gestión Arranque Avanzado: opción eliminar no muestra plantillas (no válido) #658 Correccion en eliminar imagen de caché de cliente #661 Error al mostrar configuración de varios equipos con caché @@ -705,7 +813,7 @@ Tickets resueltos en módulo OpenGnSys Installer: #171 binarios y scripts para multicast Tickets genéricos resueltos: -#129 Decidir entre NFS y NBD. +#129 Decidir entre NFS y NBD Lista de cambios incluidos en OpenGnSys 0.9.1 diff --git a/doc/INSTALL.en.txt b/doc/INSTALL.en.txt index 33499bc2..4eef6920 100644 --- a/doc/INSTALL.en.txt +++ b/doc/INSTALL.en.txt @@ -17,7 +17,7 @@ Minimum storage requirements: Installation ------------ -To install OpenGnSys run opengnsys_installer.sh after unpacking the release file (opengnsys-release.tar.gz) o downloading it directly from http://www.opengnsys.es/svn/trunk/installer/opengnsys_installer.sh. +To install OpenGnsys, run opengnsys_installer.sh after unpacking the release file (opengnsys-release.tar.gz) o downloading it directly from https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh. Unpacking example: tar xvzf opengnsys-1.0.5.tar.gz @@ -26,10 +26,10 @@ Unpacking example: Download examples: * Download with wget. - wget http://www.opengnsys.es/svn/trunk/installer/opengnsys_installer.sh -O opengnsys_installer.sh + wget https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh -O opengnsys_installer.sh * Download with curl. - curl http://www.opengnsys.es/svn/trunk/installer/opengnsys_installer.sh > opengnsys_installer.sh + curl https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh > opengnsys_installer.sh You must be root to run the installation script: @@ -38,7 +38,7 @@ You must be root to run the installation script: The following information will be requested in order to configure the access to the service (a default value will be introduced if no parameter is indicated): * MySQL root password - * Web console user and OpenGnSys Super Administrator + * Web console user and OpenGnsys Super Administrator * Web console user's password * Client's password for accessing remote services @@ -46,16 +46,16 @@ The following processes will be carried out: * Gathering of the basic network parameters. * Checking the installed packages. * Downloading and installing dependencies. - * Creating OpenGnSys basic folder sctructure. + * Creating OpenGnsys basic folder sctructure. * Download the code repository to a temporal folder (/tmp/opengnsys_installer). In upcoming releases this process will not be necessary. - * Compiling and installing OpenGnSys services. - * Basic configuration of OpenGnSys network services (DHCP, PXE and Samba) using the existing configuration templates. + * Compiling and installing OpenGnsys services. + * Basic configuration of OpenGnsys network services (DHCP, PXE and Samba) using the existing configuration templates. * Copying additional server management files. - * Creating the database and configuring OpenGnSys administration console web server. + * Creating the database and configuring OpenGnsys administration console web server. * Copying web administration console pages. - * Copying the OpenGnSys client folder structure. - * Downloading OpenGnSys client initial image. - * Basic configuration of OpenGnSys services using network parameters. + * Copying the OpenGnsys client folder structure. + * Downloading OpenGnsys client initial image. + * Basic configuration of OpenGnsys services using network parameters. Once the installation is finished you can start working with the system: * Configuring DHCP. @@ -82,13 +82,11 @@ You must be root to run this script: Uninstall --------- -There is also an uninstall script for the OpenGnSys components: - * OpenGnSys files and data base will be deleted. +There is also an uninstall script for the OpenGnsys components: + * OpenGnsys files and data base will be deleted. * Packages belonging to the operating system and their configuration files will be preserved. * The image folder and its content will not be deleted. - - You must be root to run this script: sudo /opt/opengnsys/lib/opengnsys_uninstall.sh diff --git a/doc/INSTALL.es.txt b/doc/INSTALL.es.txt index c5f63e35..790ad58e 100644 --- a/doc/INSTALL.es.txt +++ b/doc/INSTALL.es.txt @@ -1,24 +1,24 @@ -Instalación de OpenGnSys Server v 1.0.6 +Instalación de OpenGnsys Server v 1.1.0 ======================================= Notas iniciales --------------- -Se presupone que el servidor de OpenGnSys va a ser instalado en una distribución del sistema operativo Ubuntu Server a partir de la versión 12.04 LTS (también ha sido probado en sistemas basados en Fedora 20 y CentOS 6.5). +Se presupone que el servidor de OpenGnsys va a ser instalado en una distribución del sistema operativo Ubuntu Server a partir de la versión 14.04 LTS (también ha sido probado en sistemas basados en CentOS 7). El serividor debe tener acceso a Internet para descargar los paquetes necesarios, el código del proyecto y el cliente preconfigurado. Requisitos mínimos de almacenamiento: - 100 MB en el directorio /tmp (solo durante la instalación) -- 500 MB en el directorio /var/lib/tftpboot (o /srv en sistemas Debian) -- 500 MB en el directorio de instalación /opt/opengnsys sin contar el espacio para logs (100 MB si el cliente ogLive está previamente descargado). +- 600 MB en el directorio /var/lib/tftpboot (o /srv en sistemas Debian) por cada cliente ogLive que se desee instalar. +- 250 MB en el directorio de instalación /opt/opengnsys más 600 MB por cada imagen ISO descargada de clientes ogLive. - Estimar la capacidad necesaria para el repositorio de imágenes en /opt/opengnsys/images (es recomendable que este directorio se monte sobre un sistema de archivos independiente). Instalación ----------- -La instalación de OpenGnSys se realiza ejecutando el script de instalación opengnsys_installer.sh, el cual puede obtenerse descomprimiendo el fichero de la versión opengnsys-Version.tar.gz o descargándolo directamente de la dirección: http://www.opengnsys.es/svn/trunk/installer/opengnsys_installer.sh +La instalación de OpenGnsys se realiza ejecutando el script de instalación opengnsys_installer.sh, el cual puede obtenerse descomprimiendo el fichero de la versión opengnsys-Version.tar.gz o descargándolo directamente de la dirección: https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh Ejemplos de descompresión del programa: @@ -28,10 +28,10 @@ Ejemplos de descompresión del programa: Ejemplos de descarga con varias herramientas: * Descargar con wget. - wget http://www.opengnsys.es/svn/trunk/installer/opengnsys_installer.sh -O opengnsys_installer.sh + wget https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh -O opengnsys_installer.sh * Descargar con curl. - curl http://www.opengnsys.es/svn/trunk/installer/opengnsys_installer.sh > opengnsys_installer.sh + curl https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh > opengnsys_installer.sh El script de instalación debe ser ejecutado como usuario root: @@ -40,24 +40,25 @@ El script de instalación debe ser ejecutado como usuario root: Dicho script solicitará por teclado la siguiente información para configurar el acceso al servicio (si no se indica un parámetro, toma el valor por defecto): * Clave del usuario root de MySQL. - * Usuario de acceso a la consola web y super-administrador de OpenGnSys. + * Usuario de acceso a la consola web y super-administrador de OpenGnsys. * Clave del usuario de acceso a la consola web. - * Clave de acceso del cliente a servicios remotos. + * Clave de acceso del cliente a servicios remotos. + * Seleccionar cliente(s) ogLive para instalar. Se realizan los siguientes procesos: * Obtener los parámetros básicos de la red. * Comprobar los paquetes instalados. * Descargar e instalar las dependencias que faltan. - * Crear la estructura básica de directorios de OpenGnSys. + * Crear la estructura básica de directorios de OpenGnsys. * Descargar el repositorio de código en un directorio temporal (/tmp/opengnsys_installer). Nota: en versiones futuras este proceso no será necesario. - * Compilar e instalar los servicios de OpenGnSys. + * Compilar e instalar los servicios de OpenGnsys. * Configuración básica de los serviciios de red DHCP, PXE y NFS/Samba a partir de las plantillas de configuración * Copiar ficheros complementarios de gestión del servidor. - * Crear la base de datos y configurar el servidor web de OpenGnSys Web Admin Console. + * Crear la base de datos y configurar el servidor web de OpenGnsys Web Admin Console. * Copiar los ficheros de las páginas de Web Admin Console. - * Copiar la estructura de directorios de OpenGnSys Client. - * Descargar la imagen inicial de OpenGnSys Client. - * Configuración básica de los serviciios de OpenGnSys a partir de los parámetros de red. + * Copiar la estructura de directorios de OpenGnsys Client. + * Descargar la o las imágenes iniciales de OpenGnsys Client. + * Configuración básica de los serviciios de OpenGnsys a partir de los parámetros de red. Una vez finalizada la ejecución del instalador, puede empezarse a trabajar con el sistema: * Configurar DHCP. @@ -85,10 +86,12 @@ El script debe ser ejecutado como usuario root: Desinstalación -------------- -También existe un script de desinstalación de los componentes de OpenGnSys, con las siguientes características: - * Se eliminan los ficheros de OpenGnSys y su base de datos. +También existe un script de desinstalación de los componentes de OpenGnsys, con las siguientes características: + * Solicita confirmación para ejecutar sus operaciones. + * Se eliminan los ficheros de OpenGnsys y su base de datos. * No se eliminan ni paquetes del sistema operativo ni sus ficheros de configuración. * No se elimina el directorio de las imágenes ni su contenido. + * No se eliminan los clientes ogLive ni las plantillas PXE. El script debe ser ejecutado como usuario root: diff --git a/doc/README.en.txt b/doc/README.en.txt index 149b600f..b82fe385 100644 --- a/doc/README.en.txt +++ b/doc/README.en.txt @@ -1,49 +1,49 @@ -The OpenGnSys Project README +The OpenGnsys Project README ================================ -OpenGnSys (pronounced Open Genesis) is based on a modular architecture separated in different service layers which allows its implementation in several educational and organizational IT environments, both in a centralized or distributed way. The main system management is carried out by means of a simple web interface which supports delegated administration. OpenGnSys is also suitable for isolated environments, being able to work under network failure conditions (offline mode). +OpenGnsys (pronounced Open Genesis) is based on a modular architecture separated in different service layers which allows its implementation in several educational and organizational IT environments, both in a centralized or distributed way. The main system management is carried out by means of a simple web interface which supports delegated administration. OpenGnsys is also suitable for isolated environments, being able to work under network failure conditions (offline mode). Architecture ------------ -From the point of view of clients, OpenGnSys Project is constituted by a set of separate modules in different layers of services. +From the point of view of clients, OpenGnsys Project is constituted by a set of separate modules in different layers of services. * The bottom layer is responsible for direct access to client devices and motor functions of cloning. * An intermediate layer consisting of a set of tools to perform complex tasks and environment customization. * Management module consists of a simple and intuitive web interface that allows common tasks to manage software distribution to clients. -Overall, OpenGnSys is a modular system that integrates a set of interrelated components and can be adapted to a variety of work settings possible. These components consist of standard services (file servers, web, database, DHCP, PXE, ...) and custom-developed tools for the project (cloning engine, console web, browser ad hoc, management demons repository and server, ...) which in combination offer everything OpenGnSys system. +Overall, OpenGnsys is a modular system that integrates a set of interrelated components and can be adapted to a variety of work settings possible. These components consist of standard services (file servers, web, database, DHCP, PXE, ...) and custom-developed tools for the project (cloning engine, console web, browser ad hoc, management demons repository and server, ...) which in combination offer everything OpenGnsys system. - * OpenGnSys Server + * OpenGnsys Server Basic service cloning system (DHCP, NFS/Samba, PXE, database, etc..) Necessary for the boot process and initial configuration of the clients. - * OpenGnSys Administrator + * OpenGnsys Administrator Centralized management web console (web pages, web services, etc.) with support for delegated administration, allowing control of all system components. - * OpenGnSys Repository Manager + * OpenGnsys Repository Manager Manager repository of images for each of the administrative units defined in the module OpenGnSys Administrator. There may be one or more modules depending on the model of the organization defined. - * OpenGnSys Client Agent + * OpenGnsys Client Agent Executing agent of orders in the client, which integrates the following features: - Graphical interface to select options predefined by the administrator. - Interactive execution of Cloning Engine functions in administrator mode. - Execution of the tasks sent from the OpenGnSys Administrator module. - * OpenGnSys Clonning Engine + * OpenGnsys Clonning Engine Motor function libraries cloning, installation and startup of the client operating systems. - * OpenGnSys Installer + * OpenGnsys Installer Software installation, upgrade and removal system which includes the settings generator, the clients boot generator, the component package builder, etc. Scenarios --------- -OpenGnSys is a modular system that can be used in different scenarios within an Institution, both educational and organizational. +OpenGnsys is a modular system that can be used in different scenarios within an Institution, both educational and organizational. - * Educational Scenarios: OpenGnSys can lend support to some of the educational settings defined by the Working Group-Net Teaching RedIRIS. + * Educational Scenarios: OpenGnsys can lend support to some of the educational settings defined by the Working Group-Net Teaching RedIRIS. - Classroom teaching: allowing the management and implementation of software installation on the computers of teachers, with ability to customize the settings according to user requirements. - Classroom teaching ICT Classrooms: implementing methods independent support for PCs of students and teachers. @@ -58,10 +58,13 @@ OpenGnSys is a modular system that can be used in different scenarios within an Origins -OpenGnSys born in May 2009 after the Working Groups RedIRIS held in Malaga as an effort to integrate several projects in development: +OpenGnsys born in May 2009 after the Working Groups RedIRIS held in Malaga as an effort to integrate several projects in development: * Brutalix, University of Zaragoza * Entorno Avanzado de Clonación (EAC), University of Málaga. * Web Hidra Interface, University of Seville. +OpenGnsys homepage: + https://opengnsys.es/ + diff --git a/doc/README.es.txt b/doc/README.es.txt index eba0784c..60c8af9d 100644 --- a/doc/README.es.txt +++ b/doc/README.es.txt @@ -1,15 +1,15 @@ -Proyecto OpenGnSys +Proyecto OpenGnsys ================== -El proyecto OpenGnSys (léase OpenGenesis) reúne el esfuerzo conjunto de varias Universidades Públicas españolas para construir una aplicación que permita una fácil gestión centralizada de ordenadores y servidores. Con ella se permite la distribución, instalación y despliegue de distintos sistemas operativos. +El Proyecto OpenGnsys (léase OpenGénesis) reúne el esfuerzo conjunto de varias Universidades Públicas españolas para construir una aplicación que permita una fácil gestión centralizada de ordenadores y servidores. Con ella se permite la distribución, instalación y despliegue de distintos sistemas operativos. -OpenGnSys nace debido a la necesidad de disponer de un conjunto de herramientas libres y abiertas que constituyan un sistema completo de gestión y clonación de equipos, versátil e intuitivo, que pueda ser utilizado tanto en la gestión de aulas de informática, como para reinstalar ordenadores y servidores. +OpenGnsys nace debido a la necesidad de disponer de un conjunto de herramientas libres y abiertas que constituyan un sistema completo de gestión y clonación de equipos, versátil e intuitivo, que pueda ser utilizado tanto en la gestión de aulas de informática, como para reinstalar ordenadores y servidores. Está basado en una arquitectura cliente/servidor. El ordenador cliente realiza una petición de conexión durante su proceso de arranque y el servidor le devuelve sus datos de red y un menú de inicio. En tal página el usuario puede seleccionar las acciones predefinidas por el administrador, ejecutar dichas acciones automáticamente sin intervención del usuario final o entrar directamente en una interfaz administrativa. -La gestión principal del sistema está basada en una sencilla interfaz web que permite realizar las tareas comunes para gestionar la distribución de software en los distintos clientes. Sin embargo, la estructura de OpenGnSys es lo suficientemente versátil como para adaptarse a las necesidades de las diferentes arquitecturas de redes de ordenadores disponibles en empresas e instituciones. +La gestión principal del sistema está basada en una sencilla interfaz web que permite realizar las tareas comunes para gestionar la distribución de software en los distintos clientes. Sin embargo, la estructura de OpenGnsys es lo suficientemente versátil como para adaptarse a las necesidades de las diferentes arquitecturas de redes de ordenadores disponibles en empresas e instituciones. -OpenGnSys está constituido por un conjunto de módulos separados en distintas capas de servicios. +OpenGnsys está constituido por un conjunto de módulos separados en distintas capas de servicios. * La capa inferior se encarga del acceso directo a los dispositivos del cliente y de las funciones del motor de clonación. * Una capa intermedia está constituida por un conjunto de herramientas para realizar tareas complejas y personalización del entorno. @@ -19,15 +19,18 @@ Los procesos específicos de configuración y modificación de datos en cada uno En el estado actual de desarrollo del Proyecto, se permite la clonación y despliegue de sistemas operativos Windows (incluido Windows 7) con sistemas de ficheros FAT32 y NTFS, así como distribuciones Linux con Sistemas de ficheros Ext2, Ext3 y Ext4. -Algunos de los aspectos principales de la futura línea de trabajo de OpenGnSys son la capacidad de gestión de discos redundantes, volúmenes lógicos y tener la posibilidad de clonar y desplegar otros sistemas operativos. Esto ultimo conlleva soportar nuevos tipos de sistemas de ficheros. +Algunos de los aspectos principales de la futura línea de trabajo de OpenGnsys son la capacidad de gestión de discos redundantes, volúmenes lógicos y tener la posibilidad de clonar y desplegar otros sistemas operativos. Esto ultimo conlleva soportar nuevos tipos de sistemas de ficheros. La distribución de imágenes y ficheros debe ser lo más flexible posible, implementando distintos protocolos de comunicaciones, como Unixast, Multicast y P2P; e incluso también poder disponer de dicha información de forma off-line (sin necesidad de comunicación con el servidor) accediendo directamente a la caché de datos local de cada cliente o a un dispositivo externo de almacenamiento. -Por definición, OpenGnSys es un proyecto de Software Libre. Como tal, todo el código está licenciado bajo GPLv3 o superior, mientras que la documentación asociada está disponible bajo licencia Creative Commons con Reconocimiento y Compartir Igual. +Por definición, OpenGnsys es un proyecto de Software Libre. Como tal, todo el código está licenciado bajo GPLv3 o superior, mientras que la documentación asociada está disponible bajo licencia Creative Commons con Reconocimiento y Compartir Igual. -OpenGnSys es el resultado del proceso de integración de 3 proyectos anteriores desarrollados en diferentes universidades: +OpenGnsys es el resultado del proceso de integración de 3 proyectos anteriores desarrollados en diferentes universidades: * Brutalix (Universidad de Zaragoza) * EAC (Universidad de Málaga) * Hidra (Universidad de Sevilla) +Página web del Proyecto OpenGnsys: + https://opengnsys.es/ + diff --git a/doc/VERSION.txt b/doc/VERSION.txt index 66e48d49..2ffa83a4 100644 --- a/doc/VERSION.txt +++ b/doc/VERSION.txt @@ -1 +1 @@ -OpenGnSys 1.0.6b +OpenGnsys 1.1.0 r5607 diff --git a/doc/filetree.en.txt b/doc/filetree.en.txt index a43d2850..a276617d 100644 --- a/doc/filetree.en.txt +++ b/doc/filetree.en.txt @@ -1,9 +1,9 @@ -OpenGnSys 1.0.x Filesystem Hiearchy +OpenGnsys 1.1.x Filesystem Hiearchy =================================== -Directory Structure of OpenGnSys Client +Directory Structure of OpenGnsys Client --------------------------------------------- /opt/opengnsys @@ -18,21 +18,23 @@ Directory Structure of OpenGnSys Client -Directory Structure of OpenGnSys Server: +Directory Structure of OpenGnsys Server: ---------------------------------------------- /opt/opengnsys bin - server binaries. client - exports the client's directory structure. + doc - documentation files. etc - configuration files. - lib - tool libraries. - log - ficheros de registro de incidencias. + lib - tools and libraries. log - log files. + sbin - binaries for services. tftpboot - remote boot files (linked to TFTP directory). + www - web files. -Directory Structure of OpenGnSys Repository Manager +Directory Structure of OpenGnsys Repository Manager --------------------------------------------------------- /opt/opengnsys @@ -40,6 +42,7 @@ Directory Structure of OpenGnSys Repository Manager etc - configuration files. images - filesystem images. log - log files. + sbin - binaries for services. diff --git a/doc/filetree.es.txt b/doc/filetree.es.txt index fa07a967..698b8174 100644 --- a/doc/filetree.es.txt +++ b/doc/filetree.es.txt @@ -1,9 +1,9 @@ -Estructura de Ficheros de OpenGnSys 1.0 +Estructura de Ficheros de OpenGnsys 1.1 ======================================= -Estructura de directorios de OpenGnSys Client +Estructura de directorios de OpenGnsys Client --------------------------------------------- /opt/opengnsys @@ -19,7 +19,7 @@ Estructura de directorios de OpenGnSys Client log (rw) - ficheros de registro de incidencias. -Servicios de OpenGnSys Server: +Servicios de OpenGnsys Server: ------------------------------ - Syslog - gestión de logs de servidores y clientes. - DHCP @@ -30,21 +30,24 @@ Servicios de OpenGnSys Server: - Servidor de órdenes -Estructura de directorios de OpenGnSys Server: +Estructura de directorios de OpenGnsys Server: ---------------------------------------------- /opt/opengnsys bin - binarios del servidor. client - exporta en remoto la estructura de directorios del cliente. + doc - ficheros de documentación. etc - ficheros de configuración. lib - librerías de las utilidades. log - ficheros de registro de incidencias. + sbin - binarios de servicios. tftpboot - arranque remoto de clientes (enlace al directorio de TFTP). + www - ficheros web. NOTA: páginas de manuales y documentación se copian a los directorios estándares del sistema operativo. -Estructura de directorios de OpenGnSys Repository Manager +Estructura de directorios de OpenGnsys Repository Manager --------------------------------------------------------- /opt/opengnsys @@ -52,6 +55,7 @@ Estructura de directorios de OpenGnSys Repository Manager etc - ficheros de configuración. images - imágenes de sistemas de archivos. log - ficheros de registro de incidencias. + sbin - binarios de servicios. diff --git a/doc/userManual/Tema0-Laboratorio_virtual.pdf b/doc/userManual/Tema0-Laboratorio_virtual.pdf new file mode 100644 index 00000000..3eacafb0 Binary files /dev/null and b/doc/userManual/Tema0-Laboratorio_virtual.pdf differ diff --git a/doc/userManual/Tema1-Introduccion.pdf b/doc/userManual/Tema1-Introduccion.pdf index 555c0b26..eed9744f 100644 Binary files a/doc/userManual/Tema1-Introduccion.pdf and b/doc/userManual/Tema1-Introduccion.pdf differ diff --git a/doc/userManual/Tema2-Instalacion.pdf b/doc/userManual/Tema2-Instalacion.pdf index ae0d1b2e..1ab9461f 100644 Binary files a/doc/userManual/Tema2-Instalacion.pdf and b/doc/userManual/Tema2-Instalacion.pdf differ diff --git a/doc/userManual/Tema3.1-Administracion_componentes.pdf b/doc/userManual/Tema3.1-Administracion_componentes.pdf index 0de21554..69e1d4f7 100644 Binary files a/doc/userManual/Tema3.1-Administracion_componentes.pdf and b/doc/userManual/Tema3.1-Administracion_componentes.pdf differ diff --git a/doc/userManual/Tema3.2-Administracion_consola_web.pdf b/doc/userManual/Tema3.2-Administracion_consola_web.pdf index 0d06eb62..26aad817 100644 Binary files a/doc/userManual/Tema3.2-Administracion_consola_web.pdf and b/doc/userManual/Tema3.2-Administracion_consola_web.pdf differ diff --git a/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf b/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf index 26f5ea95..1828aa49 100644 Binary files a/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf and b/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf differ diff --git a/doc/userManual/Tema4-Ambito_aplicacion.pdf b/doc/userManual/Tema4-Ambito_aplicacion.pdf index 9a315c94..1989899d 100644 Binary files a/doc/userManual/Tema4-Ambito_aplicacion.pdf and b/doc/userManual/Tema4-Ambito_aplicacion.pdf differ diff --git a/doc/userManual/Tema5-Particionado_discos.pdf b/doc/userManual/Tema5-Particionado_discos.pdf index 971add05..d5fbdbcd 100644 Binary files a/doc/userManual/Tema5-Particionado_discos.pdf and b/doc/userManual/Tema5-Particionado_discos.pdf differ diff --git a/doc/userManual/Tema6.1-Creacion_imagenes.pdf b/doc/userManual/Tema6.1-Creacion_imagenes.pdf index 899242e3..94c4ae26 100644 Binary files a/doc/userManual/Tema6.1-Creacion_imagenes.pdf and b/doc/userManual/Tema6.1-Creacion_imagenes.pdf differ diff --git a/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf b/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf index a3b2649c..3e5df4e3 100644 Binary files a/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf and b/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf differ diff --git a/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf b/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf index acd0686f..592cb324 100644 Binary files a/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf and b/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf differ diff --git a/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf b/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf index f7e0013a..fb59c355 100644 Binary files a/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf and b/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf differ diff --git a/installer/INSTALL.en.txt b/installer/INSTALL.en.txt index 844c4e74..a98b7931 100644 --- a/installer/INSTALL.en.txt +++ b/installer/INSTALL.en.txt @@ -1,5 +1,5 @@ -Installing and updating OpenGnSys +Installing and updating OpenGnsys ================================= @@ -8,27 +8,27 @@ Installing OpenGnsys -------------------- -Run opengnsys_installer.sh script as "root" to install all its dependencies, to install the OpenGnSys components, and to make the initial configuration. +Run opengnsys_installer.sh script as "root" to install all its dependencies, to install the OpenGnsys components, and to make the initial configuration. sudo bash opengnsys_installer.sh Follow the instructions. -Updating OpenGnSys +Updating OpenGnsys ------------------ -Run opengnsys_update.sh script as "root" to update all OpenGnSys components from the Subversion repository: +Run opengnsys_update.sh script as "root" to update all OpenGnsys components from the Subversion repository: sudo bash /opt/opengnsys/lib/opengnsys_update.sh Follow the instructions. -Uninstalling OpenGnSys +Uninstalling OpenGnsys ---------------------- -Run opengnsys_uninstall.sh script as "root" to uninstall all OpenGnSys components: +Run opengnsys_uninstall.sh script as "root" to uninstall all OpenGnsys components: sudo bash /opt/opengnsys/lib/opengnsys_uninstall.sh diff --git a/installer/INSTALL.es.txt b/installer/INSTALL.es.txt index f5446e98..b9533063 100644 --- a/installer/INSTALL.es.txt +++ b/installer/INSTALL.es.txt @@ -1,4 +1,4 @@ -Instalación y Actualización de OpenGnSys 1.0.6 +Instalación y Actualización de OpenGnsys 1.1.0 ============================================== @@ -12,19 +12,20 @@ Descargar una versión completa y desccomprimir el fichero "opengnsys-version.ta cd opengnsys/installer O bien, descargar el instalador desde la última reversión del repositorio: - svn export http://www.opengnsys.es/svn/trunk/installer/opengnsys_installer.sh + svn export https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh Opcionalmente, puede descargarse la imagen del cliente; si no se realiza este paso, el instalador la descargará automáticamente. - wget http://www.opengnsys.es/downloads/ogLive-versioncliente.iso + wget https://opengnsys.es/downloads/ogLive-versioncliente.iso 2. Ejecutar el instalador como root: sudo bash opengnsys_installer.sh Dicho script solicitará por teclado la siguiente información para configurar el acceso al servicio (si no se indica un parámetro, toma el valor por defecto): * Clave del usuario root de MySQL. - * Usuario de acceso a la consola web y super-administrador de OpenGnSys. + * Usuario de acceso a la consola web y super-administrador de OpenGnsys. * Clave del usuario de acceso a la consola web. * Clave de acceso del cliente a servicios remotos. + * Seleccionar cliente(s) ogLive para instalar. Actaulización de ficheros @@ -39,7 +40,7 @@ Notas importantes. 3. El programa de actualización no modifica ficheros de configuración, no actualiza la bases de datos y no modifica ficheros de imágenes. -Desinstalar OpenGnSys +Desinstalar OpenGnsys --------------------- Ejecutar el script de actualización como usuario root: @@ -47,6 +48,7 @@ Ejecutar el script de actualización como usuario root: Notas importantes. 1. Para poder conservar la información, es recomendable hacer copia de seguridad del servidor antes de desinstalar. -2. El programa de desinstalación no elimina los ficheros de imágenes, no desinstala ningún paquete del sistema operativo incluido en el proceso de instalación y no detiene, ni desconfigura ningún otro servicio auxiliar a OpenGnSys. +2. Se solicita confirmación por parte del usuario antes de ejecutar cualquier operación. +3. El programa de desinstalación no elimina los ficheros de imágenes, ni los clientes ogLive instalados, no desinstala ningún paquete del sistema operativo incluido en el proceso de instalación y no detiene, ni desconfigura ningún otro servicio auxiliar a OpenGnsys. diff --git a/installer/README.es.txt b/installer/README.es.txt index 1b270926..a7879033 100644 --- a/installer/README.es.txt +++ b/installer/README.es.txt @@ -1,9 +1,10 @@ -OpenGnSys Installer README + +OpenGnsys Installer README =============================== Este directorio contiene la documentación y los programas para instalar, actualizar y -eliminar el Proyecto OpenGnSys. +eliminar el Proyecto OpenGnsys. - INSTALL.es.txt información de instalación y desinistalación @@ -14,5 +15,11 @@ eliminar el Proyecto OpenGnSys. - opengnsys_uninstall.sh programa de desinstalación del serviidor - opengnsys_update.sh programa de actualización del serviidor +- ogagent-devel-installer.sh programa de preparación del entorno de desarrollo y + compilación de agentes OGAgent para sistemas operativos + +- vagrant directorio con ficheros de configuración para despliegue + de entornos de prueba y desarrollo con Vagrant + - install_ticket_wolunicast.sh programa de instalación del parche para ejecutar arranque Wake-On-Lan por IP usando protocolo Unicast diff --git a/installer/ogGenerateDoc.sh b/installer/ogGenerateDoc.sh index 9c8cbc44..5cc0914b 100755 --- a/installer/ogGenerateDoc.sh +++ b/installer/ogGenerateDoc.sh @@ -21,7 +21,7 @@ if [ $# = 2 ] then mkdir -p "$2" VERSION=$(cat $(dirname "$0")/../doc/VERSION.txt) 2>/dev/null -VERSION=${VERSION:-"1.0"} +VERSION=${VERSION:-"1.1"} cat > /tmp/doxyfile << EOF # Doxyfile 1.5.6 # Fichero para documentar codigo shellscripts linux. @@ -30,10 +30,10 @@ cat > /tmp/doxyfile << EOF # Project related configuration options #--------------------------------------------------------------------------- DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = "Proyecto OpenGnSys" +PROJECT_NAME = "Proyecto OpenGnsys" PROJECT_NUMBER = $VERSION -PROJECT_LOGO = $(dirname "$0")/../doc/opengnsys-logo.png) OUTPUT_DIRECTORY = $2 +PROJECT_LOGO = $(dirname "$0")/../doc/opengnsys-logo.png) CREATE_SUBDIRS = NO OUTPUT_LANGUAGE = Spanish BRIEF_MEMBER_DESC = YES diff --git a/installer/ogagent-devel-installer.sh b/installer/ogagent-devel-installer.sh new file mode 100755 index 00000000..a2d7a3bf --- /dev/null +++ b/installer/ogagent-devel-installer.sh @@ -0,0 +1,113 @@ +#!/bin/bash +#/** +#@file ogagent-devel-installer.sh +#@brief Script to download and prepare the environmnt to compile OGAgent packages. +#@warning Some operations need "root" privileges. +#@note This script will make the "ogagent" directory with 1.5 GiB approx. +#@version 1.0 - Initial version for OpenGnsys 1.1.0. +#@author Ramón M. Gómez, ETSII Universidad de Sevilla +#@date 2016-04-07 +#*/ ## + + +# Variables. +PROGDIR=$PWD/ogagent +SVNURL=https://opengnsys.es/svn/tags/opengnsys-1.1.0/admin/Sources/Clients/ogagent + +# Show prerequisites needed to build the environment. +mkdir -p $PROGDIR || exit 1 +cat << EOT + +OGAgent devoloping environment installation + +Prerequisites: +- Install packages, if needed: + - Wine for 32-bit (Winetricks may be required) + - Python 2.7 with pyqt4-dev-tools + - realpath + - dpkg-dev + - rpmbuild + - xar +- Open a web browser and download Microsoft Visual C++ 2010 Redistributable Package (x86) from: http://www.microsoft.com/en-us/download/details.aspx?id=5555 +- Copy or move "vcredist_x86.exe" file to $PROGDIR directory. +Press [Enter] key when ready to continue. +EOT +read + +# Importing OGAgent source code. +svn export --force $SVNURL $PROGDIR || exit 1 + +# Update PyQt components. +pushd ogagent/src >/dev/null +./update.sh +popd >/dev/null + +# Showing instructions to configure Wine. +cat << EOT + +Manual actions: +- After all downloads, install Gecko for Wine, if needed. +- Press [Esc] key or "Cancel" button on Winetricks screen, if needed. +- Accept default settings for all other components. +- Uncheck all options on "Completing NSIS Setup" screen. +Press [Enter] key to init downloads. + +EOT +read + +# Downloading and configuring Wine prerequisites. +pushd ogagent/windows >/dev/null +./py2exe-wine-linux.sh +cp -a build.bat ogagent.nsi .. +ln -s ../../.. wine/drive_c/ogagent +popd >/dev/null + +# Download, compile and install bomutils. +mkdir -p ogagent/macos/downloads +svn export https://github.com/hogliux/bomutils.git/trunk ogagent/macos/downloads/bomutils +pushd ogagent/macos/downloads/bomutils >/dev/null +make && sudo make install +popd >/dev/null + +# Build OGAgent for GNU/Linux. +pushd $PROGDIR/linux >/dev/null +sudo ./build-packages.sh +popd >/dev/null + +# Build OGAgent for macOS. +pushd $PROGDIR/macos >/dev/null +./build-pkg.sh +popd >/dev/null + +# Build OGAgent for Windows. +pushd $PROGDIR/windows >/dev/null +./build-windows.sh +popd >/dev/null + +# Showing instructions to rebuild OGAgent packages. +cat << EOT + +How to rebuild OGAgent packages +------------------------------- +OGAgent project source code is available in $PROGDIR/src directory. + +- Commands to update PyQt graphical components for OGAgnet: + cd $PROGDIR/src + ./update.sh + +- Commands to rebuild Linux packages: + cd $PROGDIR/linux + sudo ./build-packages.sh + +- Commands to rebuild macOS package: + cd $PROGDIR/macos + ./build-pkg.sh + +- Commands to rebuild Windows installer: + cd $PROGDIR/windows + ./build-windows.sh + +OGAgent packages will be created into $PROGDIR directory. + +EOT + diff --git a/installer/ogagentpkgs-1.1.0.tar.gz b/installer/ogagentpkgs-1.1.0.tar.gz new file mode 100644 index 00000000..59b0f371 Binary files /dev/null and b/installer/ogagentpkgs-1.1.0.tar.gz differ diff --git a/installer/opengnsys_export.sh b/installer/opengnsys_export.sh new file mode 100755 index 00000000..8e9c9ccd --- /dev/null +++ b/installer/opengnsys_export.sh @@ -0,0 +1,114 @@ +#!/bin/bash +# exportclient str_backupfile +#@file exportclient +#@brief Exporta los clientes de un archivo de backup: dhcp, pxe, páginas de inicio y configuración de la consola. +#@param 1 str_backupfile fichero de backup (creado con exportclient) +#@exception 1 Error de formato. +#@exception 2 Sólo ejecutable por usuario root. +#@exception 3 Sin acceso a la configuración de OpenGnsys. +#@exception 4 No existe el directorio de backup. +#@exception 5 Es necesario instalar el comando realpath. +#@warning This script uses "realpath" command. +#@version 1.1.0 - Versión inicial. +#@author Irina Gómez - ETSII Univ. Sevilla +#@date 2016-10-18 +#@version 1.1.0 - Cambia cómo se exporta la base de datos para permitir importar en versiones posteriores. +#@note Incompatible con versiones de opengnsys_import.sh anteriores a esta fecha. +#@date 2018-02-14 +#*/ ## + +# Variables globales. +PROG="$(basename $0)" + +OPENGNSYS="/opt/opengnsys" +TMPDIR=/tmp +MYSQLFILE="$TMPDIR/ogAdmBD.sql" +BACKUPPREFIX="opengnsys_export" + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + echo -e "$PROG: Exporta los datos de OpenGnsys desde un archivo de backup:" \ + " dhcp, pxe, páginas de inicio y configuración de la consola.\n" \ + " Formato: $PROG backup_file\n" \ + " Ejemplo: $PROG backup.tgz" + exit +fi + +# Comprobar parámetros. +# Comprobamos número de parámetros +if [ $# -ne 1 ]; then + echo "$PROG: ERROR: Error de formato: $PROG backup_file" + exit 1 +fi + +if [ "$USER" != "root" ]; then + echo "$PROG: Error: solo ejecutable por root." >&2 + exit 2 +fi + +# Comprobamos que esté instalado el comando realpath +if ! which realpath &>/dev/null ; then + echo "Need to install \"realpath\"." + exit 5 +fi + +# Comprobamos acceso a ficheros de configuración +if ! [ -r $OPENGNSYS/etc/ogAdmServer.cfg ]; then + echo "$PROG: ERROR: Sin acceso a la configuración de OpenGnsys." | tee -a $FILESAL + exit 3 +fi + +# Comprobamos que exista el directorio para el archivo de backup +BACKUPDIR=$(realpath $(dirname $1) 2>/dev/null) +[ $? -ne 0 ] && echo "$PROG: Error: No existe el directorio para el archivo de backup" && exit 4 +BACKUPFILE="$BACKUPDIR/$(basename $1)" + +# DHCP +for DIR in /etc/dhcp /etc/dhcp3; do + [ -r $DIR/dhcpd.conf ] && DHCPDIR=$DIR +done + +# Exportar la base de datos +echo "Exportamos la información de la base de datos." +source $OPENGNSYS/etc/ogAdmServer.cfg +# Crear fichero temporal de acceso a la BD +MYCNF=$(mktemp /tmp/.my.cnf.XXXXX) +chmod 600 $MYCNF +trap "rm -f $MYCNF $MYSQLFILE $TMPDIR/IPSERVER.txt" 1 2 3 6 9 15 +cat << EOT > $MYCNF +[client] +user=$USUARIO +password=$PASSWORD +EOT + +mysqldump --defaults-extra-file=$MYCNF --opt $CATALOG > $MYSQLFILE + +# Borrar fichero temporal +rm -f $MYCNF + +# IP SERVIDOR +echo $ServidorAdm > $TMPDIR/IPSERVER.txt + +# Si existe ya archivo de backup lo renombramos +[ -r $BACKUPFILE ] && mv $BACKUPFILE $BACKUPFILE-$(date +%Y%M%d) + +# Empaquetamos los ficheros +echo "Creamos un archivo comprimido con los datos: $BACKUPFILE." +tar -cvzf $BACKUPFILE --transform="s!^!$BACKUPPREFIX/!" \ + -C $(dirname $MYSQLFILE) $(basename $MYSQLFILE) \ + -C $TMPDIR IPSERVER.txt \ + -C $DHCPDIR dhcpd.conf \ + -C $OPENGNSYS/tftpboot menu.lst \ + -C $OPENGNSYS/doc VERSION.txt \ + -C $OPENGNSYS/client/etc engine.cfg \ + -C $OPENGNSYS/www menus \ + -C /etc default/opengnsys &>/dev/null + +# Cambio permisos: sólo puede leerlo el root +chmod 600 $BACKUPFILE + +# Borrar ficheros temporales +rm -f $MYSQLFILE $TMPDIR/IPSERVER.txt + +echo -e "\nNo conveniente situar el fichero de backup dentro de /opt/opengnsys" \ + "\n ya que se borrará si desinstala OpenGnsys." diff --git a/installer/opengnsys_import.sh b/installer/opengnsys_import.sh new file mode 100755 index 00000000..e3a04c17 --- /dev/null +++ b/installer/opengnsys_import.sh @@ -0,0 +1,331 @@ +#!/bin/bash +# importclient str_backupfile +#@file importclient +#@brief Importa los datos de OpenGnsys de un archivo de backup: dhcp, pxe, páginas de inicio y configuración de la consola. +#@param 1 str_backupfile fichero de backup (creado con exportclient) +#@exception 1 Error de formato +#@exception 2 Sólo ejecutable por usuario root +#@exception 3 Sin acceso al fichero de backup +#@exception 4 Sin acceso a la configuración de OpenGnsys +#@exception 5 Errores al importar o exportar de la bd auxiliar +#@exception 6 Errores al importar los archivos de actualización de la BD desde opengnsys.es +#@exception 7 El archivo de backup ha sido crearo con una versión incompatible de opengnsys_export. Usar 1.1.0-5594 o posterior. +#@note En las versiones de desarrollo (pre) no se modifica la estructura de la base de datos. +#@version 1.1.0 - Versión inicial. +#@author Irina Gómez - ETSII Univ. Sevilla +#@date 2016-10-18 +#@version 1.1.0 - Permite importar de versiones de OpenGnsys anteriores. Cambia la importación de la base de datos. +#@note Incompatible con versiones de opengnsys_export.sh anteriores a esta fecha. +#@date 2018-02-14 +#*/ ## + +# Variables globales. +PROG="$(basename $0)" + +DATE=$(date +%Y%m%d) +BACKUPFILE=$1 +TMPDIR=/tmp/opengnsys_export +OPENGNSYS="/opt/opengnsys" +MYCNF=$(mktemp /tmp/.my.cnf.XXXXX) +CATALOG="ogAdmBD" +AUXCATALOG="og_import" +MYSQLFILE="$TMPDIR/$CATALOG.sql" +MYSQLBCK="$OPENGNSYS/doc/$CATALOG.sql-$DATE" + +LOG_FILE=$OPENGNSYS/log/${PROG%.sh}.log +OPENGNSYS_SERVER="opengnsys.es" +DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot" # Clave por defecto root de MySQL + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + echo -e "$PROG: Importa los datos de OpenGnsys desde un archivo de backup:" \ + " dhcp, pxe, páginas de inicio y configuración de la consola.\n" \ + " Formato: $PROG backup_file\n" \ + " Ejemplo: $PROG backup.tgz" + exit +fi + +# Comprobamos número de parámetros +if [ $# -ne 1 ]; then + echo "$PROG: ERROR: Error de formato: $PROG backup_file" + exit 1 +fi + +# Comprobar parámetros. +if [ "$USER" != "root" ]; then + echo "$PROG: Error: solo ejecutable por root." >&2 + exit 2 +fi + +# Comprobamos acceso al fichero de backup +if ! [ -r $BACKUPFILE ]; then + echo "$PROG: ERROR: Sin acceso al fichero de backup." | tee -a $FILESAL + exit 3 +fi + +# Comprobamos acceso a ficheros de configuración +if ! [ -r $OPENGNSYS/etc/ogAdmServer.cfg ]; then + echo "$PROG: ERROR: Sin acceso a la configuración de OpenGnsys." | tee -a $FILESAL + exit 4 +fi + +# Si existe el directorio auxiliar lo borramos +[ -d $TMPDIR ] && rm -rf $TMPDIR + +####### Funciones ############################################## +# Al salir elimina archivos y base de datos temporal +function clean() +{ + mysql --defaults-extra-file=$MYCNF -e "DROP DATABASE IF EXISTS $AUXCATALOG" + rm -f $MYCNF +} + +function getDateTime() +{ + date "+%Y%m%d-%H%M%S" +} + +# Escribe a fichero y muestra por pantalla +function echoAndLog() +{ + echo " $1" + DATETIME=`getDateTime` + echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE +} + +function errorAndLog() +{ + echo " ERROR: $1" + DATETIME=`getDateTime` + echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE +} + +function mysqlPassword() +{ + # Clave root de MySQL + while : ; do + echo -n -e "\\nEnter root password for MySQL (${DEFAULT_MYSQL_ROOT_PASSWORD}): "; + read -r MYSQL_ROOT_PASSWORD + if [ -n "${MYSQL_ROOT_PASSWORD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico + echo -e "\\aERROR: Must be alphanumeric, try again..." + else + # Si esta vacio ponemos el valor por defecto + MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-$DEFAULT_MYSQL_ROOT_PASSWORD}" + break + fi + done + cat << EOT > $MYCNF +[client] +user=root +password=$MYSQL_ROOT_PASSWORD +EOT +} + +# Actualización incremental de la BD (versión actual a actual+1, hasta final-1 a final). +function updateSqlFile() +{ + local DBDIR="$TMPDIR/Database" + local file FILES="" + + echoAndLog "${FUNCNAME}(): looking for database updates" + pushd $DBDIR >/dev/null + # Bucle de actualización incremental desde versión actual a la final. + for file in $CATALOG-*-*.sql; do + case "$file" in + $CATALOG-$OLDVERSION-$NEWVERSION.sql) + # Actualización única de versión inicial y final. + FILES="$FILES $file" + break + ;; + $CATALOG-*-postinst.sql) + # Ignorar fichero específico de post-instalación. + ;; + $CATALOG-$OLDVERSION-*.sql) + # Actualización de versión n a n+1. + FILES="$FILES $file" + OLDVERSION="$(echo $file | cut -f3 -d-)" + ;; + $CATALOG-*-$NEWVERSION.sql) + # Última actualización de versión final-1 a final. + if [ -n "$FILES" ]; then + FILES="$FILES $file" + break + fi + ;; + esac + done + # Aplicar posible actualización propia para la versión final. + file=$CATALOG-$NEWVERSION.sql + if [ -n "$FILES" -o "$OLDVERSION" = "$NEWVERSION" -a -r $file ]; then + FILES="$FILES $file" + fi + + popd >/dev/null + if [ -n "$FILES" ]; then + mysql --defaults-extra-file=$MYCNF -e "CREATE DATABASE $AUXCATALOG" + [ $? != 0 ] && errorAndLog "${FUNCNAME}: Can't create database $AUXCATALOG" && exit 5 + mysql --defaults-extra-file=$MYCNF -D "$AUXCATALOG" < $MYSQLFILE &>/dev/null + [ $? != 0 ] && errorAndLog "${FUNCNAME}: Can't import $MYSQLFILE in $AUXCATALOG" && exit 5 + + for file in $FILES; do + importSqlFile $DBDIR/$file + done + + cp $MYSQLFILE $MYSQLFILE.backup + mysqldump --defaults-extra-file=$MYCNF --opt $AUXCATALOG > $MYSQLFILE + [ $? != 0 ] && errorAndLog "${FUNCNAME}: Can't export $AUXCATALOG in $MYSQLFILE" && exit 5 + + mysql --defaults-extra-file=$MYCNF -e "DROP DATABASE $AUXCATALOG" + echoAndLog "${FUNCNAME}(): sqlfile update" + else + echoAndLog "${FUNCNAME}(): sqlfile unchanged" + fi +} + + +# Actualizar la base datos +function importSqlFile() +{ + local sqlfile="$1" + + if [ ! -r $sqlfile ]; then + errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!" + exit 5 + fi + + echoAndLog "${FUNCNAME}(): importing SQL file..." + # Ejecutar actualización y borrar fichero de credenciales. + mysql --defaults-extra-file=$MYCNF --default-character-set=utf8 -D "$AUXCATALOG" < $sqlfile + if [ $? -ne 0 ]; then + errorAndLog "${FUNCNAME}(): error importing ${sqlfile##*/} in temporal database" + exit 5 + fi + echoAndLog "${FUNCNAME}(): file ${sqlfile##*/} imported to temporal database" + return 0 +} + +################################################################## +# Al salir borramos MYCNF y la db tamporal +trap "clean" 1 2 3 6 9 14 15 EXIT + +# Descomprimimos backup +tar -xvzf $BACKUPFILE --directory /tmp &>/dev/null + +# Comprueba que opengnsys_export sea compatible +grep "CREATE TABLE.*usuarios" $MYSQLFILE &>/dev/null +if [ $? -ne 0 ]; then + errorAndLog "Backup file created with old version opengnsys_export. Use version 1.1.0-5594 or later." + exit 7 +fi + +# Comprobamos si es la misma versión +OLDVERSION=$(awk '{print $2}' $TMPDIR/VERSION.txt) +NEWVERSION=$(awk '{print $2}' $OPENGNSYS/doc/VERSION.txt) +# FALTA: Comprobar que la versión OLD es menor que la NEW +if [ $OLDVERSION != $NEWVERSION ] ; then + echo "La versión del servidor no coincide con la del backup." + cat $OPENGNSYS/doc/VERSION.txt $TMPDIR/VERSION.txt + read -p "¿Quiere continuar? (y/n): " ANSWER + if [ "${ANSWER^^}" != "Y" ]; then + echo "Operación cancelada." + exit 0 + fi + # Nos bajamos los archivos de actualización de la base de datos + SVN_URL="https://$OPENGNSYS_SERVER/svn/tags/opengnsys-$NEWVERSION/admin/Database" + [[ "$NEWVERSION" =~ pre ]] && SVN_URL="https://$OPENGNSYS_SERVER/svn/branches/version${NEWVERSION%.*}/admin/Database" + svn checkout "$SVN_URL" $TMPDIR/Database + [ $? -ne 0 ] && errorAndLog "$PROG: Error getting code from $SVN_URL" && exit 6 + + # Solicitamos la clave de mysql. + mysqlPassword + DIFFVERSION=TRUE +fi + +# MYSQL +echo " * Importamos informacion mysql." +source $OPENGNSYS/etc/ogAdmServer.cfg +# Crear fichero temporal de acceso a la BD +if [ ! -r $MYCNF ]; then + chmod 600 $MYCNF + trap "rm -f $MYCNF" 1 2 3 6 9 15 + cat << EOT > $MYCNF +[client] +user=$USUARIO +password=$PASSWORD +EOT +fi + +# Si la BD tiene no definido el trigger necesitamos permisos de root +mysql --defaults-extra-file=$MYCNF -e "SHOW TRIGGERS FROM $CATALOG;" |grep "Trigger" &>/dev/null +if [ $? -eq 0 ]; then + # Existe el trigger: eliminamos líneas del trigger en $CATALOG.sql + read INI END <<< $(grep -n -e TRIGGER -e "END.*;;" $MYSQLFILE |cut -d: -f1) + [ -n "$INI" ] && sed -i "$INI,${END}d" $MYSQLFILE +else + # No existe: necesitamos privilegios de root + grep "user=root" $MYCNF &>/dev/null || mysqlPassword +fi + +# Si la versión es diferente usamos una tabla auxiliar para actualizar el .sql +[ "$DIFFVERSION" == TRUE ] && updateSqlFile + +# Eliminamos las tablas que no importamos: repositorios, entorno +# y añadimos los usuarios, sólo si no existen. +cp $MYSQLFILE $MYSQLFILE.prueba +sed -i -e '/Table structure.* `repositorios`/,/Table structure/d' \ + -e '/Table structure.* `entornos`/,/Table structure/d' \ + -e '/Table structure.*`usuarios`/,/CHARSET/d' \ + -e '/usuarios/s/IGNORE//g' \ + -e '/usuarios/s/^INSERT /\nALTER TABLE usuarios ADD UNIQUE (usuario);\n\nINSERT IGNORE /g' $MYSQLFILE + +# Copia de seguridad del estado de la base de datos +mysqldump --defaults-extra-file=$MYCNF --opt $CATALOG > $MYSQLBCK +# Importamos los datos nuevos +mysql --defaults-extra-file=$MYCNF -D "$CATALOG" < $MYSQLFILE &>/dev/null +[ $? -ne 0 ] && echo "ERROR: Error al importar la información de la base de datos." + +# Copiamos los archivos a su sitio correcto +# DHCP +echo " * Componemos la configuración del dhcp." +for DHCPCFGDIR in /etc/dhcp /etc/dhcp3; do + if [ -r $DHCPCFGDIR/dhcpd.conf ]; then + # Tomamos las variables globales de la configuración actual y las declaraciones host del backup + # Inicio declaraciones host + OLDHOSTINI=$(grep -n -m1 -e "^[[:blank:]]*host" -e "^#[[:blank:]]*host" $TMPDIR/dhcpd.conf|cut -d: -f1) + let BEFOREHOST=$(grep -n -m1 -e "^[[:blank:]]*host" -e "^#[[:blank:]]*host" $DHCPCFGDIR/dhcpd.conf| cut -d: -f1)-1 + # Copia de seguridad de la configuración anterior + cp $DHCPCFGDIR/dhcpd.conf $DHCPCFGDIR/dhcpd.conf-LAST + mv $DHCPCFGDIR/dhcpd.conf $DHCPCFGDIR/dhcpd.conf-$DATE + # Nuevo fichero + sed ${BEFOREHOST}q $DHCPCFGDIR/dhcpd.conf-LAST > $DHCPCFGDIR/dhcpd.conf + sed -n -e "$OLDHOSTINI,\$p" $TMPDIR/dhcpd.conf >> $DHCPCFGDIR/dhcpd.conf + break + fi +done + +# TFTP +echo " * Guardamos los ficheros PXE de los clientes." +mv $OPENGNSYS/tftpboot/menu.lst $OPENGNSYS/tftpboot/menu.lst-$DATE +cp -r $TMPDIR/menu.lst $OPENGNSYS/tftpboot +chown -R www-data:www-data $OPENGNSYS/tftpboot/menu.lst + +# Configuración de los clientes +echo " * Guardamos la configuración de los clientes." +mv $OPENGNSYS/client/etc/engine.cfg $OPENGNSYS/client/etc/engine.cfg-$DATE +cp $TMPDIR/engine.cfg $OPENGNSYS/client/etc/engine.cfg + +# Páginas de inicio +echo " * Guardamos las páginas de inicio." +mv $OPENGNSYS/www/menus $OPENGNSYS/www/menus-$DATE +cp -r $TMPDIR/menus $OPENGNSYS/www + +echo -e "Se ha terminado de importar los datos del backup. \n\nSe han realizado copias de seguridad de los archivos antiguos:" +echo " - $DHCPCFGDIR/dhcpd.conf-$DATE" +echo " - $OPENGNSYS/tftpboot/menu.lst-$DATE" +echo " - $OPENGNSYS/client/etc/engine.cfg-$DATE" +echo " - $OPENGNSYS/www/menus-$DATE" +echo -e " - $MYSQLBCK \n" + +echo "Hay que revisar la configuración del dhcp. En la consola es necesario configurar los valores de las ips de repositorios, servidores ntp, etc y lanzar el \"netBoot Avanzado\" a todas las aulas" + +echo "Es necesario probar todos los procedimientos y en caso de error borrarlos y generarlos de nuevo." diff --git a/installer/opengnsys_installer.sh b/installer/opengnsys_installer.sh index 26e22f21..26da2894 100755 --- a/installer/opengnsys_installer.sh +++ b/installer/opengnsys_installer.sh @@ -1,15 +1,15 @@ #!/bin/bash ##################################################################### -####### Script instalador OpenGnSys -####### autor: Luis Guillén +####### Script instalador OpenGnsys +####### Autor: Luis Guillén ##################################################################### #### AVISO: Puede editar configuración de acceso por defecto. #### WARNING: Edit default access configuration if you wish. DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot" # Clave por defecto root de MySQL -DEFAULT_OPENGNSYS_DB_USER="usuog" # Usuario por defecto de acceso a la base de datos +DEFAULT_OPENGNSYS_DB_USER="usuog" # Usuario por defecto de acceso a la base de datos DEFAULT_OPENGNSYS_DB_PASSWD="passusuog" # Clave por defecto de acceso a la base de datos DEFAULT_OPENGNSYS_CLIENT_PASSWD="og" # Clave por defecto de acceso del cliente @@ -19,83 +19,100 @@ if [ "$(whoami)" != 'root' ]; then exit 1 fi -echo -e "\\nOpenGnSys Installation" +echo -e "\\nOpenGnsys Installation" echo "==============================" # Clave root de MySQL while : ; do echo -n -e "\\nEnter root password for MySQL (${DEFAULT_MYSQL_ROOT_PASSWORD}): "; - read MYSQL_ROOT_PASSWORD + read -r MYSQL_ROOT_PASSWORD if [ -n "${MYSQL_ROOT_PASSWORD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico echo -e "\\aERROR: Must be alphanumeric, try again..." else - if [ -z $MYSQL_ROOT_PASSWORD ]; then # Si esta vacio ponemos el valor por defecto - MYSQL_ROOT_PASSWORD=$DEFAULT_MYSQL_ROOT_PASSWORD - fi + # Si esta vacio ponemos el valor por defecto + MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-$DEFAULT_MYSQL_ROOT_PASSWORD}" break fi done # Usuario de acceso a la base de datos while : ; do - echo -n -e "\\nEnter username for OpenGnSys console (${DEFAULT_OPENGNSYS_DB_USER}): " - read OPENGNSYS_DB_USER + echo -n -e "\\nEnter username for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_USER}): " + read -r OPENGNSYS_DB_USER if [ -n "${OPENGNSYS_DB_USER//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico echo -e "\\aERROR: Must be alphanumeric, try again..." else - if [ -z $OPENGNSYS_DB_USER ]; then # Si esta vacio ponemos el valor por defecto - OPENGNSYS_DB_USER=$DEFAULT_OPENGNSYS_DB_USER - fi + # Si esta vacio ponemos el valor por defecto + OPENGNSYS_DB_USER="${OPENGNSYS_DB_USER:-$DEFAULT_OPENGNSYS_DB_USER}" break fi done # Clave de acceso a la base de datos while : ; do - echo -n -e "\\nEnter password for OpenGnSys console (${DEFAULT_OPENGNSYS_DB_PASSWD}): " - read OPENGNSYS_DB_PASSWD + echo -n -e "\\nEnter password for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_PASSWD}): " + read -r OPENGNSYS_DB_PASSWD if [ -n "${OPENGNSYS_DB_PASSWD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico echo -e "\\aERROR: Must be alphanumeric, try again..." else - if [ -z $OPENGNSYS_DB_PASSWD ]; then # Si esta vacio ponemos el valor por defecto - OPENGNSYS_DB_PASSWD=$DEFAULT_OPENGNSYS_DB_PASSWD - fi + # Si esta vacio ponemos el valor por defecto + OPENGNSYS_DB_PASSWD="${OPENGNSYS_DB_PASSWD:-$DEFAULT_OPENGNSYS_DB_PASSWD}" break fi done # Clave de acceso del cliente while : ; do - echo -n -e "\\nEnter root password for OpenGnSys client (${DEFAULT_OPENGNSYS_CLIENT_PASSWD}): " - read OPENGNSYS_CLIENT_PASSWD + echo -n -e "\\nEnter root password for OpenGnsys client (${DEFAULT_OPENGNSYS_CLIENT_PASSWD}): " + read -r OPENGNSYS_CLIENT_PASSWD if [ -n "${OPENGNSYS_CLIENT_PASSWD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico echo -e "\\aERROR: Must be alphanumeric, try again..." else - if [ -z $OPENGNSYS_CLIENT_PASSWD ]; then # Si esta vacio ponemos el valor por defecto - OPENGNSYS_CLIENT_PASSWD=$DEFAULT_OPENGNSYS_CLIENT_PASSWD - fi + # Si esta vacio ponemos el valor por defecto + OPENGNSYS_CLIENT_PASSWD="${OPENGNSYS_CLIENT_PASSWD:-$DEFAULT_OPENGNSYS_CLIENT_PASSWD}" break fi done +# Selección de clientes ogLive para descargar. +while : ; do + echo -e "\\nChoose ogLive client to install." + echo -e "1) Kernel 4.8, 64-bit" + echo -e "2) Kernel 3.2, 32-bit" + echo -e "3) Both" + echo -n -e "Please, type a valid number (1): " + read -r OPT + case "$OPT" in + 1|"") OGLIVE="ogLive-xenial-4.8.0-39-generic-amd64-r5331.iso" + break ;; + 2) OGLIVE="ogLive-precise-3.2.0-23-generic-r5159.iso" + break ;; + 3) OGLIVE="ogLive-xenial-4.8.0-39-generic-amd64-r5331.iso ogLive-precise-3.2.0-23-generic-r5159.iso"; + break ;; + *) echo -e "\\aERROR: unknown option, try again." + esac +done + echo -e "\\n==============================" # Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1). -PROGRAMDIR=$(readlink -e $(dirname "$0")) +PROGRAMDIR=$(readlink -e "$(dirname "$0")") PROGRAMNAME=$(basename "$0") -OPENGNSYS_SERVER="www.opengnsys.es" +OPENGNSYS_SERVER="opengnsys.es" +DOWNLOADURL="https://$OPENGNSYS_SERVER/trac/downloads" if [ -d "$PROGRAMDIR/../installer" ]; then USESVN=0 else USESVN=1 fi -SVN_URL="http://$OPENGNSYS_SERVER/svn/trunk/" +SVN_URL="https://$OPENGNSYS_SERVER/svn/tags/opengnsys-1.1.0/" WORKDIR=/tmp/opengnsys_installer mkdir -p $WORKDIR -# Directorio destino de OpenGnSys. +# Directorio destino de OpenGnsys. INSTALL_TARGET=/opt/opengnsys +PATH=$PATH:$INSTALL_TARGET/bin # Registro de incidencias. OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log @@ -123,7 +140,7 @@ OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/${OPENGNSYS_DATABASE}.sql # - STOPSERVICE, DISABLESERVICE - parar y deshabilitar un servicio # - APACHESERV, APACHECFGDIR, APACHESITESDIR, APACHEUSER, APACHEGROUP - servicio y configuración de Apache # - APACHESSLMOD, APACHEENABLESSL, APACHEMAKECERT - habilitar módulo Apache y certificado SSL -# - APACHEENABLEOG, APACHEOGSITE, - habilitar sitio web de OpenGnSys +# - APACHEENABLEOG, APACHEOGSITE, - habilitar sitio web de OpenGnsys # - INETDSERV - servicio Inetd # - FIREWALLSERV - servicio de cortabuegos IPTables/FirewallD # - DHCPSERV, DHCPCFGDIR - servicio y configuración de DHCP @@ -131,7 +148,7 @@ OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/${OPENGNSYS_DATABASE}.sql # - MARIADBSERV - servicio MariaDB (sustituto de MySQL en algunas distribuciones) # - RSYNCSERV, RSYNCCFGDIR - servicio y configuración de Rsync # - SAMBASERV, SAMBACFGDIR - servicio y configuración de Samba -# - TFTPSERV, TFTPCFGDIR, SYSLINUXDIR - servicio y configuración de TFTP/PXE +# - TFTPSERV, TFTPCFGDIR - servicio y configuración de TFTP/PXE function autoConfigure() { # Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB). @@ -150,7 +167,7 @@ OSVERSION="${OSVERSION%%.*}" # Configuración según la distribución GNU/Linux (usar minúsculas). case "$OSDISTRIB" in ubuntu|debian|linuxmint) - DEPENDENCIES=( subversion apache2 php5 php5-ldap libapache2-mod-php5 mysql-server php5-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa syslinux xinetd build-essential g++-multilib libmysqlclient15-dev wget doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan ) + DEPENDENCIES=( subversion apache2 php5 php5-ldap libapache2-mod-php5 mysql-server php5-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient15-dev wget curl doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan realpath php5-curl gettext moreutils jq wakeonlan ) UPDATEPKGLIST="apt-get update" INSTALLPKG="apt-get -y install --force-yes" CHECKPKG="dpkg -s \$package 2>/dev/null | grep Status | grep -qw install" @@ -170,6 +187,7 @@ case "$OSDISTRIB" in APACHEUSER="www-data" APACHEGROUP="www-data" APACHESSLMOD="a2enmod ssl" + APACHEREWRITEMOD="a2enmod rewrite" APACHEENABLESSL="a2ensite default-ssl" APACHEENABLEOG="a2ensite $APACHEOGSITE" APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite" @@ -183,17 +201,12 @@ case "$OSDISTRIB" in RSYNCCFGDIR=/etc SAMBASERV=smbd SAMBACFGDIR=/etc/samba - SYSLINUXDIR=/usr/lib/syslinux TFTPCFGDIR=/var/lib/tftpboot ;; fedora|centos) - DEPENDENCIES=( subversion httpd mod_ssl php php-ldap mysql-server mysql-devel mysql-devel.i686 php-mysql dhcp tftp-server tftp syslinux xinetd binutils gcc gcc-c++ glibc-devel glibc-devel.i686 glibc-static glibc-static.i686 libstdc++ libstdc++.i686 libstdc++-devel.i686 make wget doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan ) - INSTALLEXTRADEPS=( 'rpm -Uv ftp://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/files/i586/RPMS/netpipes-4.2-alt1.i586.rpm' - 'pushd /tmp; wget -t3 http://download.bittornado.com/download/BitTornado-0.3.18.tar.gz && tar xvzf BitTornado-0.3.18.tar.gz && cd BitTornado-CVS && python setup.py install && ln -fs btlaunchmany.py /usr/bin/btlaunchmany && ln -fs bttrack.py /usr/bin/bttrack; popd' ) - if [ "$OSDISTRIB" == "centos" ]; then - UPDATEPKGLIST='test rpm -q --quiet epel-release || echo -e "[epel]\nname=EPEL temporal\nmirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-\$releasever&arch=\$basearch\nenabled=1\ngpgcheck=0" >/etc/yum.repos.d/epel.repo' - fi - INSTALLPKG="yum install -y" + DEPENDENCIES=( subversion httpd mod_ssl php php-ldap mysql-server mysql-devel mysql-devel.i686 php-mysql dhcp tftp-server tftp xinetd binutils gcc gcc-c++ glibc-devel glibc-devel.i686 glibc-static glibc-static.i686 libstdc++-devel.i686 make wget curl doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan procps-ng gettext moreutils jq net-tools http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm ) + INSTALLEXTRADEPS=( 'pushd /tmp; wget -t3 http://download.bittornado.com/download/BitTornado-0.3.18.tar.gz && tar xvzf BitTornado-0.3.18.tar.gz && cd BitTornado-CVS && python setup.py install && ln -fs btlaunchmany.py /usr/bin/btlaunchmany && ln -fs bttrack.py /usr/bin/bttrack; popd' ) + INSTALLPKG="yum install -y libstdc++ libstdc++.i686" CHECKPKG="rpm -q --quiet \$package" SYSTEMD=$(which systemctl 2>/dev/null) if [ -n "$SYSTEMD" ]; then @@ -212,6 +225,7 @@ case "$OSDISTRIB" in APACHEOGSITE=opengnsys.conf APACHEUSER="apache" APACHEGROUP="apache" + APACHEREWRITEMOD="sed -i '/rewrite/s/^#//' $APACHECFGDIR/../*.conf" DHCPSERV=dhcpd DHCPCFGDIR=/etc/dhcp if firewall-cmd --state &>/dev/null; then @@ -227,13 +241,12 @@ case "$OSDISTRIB" in RSYNCCFGDIR=/etc SAMBASERV=smb SAMBACFGDIR=/etc/samba - SYSLINUXDIR=/usr/share/syslinux TFTPSERV=tftp TFTPCFGDIR=/var/lib/tftpboot ;; "") echo "ERROR: Unknown Linux distribution, please install \"lsb_release\" command." exit 1 ;; - *) echo "ERROR: Distribution not supported by OpenGnSys." + *) echo "ERROR: Distribution not supported by OpenGnsys." exit 1 ;; esac @@ -264,7 +277,7 @@ selinuxenabled 2>/dev/null && setenforce 0 2>/dev/null # dependiendo de la versión instalada. function updatePackageList() { -local DHCPVERSION +local DHCPVERSION PHP5VERSION # Si es necesario, actualizar la lista de paquetes disponibles. [ -n "$UPDATEPKGLIST" ] && eval $UPDATEPKGLIST @@ -281,21 +294,39 @@ case "$OSDISTRIB" in DHCPSERV=dhcp3-server DHCPCFGDIR=/etc/dhcp3 fi + # Configuración para PHP 5 en Ubuntu 16.x+. + if [ -z "$(apt-cache pkgnames php5)" ]; then + eval $INSTALLPKG software-properties-common + add-apt-repository -y ppa:ondrej/php + eval $UPDATEPKGLIST + fi + PHP5VERSION=$(apt-cache pkgnames php5 | sort | head -1) + DEPENDENCIES=( ${DEPENDENCIES[@]//php5/$PHP5VERSION} ) + # Dependencias correctas para libmysqlclient. + [ -z "$(apt-cache pkgnames libmysqlclient15)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//libmysqlclient15/libmysqlclient} ) ;; centos) # Postconfiguación personalizada para CentOS. - # Incluir repositorio de paquetes EPEL y paquetes específicos. - DEPENDENCIES=( ${DEPENDENCIES[@]} epel-release procps ) + # Configuración para PHP 5. + if ! yum list php5\*w &>/dev/null; then + if [ $OSVERSION -ge 7 ]; then + yum install -y https://mirror.webtatic.com/yum/el$OSVERSION/webtatic-release.rpm + else + yum install -y https://mirror.webtatic.com/yum/el$OSVERSION/latest.rpm + fi + PHP5VERSION=$(yum list -q php5\*w | awk -F. '/^php/ {p=$1} END {print p}') + DEPENDENCIES=( ${DEPENDENCIES[@]//php/$PHP5VERSION} ) + fi # Cambios a aplicar a partir de CentOS 7. if [ $OSVERSION -ge 7 ]; then # Sustituir MySQL por MariaDB. DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} ) - # Instalar arp-scan de CentOS 6 (no disponible en CentOS 7). - DEPENDENCIES=( ${DEPENDENCIES[*]/arp-scan/http://dag.wieers.com/redhat/el6/en/$(arch)/dag/RPMS/arp-scan-1.9-1.el6.rf.$(arch).rpm} ) + # Instalar ctorrent de EPEL para CentOS 6 (no disponible en CentOS 7). + DEPENDENCIES=( ${DEPENDENCIES[*]/ctorrent/http://dl.fedoraproject.org/pub/epel/6/$(arch)/Packages/c/ctorrent-1.3.4-14.dnh3.3.2.el6.$(arch).rpm} ) fi ;; fedora) # Postconfiguación personalizada para Fedora. # Incluir paquetes específicos. - DEPENDENCIES=( ${DEPENDENCIES[@]} libstdc++-static.i686 btrfs-progs procps-ng ) + DEPENDENCIES=( ${DEPENDENCIES[@]} btrfs-progs ) # Sustituir MySQL por MariaDB a partir de Fedora 20. [ $OSVERSION -ge 20 ] && DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} ) ;; @@ -463,7 +494,7 @@ function installDependencies() fi DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND # Debian/Ubuntu - test grep -q "EPEL temporal" /etc/yum.repos.d/epel.repo 2>/dev/null ] || mv -f /etc/yum.repos.d/epel.repo.rpmnew /etc/yum.repos.d/epel.repo 2>/dev/null # CentOS/RedHat EPEL + test grep -q "EPEL temporal" /etc/yum.repos.d/epel.repo 2>/dev/null || mv -f /etc/yum.repos.d/epel.repo.rpmnew /etc/yum.repos.d/epel.repo 2>/dev/null # CentOS/RedHat EPEL echoAndLog "${FUNCNAME}(): dependencies installed" } @@ -646,6 +677,9 @@ function mysqlImportSqlFileToDb() local i=0 local dev="" local status + # Claves aleatorias para acceso a las APIs REST. + local OPENGNSYS_APIKEY=$(php -r 'echo md5(uniqid(rand(), true));') + OPENGNSYS_REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));') if [ ! -f $sqlfile ]; then errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!" @@ -659,6 +693,8 @@ function mysqlImportSqlFileToDb() sed -e "s/SERVERIP/${SERVERIP[i]}/g" \ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \ + -e "s/APIKEY/$OPENGNSYS_APIKEY/g" \ + -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \ $sqlfile > $tmpfile fi let i++ @@ -690,6 +726,9 @@ function mysqlCreateDb() errorAndLog "${FUNCNAME}(): error while creating database $database" return 1 fi + # Quitar modo ONLY_FULL_GROUP_BY de MySQL (ticket #730). + mysql --defaults-extra-file=$TMPMYCNF -e "SET GLOBAL sql_mode=(SELECT TRIM(BOTH ',' FROM REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')));" + echoAndLog "${FUNCNAME}(): database $database created" return 0 } @@ -766,7 +805,7 @@ function svnExportCode() svn export --force "$url" opengnsys if [ $? -ne 0 ]; then - errorAndLog "${FUNCNAME}(): error getting OpenGnSys code from $url" + errorAndLog "${FUNCNAME}(): error getting OpenGnsys code from $url" return 1 fi echoAndLog "${FUNCNAME}(): subversion code downloaded" @@ -787,8 +826,8 @@ function checkNetworkConnection() $STOPSERVICE; $DISABLESERVICE fi - echoAndLog "${FUNCNAME}(): Checking OpenGnSys server conectivity." - OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"} + echoAndLog "${FUNCNAME}(): Checking OpenGnsys server conectivity." + OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"} if which wget &>/dev/null; then wget --spider -q $OPENGNSYS_SERVER elif which curl &>/dev/null; then @@ -799,6 +838,15 @@ function checkNetworkConnection() fi } +# Convierte nº de bits (notación CIDR) en máscara de red (gracias a FriedZombie en openwrt.org). +cidr2mask () +{ + # Number of args to shift, 255..255, first non-255 byte, zeroes + set -- $[ 5 - ($1 / 8) ] 255 255 255 255 $[ (255 << (8 - ($1 % 8))) & 255 ] 0 0 0 + [ $1 -gt 1 ] && shift $1 || shift + echo ${1-0}.${2-0}.${3-0}.${4-0} +} + # Obtener los parámetros de red de la interfaz por defecto. function getNetworkSettings() { @@ -823,12 +871,10 @@ function getNetworkSettings() exit 1 fi for dev in ${DEVICE[*]}; do - SERVERIP[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}') + SERVERIP[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}') if [ -n "${SERVERIP[i]}" ]; then - NETMASK[i]=$(LANG=C ifconfig $dev | \ - awk '/Mask/ {sub(/.*:/,"",$4); print $4} - /netmask/ {print $4}') - NETBROAD[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {print ($6)}') + NETMASK[i]=$( cidr2mask $(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/.*\//, "", $4); print ($4)}') ) + NETBROAD[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {print ($6)}') NETIP[i]=$(ip route | awk -v d="$dev" '$3==d && /src/ {sub (/\/.*/,""); print $1}') ROUTERIP[i]=$(ip route | awk -v d="$dev" '$1=="default" && $5==d {print $3}') DEFAULTDEV=${DEFAULTDEV:-"$dev"} @@ -873,9 +919,6 @@ function tftpConfigure() service=$INETDSERV $ENABLESERVICE; $STARTSERVICE - # Copiar ficheros de Syslinux. - cp -a $SYSLINUXDIR $TFTPCFGDIR/syslinux - # comprobamos el servicio tftp sleep 1 testPxe @@ -892,7 +935,7 @@ function testPxe () ######################################################################## -## Configuracion servicio Samba +## Configuración servicio Samba ######################################################################## # Configurar servicios Samba. @@ -902,11 +945,11 @@ function smbConfigure() backupFile $SAMBACFGDIR/smb.conf - # Copiar plantailla de recursos para OpenGnSys + # Copiar plantailla de recursos para OpenGnsys sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \ $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf # Configurar y recargar Samba" - perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnSys Samba Server/" $SAMBACFGDIR/smb.conf + perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf fi @@ -925,7 +968,7 @@ function smbConfigure() ######################################################################## -## Configuracion servicio Rsync +## Configuración servicio Rsync ######################################################################## # Configurar servicio Rsync. @@ -976,7 +1019,7 @@ EOT ######################################################################## -## Configuracion servicio DHCP +## Configuración servicio DHCP ######################################################################## # Configurar servicios DHCP. @@ -1018,10 +1061,13 @@ function dhcpConfigure() ####### Funciones específicas de la instalación de Opengnsys ##################################################################### -# Copiar ficheros del OpenGnSys Web Console. +# Copiar ficheros del OpenGnsys Web Console. function installWebFiles() { local COMPATDIR f + local XAJAXFILE="xajax_0.5_standard.zip" + local SLIMFILE="slim-2.6.1.zip" + local SWAGGERFILE="swagger-ui-2.2.5.zip" echoAndLog "${FUNCNAME}(): Installing web files..." # Copiar ficheros. @@ -1031,8 +1077,12 @@ function installWebFiles() exit 1 fi find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null - # Descomprimir XAJAX. - unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax + + # Descomprimir librerías: XAJAX, Slim y Swagger-UI. + unzip -o $WORKDIR/opengnsys/admin/$XAJAXFILE -d $INSTALL_TARGET/www/xajax + unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest + unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest + # Compatibilidad con dispositivos móviles. COMPATDIR="$INSTALL_TARGET/www/principal" for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do @@ -1042,10 +1092,40 @@ function installWebFiles() # Cambiar permisos para ficheros especiales. chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos} chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/ + # Ficheros de log de la API REST. + touch $INSTALL_TARGET/log/{ogagent,remotepc,rest}.log + chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/{ogagent,remotepc,rest}.log echoAndLog "${FUNCNAME}(): Web files installed successfully." } +# Copiar ficheros en la zona de descargas de OpenGnsys Web Console. +function installDownloadableFiles() +{ + local FILENAME=ogagentpkgs-$INSTVERSION.tar.gz + local TARGETFILE=$WORKDIR/$FILENAME + + # Descargar archivo comprimido, si es necesario. + if [ -s $PROGRAMDIR/$FILENAME ]; then + echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)" + mv $PROGRAMDIR/$FILENAME $TARGETFILE + else + echoAndLog "${FUNCNAME}(): Downloading $FILENAME" + curl $DOWNLOADURL/$FILENAME -o $TARGETFILE + fi + if [ ! -s $TARGETFILE ]; then + errorAndLog "${FUNCNAME}(): Cannot download $FILENAME" + return 1 + fi + + # Descomprimir fichero en zona de descargas. + tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas + if [ $? != 0 ]; then + errorAndLog "${FUNCNAME}(): Error uncompressing archive." + exit 1 + fi +} + # Configuración específica de Apache. function installWebConsoleApacheConf() { @@ -1071,27 +1151,27 @@ function installWebConsoleApacheConf() $APACHESSLMOD $APACHEENABLESSL $APACHEMAKECERT - + # Activar módulo Rewrite. + $APACHEREWRITEMOD # Genera configuración de consola web a partir del fichero plantilla. if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then # Configuración para versiones anteriores de Apache. - sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \ + sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \ $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE} else # Configuración específica a partir de Apache 2.4 - sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \ + sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \ $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf fi $APACHEENABLEOG if [ $? -ne 0 ]; then errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation" return 1 - else - echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon" - service=$APACHESERV - $ENABLESERVICE; $STARTSERVICE - return 0 fi + echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon" + service=$APACHESERV + $ENABLESERVICE; $STARTSERVICE + return 0 } @@ -1133,7 +1213,7 @@ function createDirs() ln -fs $path_opengnsys_base/log /var/log/opengnsys mkdir -p $path_opengnsys_base/sbin mkdir -p $path_opengnsys_base/www - mkdir -p $path_opengnsys_base/images + mkdir -p $path_opengnsys_base/images/groups mkdir -p $TFTPCFGDIR ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot mkdir -p $path_opengnsys_base/tftpboot/menu.lst @@ -1146,10 +1226,10 @@ function createDirs() if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created" else - echoAndLog "${FUNCNAME}(): creating OpenGnSys user" + echoAndLog "${FUNCNAME}(): creating OpenGnsys user" useradd $OPENGNSYS_CLIENT_USER 2>/dev/null if [ $? -ne 0 ]; then - errorAndLog "${FUNCNAME}(): error creating OpenGnSys user" + errorAndLog "${FUNCNAME}(): error creating OpenGnsys user" return 1 fi fi @@ -1186,18 +1266,24 @@ function copyServerFiles () local SOURCES=( server/tftpboot \ server/bin \ repoman/bin \ + server/lib \ admin/Sources/Services/ogAdmServerAux admin/Sources/Services/ogAdmRepoAux installer/opengnsys_uninstall.sh \ installer/opengnsys_update.sh \ + installer/opengnsys_export.sh \ + installer/opengnsys_import.sh \ doc ) local TARGETS=( tftpboot \ bin \ bin \ + lib \ sbin \ sbin \ lib \ lib \ + lib \ + lib \ doc ) if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then @@ -1229,44 +1315,44 @@ function copyServerFiles () ### Funciones de compilación de código fuente de servicios #################################################################### -# Compilar los servicios de OpenGnSys +# Compilar los servicios de OpenGnsys function servicesCompilation () { local hayErrores=0 - # Compilar OpenGnSys Server - echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Server" + # Compilar OpenGnsys Server + echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server" pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer make && mv ogAdmServer $INSTALL_TARGET/sbin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server" hayErrores=1 fi popd - # Compilar OpenGnSys Repository Manager - echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Repository Manager" + # Compilar OpenGnsys Repository Manager + echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Repository Manager" pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo make && mv ogAdmRepo $INSTALL_TARGET/sbin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager" hayErrores=1 fi popd - # Compilar OpenGnSys Agent - echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Agent" + # Compilar OpenGnsys Agent + echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent" pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent make && mv ogAdmAgent $INSTALL_TARGET/sbin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent" hayErrores=1 fi popd - # Compilar OpenGnSys Client - echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Client" + # Compilar OpenGnsys Client + echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client" pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient make && mv ogAdmClient ../../../../client/shared/bin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Client" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client" hayErrores=1 fi popd @@ -1304,7 +1390,7 @@ function copyClientFiles() { local errstatus=0 - echoAndLog "${FUNCNAME}(): Copying OpenGnSys Client files." + echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files." cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client if [ $? -ne 0 ]; then errorAndLog "${FUNCNAME}(): error while copying client estructure" @@ -1312,7 +1398,7 @@ function copyClientFiles() fi find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null - echoAndLog "${FUNCNAME}(): Copying OpenGnSys Cloning Engine files." + echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files." mkdir -p $INSTALL_TARGET/client/lib/engine/bin cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin if [ $? -ne 0 ]; then @@ -1330,73 +1416,42 @@ function copyClientFiles() } -# Crear cliente OpenGnSys 1.0.2 y posteriores. +# Crear cliente OpenGnsys. function clientCreate() { - local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads" - local FILENAME=ogLive-precise-3.2.0-23-generic-r4311.iso # 1.0.6-kernel3.2 - #local FILENAME=ogLive-precise-3.11.0-26-generic-r4413.iso # 1.0.6-kernel3.11 + if [ $# -ne 1 ]; then + errorAndLog "${FUNCNAME}(): invalid number of parameters" + exit 1 + fi + + local FILENAME="$1" local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME - local TMPDIR=/tmp/${FILENAME%.iso} - local RSYNCSERV RSYNCCLNT # Descargar cliente, si es necesario. if [ -s $PROGRAMDIR/$FILENAME ]; then echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)" mv $PROGRAMDIR/$FILENAME $TARGETFILE else - echoAndLog "${FUNCNAME}(): Loading Client" - wget $DOWNLOADURL/$FILENAME -O $TARGETFILE + echoAndLog "${FUNCNAME}(): Downloading $FILENAME" + oglivecli download $FILENAME fi if [ ! -s $TARGETFILE ]; then - errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client" + errorAndLog "${FUNCNAME}(): Error loading $FILENAME" return 1 fi + # Montar imagen, copiar cliente ogclient y desmontar. - echoAndLog "${FUNCNAME}(): Copying Client files" - mkdir -p $TMPDIR - mount -o loop,ro $TARGETFILE $TMPDIR - cp -av $TMPDIR/ogclient $INSTALL_TARGET/tftpboot - umount $TMPDIR - rmdir $TMPDIR - # Asignar la clave cliente para acceso a Samba. - echoAndLog "${FUNCNAME}(): Set client access key" + echoAndLog "${FUNCNAME}(): Installing ogLive Client" echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \ - $INSTALL_TARGET/bin/setsmbpass - - # Establecer los permisos. - find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \; - find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \; - chown -R :$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/tftpboot/ogclient + oglivecli install $FILENAME + # Adaptar permisos. chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst - # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache - cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot - cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot - - # Montar SquashFS para comprobar versión de Rsync. - mkdir -p $TMPDIR - mount -o loop,ro $INSTALL_TARGET/tftpboot/ogclient/ogclient.sqfs $TMPDIR - # Si versión Rsync de servidor > cliente, enlazar a fichero compilado. - RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - if [ -z "$RSYNCSERV" -o ${RSYNCSERV:-0} -gt ${RSYNCCLNT:-1} ]; then - [ -e $INSTALL_TARGET/client/bin/rsync-$RSYNCSERV ] && mv -f $INSTALL_TARGET/client/bin/rsync-$RSYNCSERV $INSTALL_TARGET/client/bin/rsync - else - # Si no, renombrar fichero compilado con nº de protocolo. - [ -e $INSTALL_TARGET/client/bin/rsync ] && mv -f $INSTALL_TARGET/client/bin/rsync $INSTALL_TARGET/client/bin/rsync-$($INSTALL_TARGET/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - fi - # Desmontar SquashFS. - umount $TMPDIR - rmdir $TMPDIR - # Versión del ogLive instalado - echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt - echoAndLog "${FUNCNAME}(): Client generation success" } -# Configuración básica de servicios de OpenGnSys +# Configuración básica de servicios de OpenGnsys function openGnsysConfigure() { local i=0 @@ -1416,12 +1471,13 @@ function openGnsysConfigure() echo "* * * * * root [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator echo "5 * * * * root [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker echo "* * * * * root [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete + echo "* * * * * root [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue echoAndLog "${FUNCNAME}(): Creating logrotate configuration file." sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \ $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsys - echoAndLog "${FUNCNAME}(): Creating OpenGnSys config files." + echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files." for dev in ${DEVICE[*]}; do if [ -n "${SERVERIP[i]}" ]; then sed -e "s/SERVERIP/${SERVERIP[i]}/g" \ @@ -1430,6 +1486,7 @@ function openGnsysConfigure() -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \ $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg sed -e "s/SERVERIP/${SERVERIP[i]}/g" \ + -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \ $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg sed -e "s/SERVERIP/${SERVERIP[i]}/g" \ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \ @@ -1462,19 +1519,27 @@ function openGnsysConfigure() chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php chmod 600 $INSTALL_TARGET/www/controlacceso*.php + # Configuración del motor de clonación. + # - Zona horaria del servidor. + TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}') + cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg +# OpenGnsys Server timezone. +TZ="${TZ// /}" +EOT + # Revisar permisos generales. if [ -x $INSTALL_TARGET/bin/checkperms ]; then echoAndLog "${FUNCNAME}(): Checking permissions." - OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms + OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" checkperms fi # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init). - if [ -f /etc/init/${MYSQLSERV}.conf ]; then + if [ -f /etc/init/${MYSQLSERV}.conf -a -n "$(which initctl 2>/dev/null)" ]; then service=$MYSQLSERV $DISABLESERVICE fi - echoAndLog "${FUNCNAME}(): Starting OpenGnSys services." + echoAndLog "${FUNCNAME}(): Starting OpenGnsys services." service="opengnsys" $ENABLESERVICE; $STARTSERVICE } @@ -1488,7 +1553,7 @@ function installationSummary() { # Crear fichero de versión y revisión, si no existe. local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt" - [ -f $VERSIONFILE ] || echo "OpenGnSys Server" >$VERSIONFILE + [ -f $VERSIONFILE ] || echo "OpenGnsys Server" >$VERSIONFILE # Incluir datos de revisión, si se está instaladno desde el repositorio # de código o si no está incluida en el fichero de versión. if [ $USESVN -eq 1 ] || [ -z "$(awk '$3~/r[0-9]*/ {print}' $VERSIONFILE)" ]; then @@ -1498,7 +1563,7 @@ function installationSummary() # Mostrar información. echo - echoAndLog "OpenGnSys Installation Summary" + echoAndLog "OpenGnsys Installation Summary" echo "==============================" echoAndLog "Project version: $(cat $VERSIONFILE 2>/dev/null)" echoAndLog "Installation directory: $INSTALL_TARGET" @@ -1506,6 +1571,7 @@ function installationSummary() echoAndLog "Repository directory: $INSTALL_TARGET/images" echoAndLog "DHCP configuration directory: $DHCPCFGDIR" echoAndLog "TFTP configuration directory: $TFTPCFGDIR" + echoAndLog "Installed ogLive client(s): $(oglivecli list | awk '{print $2}')" echoAndLog "Samba configuration directory: $SAMBACFGDIR" echoAndLog "Web Console URL: $OPENGNSYS_CONSOLEURL" echoAndLog "Web Console access data: specified in installer script" @@ -1516,26 +1582,25 @@ function installationSummary() echoAndLog "Post-Installation Instructions:" echo "===============================" echoAndLog "Firewall service has been disabled and SELinux mode set to" - echoAndLog " permissive during OpenGnSys installation. Please check" + echoAndLog " permissive during OpenGnsys installation. Please check" echoAndLog " ${FIREWALLSERV:-firewall} and SELinux configuration, if needed." + echoAndLog "It's strongly recommended to synchronize this server with an NTP server." echoAndLog "Review or edit all configuration files." echoAndLog "Insert DHCP configuration data and restart service." echoAndLog "Optional: Log-in as Web Console admin user." echoAndLog " - Review default Organization data and assign access to users." echoAndLog "Log-in as Web Console organization user." - echoAndLog " - Insert OpenGnSys data (labs, computers, menus, etc)." - echoAndLog "Launch $INSTALL_TARGET/bin/installoglive script and select new ogLive" - echoAndLog " for clients' hardware compatibilty." + echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)." echo } ##################################################################### -####### Proceso de instalación de OpenGnSys +####### Proceso de instalación de OpenGnsys ##################################################################### -echoAndLog "OpenGnSys installation begins at $(date)" +echoAndLog "OpenGnsys installation begins at $(date)" pushd $WORKDIR # Detectar datos iniciales de auto-configuración del instalador. @@ -1556,7 +1621,7 @@ if [ $? -ne 0 ]; then exit 1 fi -# Detener servicios de OpenGnSys, si están activos previamente. +# Detener servicios de OpenGnsys, si están activos previamente. [ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop # Actualizar repositorios @@ -1582,7 +1647,7 @@ fi # Detectar datos de auto-configuración después de instalar paquetes. autoConfigurePost -# Arbol de directorios de OpenGnSys. +# Arbol de directorios de OpenGnsys. createDirs ${INSTALL_TARGET} if [ $? -ne 0 ]; then errorAndLog "Error while creating directory paths!" @@ -1600,7 +1665,7 @@ else ln -fs "$(dirname $PROGRAMDIR)" opengnsys fi -# Compilar código fuente de los servicios de OpenGnSys. +# Compilar código fuente de los servicios de OpenGnsys. servicesCompilation if [ $? -ne 0 ]; then errorAndLog "Error while compiling OpenGnsys services" @@ -1634,14 +1699,15 @@ if [ $? -ne 0 ]; then exit 1 fi -# Copiar ficheros de servicios OpenGnSys Server. +# Copiar ficheros de servicios OpenGnsys Server. copyServerFiles ${INSTALL_TARGET} if [ $? -ne 0 ]; then errorAndLog "Error while copying the server files!" exit 1 fi +INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt) -# Instalar base de datos de OpenGnSys Admin. +# Instalar base de datos de OpenGnsys Admin. isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server" if [ $? -eq 0 ]; then # Habilitar gestor de base de datos (MySQL, si falla, MariaDB). @@ -1699,7 +1765,6 @@ if [ $? -eq 0 ]; then fi else # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios. - INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt) REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt) OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql" if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then @@ -1712,15 +1777,17 @@ fi # Eliminar fichero temporal con credenciales de acceso a MySQL. rm -f $TMPMYCNF -# copiando paqinas web +# Copiando páqinas web. installWebFiles +# Descargar/descomprimir archivos descargables. +installDownloadableFiles # Generar páqinas web de documentación de la API makeDoxygenFiles -# creando configuracion de apache2 +# Creando configuración de Apache. installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR if [ $? -ne 0 ]; then - errorAndLog "Error configuring Apache for OpenGnSys Admin" + errorAndLog "Error configuring Apache for OpenGnsys Admin" exit 1 fi @@ -1732,20 +1799,21 @@ if [ $? -ne 0 ]; then errorAndLog "Error creating client structure" fi -# Crear la estructura del cliente de OpenGnSys -clientCreate -if [ $? -ne 0 ]; then - errorAndLog "Error creating client" - exit 1 -fi +# Crear la estructura del cliente de OpenGnsys. +for i in $OGLIVE; do + if ! clientCreate "$i"; then + errorAndLog "Error creating client $i" + exit 1 + fi +done -# Configuración de servicios de OpenGnSys +# Configuración de servicios de OpenGnsys openGnsysConfigure # Mostrar sumario de la instalación e instrucciones de post-instalación. installationSummary #rm -rf $WORKDIR -echoAndLog "OpenGnSys installation finished at $(date)" +echoAndLog "OpenGnsys installation finished at $(date)" exit 0 diff --git a/installer/opengnsys_makecompress.sh b/installer/opengnsys_makecompress.sh index 99156336..5cedcde4 100755 --- a/installer/opengnsys_makecompress.sh +++ b/installer/opengnsys_makecompress.sh @@ -2,7 +2,7 @@ # # Script: opengnsys_compress.sh # Descripción: Programa para descargar y generar un fichero comprimido con los -# datos de la última revisión de código del Proyecto OpenGnSys. +# datos de la última revisión de código del Proyecto OpenGnsys. # Salida: Datos del fichero comprimido generado. # Versión: 1.0 - Incluido en OpenGnSys 1.0.1 # Autor: Ramón Gómez, Universidad de Sevilla @@ -10,7 +10,7 @@ # Variables -SVNURL="http://www.opengnsys.es/svn/trunk/" +SVNURL="https://opengnsys.es/svn/trunk/" SVNREV=$(LANG=C svn info $SVNURL | awk '/Last Changed Rev:/ {print "r"$4}') # Descargar repositorio SVN diff --git a/installer/opengnsys_uninstall.sh b/installer/opengnsys_uninstall.sh index 8c206db1..a9cde989 100755 --- a/installer/opengnsys_uninstall.sh +++ b/installer/opengnsys_uninstall.sh @@ -1,7 +1,8 @@ #!/bin/bash + #/** -#@file opengnsys_update.sh -#@brief Script de desinstalación de OpenGnSys +#@file opengnsys_uninstall.sh +#@brief Script de desinstalación de OpenGnsys. #@warning No se elimina el directorio de imágenes, ni se desinstalan otros programas. #@version 0.10 - Primera prueba de desinstalación. #@author Ramón Gómez - ETSII Univ. Sevilla @@ -18,10 +19,14 @@ #@version 1.0.5 - Usar las mismas variables que el script de instalación. #@author Ramón Gómez - ETSII Univ. Sevilla #@date 2013/01/09 +#@version 1.1.0 - Solicitar confirmación para desinstalar. +#@author Ramón Gómez - ETSII Univ. Sevilla +#@date 2017/06/27 +#*/ ## #### AVISO: Editar configuración de acceso. -#### WARNING: Edit access configuration +#### WARNING: Edit access configuration. MYSQL_ROOT_PASSWORD="passwordroot" # Clave de root de MySQL OPENGNSYS_DATABASE="ogAdmBD" # Base de datos de administración OPENGNSYS_DB_USER="usuog" # Usuario de acceso a la base de datos @@ -29,11 +34,12 @@ OPENGNSYS_DB_USER="usuog" # Usuario de acceso a la base de datos #### AVISO: NO EDITAR variables de configuración. #### WARNING: DO NOT EDIT configuration variables. -OPENGNSYS="/opt/opengnsys" # Directorio de OpenGnSys +OPENGNSYS="/opt/opengnsys" # Directorio de OpenGnsys OGIMG="images" # Directorio de imágenes del repositorio OPENGNSYS_CLIENT_USER="opengnsys" # Usuario Samba OPENGNSYS_OLDDATABASE="ogBDAdmin" # Antigua base de datos MYCNF=/tmp/.my.cnf.$$ # Fichero temporal con credenciales de acceso a la BD. +TFTPDIR=$(readlink $OPENGNSYS/tftpboot 2>/dev/null) # Directorio de PXE/TFTP # Sólo ejecutable por usuario root @@ -42,9 +48,16 @@ if [ "$(whoami)" != 'root' ]; then exit 1 fi +# Solicitar confirmación para la desinstalación de OpenGnsys. +read -rp "WARNING: Files under $OPENGNSYS directory will be removed. Continue to uninstall? (y/n): " REPLY +if [ "${REPLY^^}" != "Y" ]; then + echo "Operation cancelled." + exit 0 +fi + # Parar servicio. -echo "Uninstalling OpenGnSys services." +echo "Uninstalling OpenGnsys services." if [ -x /etc/init.d/opengnsys ]; then /etc/init.d/opengnsys stop if [ -n "$(which update-rc.d 2>/dev/null)" ]; then @@ -54,11 +67,11 @@ if [ -x /etc/init.d/opengnsys ]; then fi fi # Comprobar acceso a la bases de datos. -echo "Erasing OpenGnSys database." +echo "Erasing OpenGnsys database." DROP=1 if ! mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<<"quit" 2>/dev/null; then stty -echo - read -p "- Please, insert MySQL root password: " MYSQL_ROOT_PASSWORD + read -rp "- Please, insert MySQL root password: " MYSQL_ROOT_PASSWORD echo "" stty echo if ! mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<<"quit" 2>/dev/null; then @@ -94,7 +107,7 @@ for serv in apache2 httpd; do [ -x /etc/init.d/$serv ] && /etc/init.d/$serv reload done # Eliminar ficheros. -echo "Deleting OpenGnSys files." +echo "Deleting OpenGnsys files." for dir in $OPENGNSYS/*; do if [ "$dir" != "$OPENGNSYS/$OGIMG" ]; then rm -fr "$dir" @@ -102,13 +115,13 @@ for dir in $OPENGNSYS/*; do done rm -f /etc/init.d/opengnsys /etc/default/opengnsys /var/log/opengnsys rm -f /etc/cron.d/{opengnsys,torrentcreator,torrenttracker} -# Elminar recursos de OpenGnSys en Samba. +# Elminar recursos de OpenGnsys en Samba. rm -f /etc/samba/smb-og.conf perl -ni -e "print unless /smb-og.conf/" /etc/samba/smb.conf for serv in smbd smb ; do [ -x /etc/init.d/$serv ] && /etc/init.d/$serv reload done -# Eliminar usuario de OpenGnSys. +# Eliminar usuario de OpenGnsys. smbpasswd -x $OPENGNSYS_CLIENT_USER userdel $OPENGNSYS_CLIENT_USER # Tareas manuales a realizar después de desinstalar. @@ -116,4 +129,5 @@ echo "Manual tasks:" echo "- You may stop or uninstall manually all other services" echo " (DHCP, PXE, TFTP, NFS/Samba, Apache, MySQL)." echo "- Delete repository directory \"$OPENGNSYS/$OGIMG\"" +[ -n "$TFTPDIR" ] && echo "- Delete PXE configuration directory \"$TFTPDIR\"" diff --git a/installer/opengnsys_update.sh b/installer/opengnsys_update.sh index dba1150a..11d08a94 100755 --- a/installer/opengnsys_update.sh +++ b/installer/opengnsys_update.sh @@ -1,7 +1,7 @@ #!/bin/bash #/** #@file opengnsys_update.sh -#@brief Script actualización de OpenGnSys +#@brief Script actualización de OpenGnsys #@version 0.9 - basado en opengnsys_installer.sh #@author Ramón Gómez - ETSII Univ. Sevilla #@date 2010/01/27 @@ -26,12 +26,16 @@ #@version 1.0.6 - Redefinir URLs de ficheros de configuración usando HTTPS. #@author Ramón Gómez - ETSII Univ. Sevilla #@date 2015/03/12 +#@version 1.1.0 - Instalación de API REST y configuración de zona horaria. +#@author Ramón Gómez - ETSII Univ. Sevilla +#@date 2015/11/09 #*/ #### AVISO: NO EDITAR variables de configuración. #### WARNING: DO NOT EDIT configuration variables. INSTALL_TARGET=/opt/opengnsys # Directorio de instalación +PATH=$PATH:$INSTALL_TARGET/bin OPENGNSYS_CLIENTUSER="opengnsys" # Usuario Samba @@ -40,9 +44,9 @@ if [ "$(whoami)" != 'root' ]; then echo "ERROR: this program must run under root privileges!!" exit 1 fi -# Error si OpenGnSys no está instalado (no existe el directorio del proyecto) +# Error si OpenGnsys no está instalado (no existe el directorio del proyecto) if [ ! -d $INSTALL_TARGET ]; then - echo "ERROR: OpenGnSys is not installed, cannot update!!" + echo "ERROR: OpenGnsys is not installed, cannot update!!" exit 1 fi # Cargar configuración de acceso a la base de datos. @@ -57,18 +61,19 @@ OPENGNSYS_DBPASSWORD=${OPENGNSYS_DBPASSWORD:-"$PASSWORD"} # Clave del usuario if [ -z "$OPENGNSYS_DATABASE" -o -z "$OPENGNSYS_DBUSER" -o -z "$OPENGNSYS_DBPASSWORD" ]; then echo "ERROR: set OPENGNSYS_DATABASE, OPENGNSYS_DBUSER and OPENGNSYS_DBPASSWORD" echo " variables, and run this script again." + exit 1 fi # Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1). PROGRAMDIR=$(readlink -e $(dirname "$0")) PROGRAMNAME=$(basename "$0") -OPENGNSYS_SERVER="www.opengnsys.es" +OPENGNSYS_SERVER="opengnsys.es" if [ -d "$PROGRAMDIR/../installer" ]; then USESVN=0 else USESVN=1 fi -SVN_URL="http://$OPENGNSYS_SERVER/svn/trunk/" +SVN_URL="https://$OPENGNSYS_SERVER/svn/tags/opengnsys-1.1.0/" WORKDIR=/tmp/opengnsys_update mkdir -p $WORKDIR @@ -109,8 +114,8 @@ OSVERSION="${OSVERSION%%.*}" # Configuración según la distribución de Linux. case "$OSDISTRIB" in ubuntu|debian|linuxmint) - DEPENDENCIES=( php5-ldap xinetd rsync btrfs-tools procps arp-scan ) - UPDATEPKGLIST="apt-get update" + DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php5-curl gettext moreutils jq wakeonlan ) + UPDATEPKGLIST="add-apt-repository -y ppa:ondrej/php; apt-get update" INSTALLPKGS="apt-get -y install --force-yes" CHECKPKG="dpkg -s \$package 2>/dev/null | grep -q \"Status: install ok\"" if which service &>/dev/null; then @@ -126,7 +131,7 @@ case "$OSDISTRIB" in INETDCFGDIR=/etc/xinetd.d ;; fedora|centos) - DEPENDENCIES=( php-ldap xinetd rsync btrfs-progs procps-ng arp-scan ) + DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq wakeonlan ) # En CentOS 7 instalar arp-scan de CentOS 6. [ "$OSDISTRIB$OSVERSION" == "centos7" ] && DEPENDENCIES=( ${DEPENDENCIES[*]/arp-scan/http://dag.wieers.com/redhat/el6/en/$(arch)/dag/RPMS/arp-scan-1.9-1.el6.rf.$(arch).rpm} ) INSTALLPKGS="yum install -y" @@ -148,7 +153,7 @@ case "$OSDISTRIB" in ;; esac for i in apache2 httpd; do - [ -f /etc/$i ] && APACHECFGDIR="/etc/$i" + [ -d /etc/$i ] && APACHECFGDIR="/etc/$i" [ -f /etc/init.d/$i ] && APACHESERV="/etc/init.d/$i" done for i in dhcpd dhcpd3-server isc-dhcp-server; do @@ -279,6 +284,8 @@ function importSqlFile() local tmpfile=$(mktemp) local mycnf=/tmp/.my.cnf.$$ local status + local APIKEY=$(php -r 'echo md5(uniqid(rand(), true));') + REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));') if [ ! -r $sqlfile ]; then errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!" @@ -288,7 +295,8 @@ function importSqlFile() echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..." chmod 600 $tmpfile sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \ - -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile + -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \ + -e "s/APIKEY/$APIKEY/g" -e "s/REPOKEY/$REPOKEY/g" $sqlfile > $tmpfile # Componer fichero con credenciales de conexión. touch $mycnf chmod 600 $mycnf @@ -309,6 +317,34 @@ EOT return 0 } +# Comprobar configuración de MySQL y recomendar cambios necesarios. +function checkMysqlConfig() +{ + if [ $# -ne 2 ]; then + errorAndLog "${FNCNAME}(): invalid number of parameters" + exit 1 + fi + + local dbuser="$1" + local dbpassword="$2" + local mycnf=/tmp/.my.cnf.$$ + + echoAndLog "${FUNCNAME}(): checking MySQL configuration" + touch $mycnf + cat << EOT > $mycnf +[client] +user=$dbuser +password=$dbpassword +EOT + # Check if scheduler is active. + if [ "$(mysql --defaults-extra-file=$mycnf -Nse 'SELECT @@GLOBAL.event_scheduler;')" = "OFF" ]; then + MYSQLCONFIG="SET GLOBAL event_scheduler = ON; " + fi + rm -f $mycnf + + echoAndLog "${FUNCNAME}(): MySQL configuration has checked" + return 0 +} ##################################################################### ####### Funciones de instalación de paquetes @@ -320,18 +356,19 @@ function installDependencies() local package if [ $# = 0 ]; then - echoAndLog "${FUNCNAME}(): no deps needed." + echoAndLog "${FUNCNAME}(): no dependencies are needed" else + PHP5VERSION=$(apt-cache pkgnames php5 2>/dev/null | sort | head -1) while [ $# -gt 0 ]; do - package="$1" - eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $1" + package="${1/php5/$PHP5VERSION}" + eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $package" shift done if [ -n "$INSTALLDEPS" ]; then $UPDATEPKGLIST $INSTALLPKGS $INSTALLDEPS if [ $? -ne 0 ]; then - errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS." + errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS" return 1 fi fi @@ -371,10 +408,31 @@ function svnExportCode() # Comprobar si existe conexión. function checkNetworkConnection() { - OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"} + OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"} wget --spider -q $OPENGNSYS_SERVER } +# Comprobar si la versión es anterior a la actual. +function checkVersion() +{ + local PRE + + # Obtener versión actual y versión a actualizar. + OLDVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt 2>/dev/null) + if [ $USESVN -eq 1 ]; then + NEWVERSION=$(curl -s $SVN_URL/doc/VERSION.txt 2>/dev/null | awk '{print $2}') + else + NEWVERSION=$(awk '{print $2}' $PROGRAMDIR/doc/VERSION.txt 2>/dev/null) + fi + [[ "$NEWVERSION" =~ pre ]] && PRE=1 + + # Comparar versiones. + [[ "$NEWVERSION" < "${OLDVERSION/pre/}" ]] && return 1 + [ "${NEWVERSION/pre/}" == "$OLDVERSION" -a "$PRE" == "1" ] && return 1 + + return 0 +} + # Obtener los parámetros de red del servidor. function getNetworkSettings() { @@ -384,7 +442,7 @@ function getNetworkSettings() local DEVICES local dev - echoAndLog "${FUNCNAME}(): Detecting network parameters." + echoAndLog "${FUNCNAME}(): Detecting network parameters" SERVERIP="$ServidorAdm" DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')" for dev in $DEVICES; do @@ -397,14 +455,14 @@ function getNetworkSettings() ####### Funciones específicas de la instalación de Opengnsys ##################################################################### -# Actualizar cliente OpenGnSys. +# Actualizar cliente OpenGnsys. function updateClientFiles() { local ENGINECFG=$INSTALL_TARGET/client/etc/engine.cfg # Actualizar ficheros del cliente. backupFile $ENGINECFG - echoAndLog "${FUNCNAME}(): Updating OpenGnSys Client files." + echoAndLog "${FUNCNAME}(): Updating OpenGnsys Client files" rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client if [ $? -ne 0 ]; then errorAndLog "${FUNCNAME}(): error while updating client structure" @@ -413,34 +471,62 @@ function updateClientFiles() find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null # Actualizar librerías del motor de clonación. - echoAndLog "${FUNCNAME}(): Updating OpenGnSys Cloning Engine files." + echoAndLog "${FUNCNAME}(): Updating OpenGnsys Cloning Engine files" rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin if [ $? -ne 0 ]; then errorAndLog "${FUNCNAME}(): error while updating engine files" exit 1 fi + # Actualizar fichero de configuración del motor de clonación. + if ! grep -q "^TZ" $ENGINECFG; then + TZ=$(timedatectl status | awk -F"[:()]" '/Time.*zone/ {print $2}') + cat << EOT >> $ENGINECFG +# OpenGnsys Server timezone. +TZ="${TZ// /}" +EOT + fi if ! diff -q ${ENGINECFG}{,-LAST} &>/dev/null; then NEWFILES="$NEWFILES $ENGINECFG" else rm -f ${ENGINECFG}-LAST fi + # Obtener URL para descargas adicionales. + DOWNLOADURL=$(oglivecli config download-url 2>/dev/null) + DOWNLOADURL=${DOWNLOADURL:-"https://$OPENGNSYS_SERVER/trac/downloads"} - echoAndLog "${FUNCNAME}(): client files update success." + echoAndLog "${FUNCNAME}(): client files successfully updated" } # Configurar HTTPS y exportar usuario y grupo del servicio Apache. function apacheConfiguration () { - # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2). + local config template + + # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2) y + # activar módulo Rewrite (solo actualizaciones desde 1.0.x a 1.1.x). if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then - echoAndLog "${FUNCNAME}(): Configuring HTTPS access..." - mv $APACHECFGDIR/sites-available/opengnsys.conf $APACHECFGDIR/sites-available/opengnsys + echoAndLog "${FUNCNAME}(): Configuring Apache modules" a2ensite default-ssl a2enmod ssl - a2dissite opengnsys.conf + a2enmod rewrite a2ensite opengnsys - $APACHESERV restart + elif [ -e $APACHECFGDIR/conf.modules.d ]; then + echoAndLog "${FUNCNAME}(): Configuring Apache modules" + sed -i '/rewrite/s/^#//' $APACHECFGDIR/*.conf fi + # Actualizar configuración de Apache a partir de fichero de plantilla. + for config in $APACHECFGDIR/{,sites-available/}opengnsys.conf; do + # Elegir plantilla según versión de Apache. + if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then + template=$WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $config + else + template=$WORKDIR/opengnsys/server/etc/apache.conf.tmpl + fi + sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g" $template > $config + done + + # Reiniciar Apache. + $APACHESERV restart # Variables de ejecución de Apache. # - APACHE_RUN_USER @@ -459,7 +545,7 @@ function rsyncConfigure() # Configurar acceso a Rsync. if [ ! -f /etc/rsyncd.conf ]; then - echoAndLog "${FUNCNAME}(): Configuring Rsync service." + echoAndLog "${FUNCNAME}(): Configuring Rsync service" NEWFILES="$NEWFILES /etc/rsyncd.conf" sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \ $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf @@ -491,7 +577,7 @@ EOT fi } -# Copiar ficheros del OpenGnSys Web Console. +# Copiar ficheros del OpenGnsys Web Console. function updateWebFiles() { local ERRCODE COMPATDIR f @@ -505,6 +591,8 @@ function updateWebFiles() ERRCODE=$? mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax + unzip -o $WORKDIR/opengnsys/admin/slim-2.6.1.zip -d $INSTALL_TARGET/www/rest + unzip -o $WORKDIR/opengnsys/admin/swagger-ui-2.2.5.zip -d $INSTALL_TARGET/www/rest if [ $ERRCODE != 0 ]; then errorAndLog "${FUNCNAME}(): Error updating web files." exit 1 @@ -525,11 +613,38 @@ function updateWebFiles() done cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php - # Cambiar permisos para ficheros especiales. - chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos} - chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/ + # Fichero de log de la API REST. + touch $INSTALL_TARGET/log/{ogagent,rest,remotepc}.log + chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/{ogagent,rest,remotepc}.log + + echoAndLog "${FUNCNAME}(): Web files successfully updated" +} + +# Copiar ficheros en la zona de descargas de OpenGnsys Web Console. +function updateDownloadableFiles() +{ + local FILENAME=ogagentpkgs-$NEWVERSION.tar.gz + local TARGETFILE=$WORKDIR/$FILENAME + + # Descargar archivo comprimido, si es necesario. + if [ -s $PROGRAMDIR/$FILENAME ]; then + echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)" + mv $PROGRAMDIR/$FILENAME $TARGETFILE + else + echoAndLog "${FUNCNAME}(): Downloading $FILENAME" + wget $DOWNLOADURL/$FILENAME -O $TARGETFILE + fi + if [ ! -s $TARGETFILE ]; then + errorAndLog "${FUNCNAME}(): Cannot download $FILENAME" + return 1 + fi - echoAndLog "${FUNCNAME}(): Web files updated successfully." + # Descomprimir fichero en zona de descargas. + tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas + if [ $? != 0 ]; then + errorAndLog "${FUNCNAME}(): Error uncompressing archive $FILENAME" + exit 1 + fi } # Copiar carpeta de Interface @@ -547,10 +662,7 @@ function updateInterfaceAdm() echoAndLog "${FUNCNAME}(): error while updating admin interface" exit 1 fi - chmod -R +x $INSTALL_TARGET/client/interfaceAdm - chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso - chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso - echoAndLog "${FUNCNAME}(): Admin interface updated successfully." + echoAndLog "${FUNCNAME}(): Admin interface successfully updated" } # Crear documentación Doxygen para la consola web. @@ -560,14 +672,13 @@ function makeDoxygenFiles() $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \ $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www if [ ! -d "$INSTALL_TARGET/www/html" ]; then - errorAndLog "${FUNCNAME}(): unable to create Doxygen web files." + errorAndLog "${FUNCNAME}(): unable to create Doxygen web files" return 1 fi rm -fr "$INSTALL_TARGET/www/api" mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api" rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf} - chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api - echoAndLog "${FUNCNAME}(): Doxygen web files created successfully." + echoAndLog "${FUNCNAME}(): Doxygen web files created successfully" } @@ -579,7 +690,7 @@ function createDirs() local dir mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www} - mkdir -p ${INSTALL_TARGET}/{client,images} + mkdir -p ${INSTALL_TARGET}/{client,images/groups} mkdir -p ${INSTALL_TARGET}/log/clients ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys # Detectar directorio de instalación de TFTP. @@ -588,35 +699,25 @@ function createDirs() [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot done fi - mkdir -p ${INSTALL_TARGET}/tftpboot/menu.lst + mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples if [ $? -ne 0 ]; then errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?" return 1 fi + ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples # Crear usuario ficticio. if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created" else - echoAndLog "${FUNCNAME}(): creating OpenGnSys user" + echoAndLog "${FUNCNAME}(): creating OpenGnsys user" useradd $OPENGNSYS_CLIENTUSER 2>/dev/null if [ $? -ne 0 ]; then - errorAndLog "${FUNCNAME}(): error creating OpenGnSys user" + errorAndLog "${FUNCNAME}(): error creating OpenGnsys user" return 1 fi fi - # Establecer los permisos básicos. - echoAndLog "${FUNCNAME}(): setting directory permissions" - chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/menu.lst} - mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples - ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples - chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/menu.lst} - if [ $? -ne 0 ]; then - errorAndLog "${FUNCNAME}(): error while setting permissions" - return 1 - fi - # Mover el fichero de registro al directorio de logs. echoAndLog "${FUNCNAME}(): moving update log file" mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE @@ -626,23 +727,79 @@ function createDirs() return 0 } +# Actualización incremental de la BD (versión actaul a actaul+1, hasta final-1 a final). +function updateDatabase() +{ + local DBDIR="$WORKDIR/opengnsys/admin/Database" + local file FILES="" + + echoAndLog "${FUNCNAME}(): looking for database updates" + pushd $DBDIR >/dev/null + # Bucle de actualización incremental desde versión actual a la final. + for file in $OPENGNSYS_DATABASE-*-*.sql; do + case "$file" in + $OPENGNSYS_DATABASE-$OLDVERSION-$NEWVERSION.sql) + # Actualización única de versión inicial y final. + FILES="$FILES $file" + break + ;; + $OPENGNSYS_DATABASE-*-postinst.sql) + # Ignorar fichero específico de post-instalación. + ;; + $OPENGNSYS_DATABASE-$OLDVERSION-*.sql) + # Actualización de versión n a n+1. + FILES="$FILES $file" + OLDVERSION="$(echo $file | cut -f3 -d-)" + ;; + $OPENGNSYS_DATABASE-*-$NEWVERSION.sql) + # Última actualización de versión final-1 a final. + if [ -n "$FILES" ]; then + FILES="$FILES $file" + break + fi + ;; + esac + done + # Aplicar posible actualización propia para la versión final. + file=$OPENGNSYS_DATABASE-$NEWVERSION.sql + if [ -n "$FILES" -o "$OLDVERSION" = "$NEWVERSION" -a -r $file ]; then + FILES="$FILES $file" + fi + + popd >/dev/null + if [ -n "$FILES" ]; then + for file in $FILES; do + importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $DBDIR/$file + done + echoAndLog "${FUNCNAME}(): database is update" + else + echoAndLog "${FUNCNAME}(): database unchanged" + fi +} + # Copia ficheros de configuración y ejecutables genéricos del servidor. function updateServerFiles() { # No copiar ficheros del antiguo cliente Initrd local SOURCES=( repoman/bin \ server/bin \ + server/lib \ admin/Sources/Services/ogAdmServerAux \ admin/Sources/Services/ogAdmRepoAux \ server/tftpboot \ installer/opengnsys_uninstall.sh \ + installer/opengnsys_export.sh \ + installer/opengnsys_import.sh \ doc ) local TARGETS=( bin \ bin \ + lib \ sbin/ogAdmServerAux \ sbin/ogAdmRepoAux \ tftpboot \ lib/opengnsys_uninstall.sh \ + lib/opengnsys_export.sh \ + lib/opengnsys_import.sh \ doc ) if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then @@ -680,12 +837,14 @@ function updateServerFiles() perl -pi -e 's!UrlMsg=.*msgbrowser\.php!UrlMsg=http://localhost/cgi-bin/httpd-log\.sh!g; s!UrlMenu=http://!UrlMenu=https://!g' $INSTALL_TARGET/client/etc/ogAdmClient.cfg NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg" fi + echoAndLog "${FUNCNAME}(): updating cron files" [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * * root [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete - echoAndLog "${FUNCNAME}(): server files updated successfully." + [ ! -f /etc/cron.d/ogagentqueue ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue + echoAndLog "${FUNCNAME}(): server files successfully updated" } #################################################################### @@ -718,40 +877,44 @@ function compileServices() { local hayErrores=0 - # Compilar OpenGnSys Server - echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Admin Server" + # Compilar OpenGnsys Server + echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Admin Server" pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer make && moveNewService ogAdmServer $INSTALL_TARGET/sbin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server" hayErrores=1 fi popd - # Compilar OpenGnSys Repository Manager - echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Repository Manager" + # Compilar OpenGnsys Repository Manager + echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Repository Manager" pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo make && moveNewService ogAdmRepo $INSTALL_TARGET/sbin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager" hayErrores=1 fi popd - # Compilar OpenGnSys Agent - echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Agent" + # Actualizar o insertar clave de acceso REST en el fichero de configuración del repositorio. + grep -q '^ApiToken=' $INSTALL_TARGET/etc/ogAdmRepo.cfg && \ + sed -i "s/^ApiToken=.*$/ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg || \ + sed -i "$ a\ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg + # Compilar OpenGnsys Agent + echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Server Agent" pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent make && moveNewService ogAdmAgent $INSTALL_TARGET/sbin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Server Agent" hayErrores=1 fi popd - # Compilar OpenGnSys Client - echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Client" + # Compilar OpenGnsys Client + echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Client" pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient make && mv ogAdmClient $INSTALL_TARGET/client/bin if [ $? -ne 0 ]; then - echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Client" + echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Client" hayErrores=1 fi popd @@ -761,116 +924,60 @@ function compileServices() #################################################################### -### Funciones instalacion cliente OpenGnSys +### Funciones instalacion cliente OpenGnsys #################################################################### -# Actualizar cliente OpenGnSys +# Actualizar cliente OpenGnsys function updateClient() { - local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads" - local FILENAME=ogLive-precise-3.2.0-23-generic-r4311.iso # 1.0.4-rc4 - #local FILENAME=ogLive-precise-3.11.0-26-generic-r4413.iso # 1.0.6-rc1 + #local FILENAME=ogLive-precise-3.2.0-23-generic-r5159.iso # 1.1.0-rc6 (old) + local FILENAME=ogLive-xenial-4.8.0-39-generic-amd64-r5331.iso # 1.1.0-rc6 local SOURCEFILE=$DOWNLOADURL/$FILENAME - local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME - local SOURCELENGTH TARGETLENGTH - local TMPDIR=/tmp/${FILENAME%.iso} - local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img - local OGVMLINUZ=$INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz + local TARGETFILE=$(oglivecli config download-dir)/$FILENAME + local SOURCELENGTH + local TARGETLENGTH + local OGINITRD local SAMBAPASS - local KERNELVERSION - local RSYNCSERV RSYNCCLNT + # Comprobar si debe convertirse el antiguo cliente al nuevo formato ogLive. + if oglivecli check | grep -q "oglivecli convert"; then + echoAndLog "${FUNCNAME}(): Converting OpenGnsys Client to default ogLive" + oglivecli convert + fi # Comprobar si debe actualizarse el cliente. SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}') - TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}') + TARGETLENGTH=$(stat -c "%s" $TARGETFILE 2>/dev/null) [ -z $TARGETLENGTH ] && TARGETLENGTH=0 if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then - echoAndLog "${FUNCNAME}(): Loading Client" - wget $DOWNLOADURL/$FILENAME -O $TARGETFILE + echoAndLog "${FUNCNAME}(): Downloading $FILENAME" + oglivecli download $FILENAME if [ ! -s $TARGETFILE ]; then - errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client" + errorAndLog "${FUNCNAME}(): Error downloading $FILENAME" return 1 fi - # Obtener la clave actual de acceso a Samba para restaurarla. - if [ -f $OGINITRD ]; then - SAMBAPASS=$(gzip -dc $OGINITRD | \ - cpio -i --to-stdout scripts/ogfunctions 2>&1 | \ - grep "^[ ].*OPTIONS=" | \ - sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') - fi - # Montar la imagen ISO del ogclient, actualizar ficheros y desmontar. - echoAndLog "${FUNCNAME}(): Updatting ogclient files" - mkdir -p $TMPDIR - mount -o loop,ro $TARGETFILE $TMPDIR - rsync -irlt $TMPDIR/ogclient $INSTALL_TARGET/tftpboot - umount $TMPDIR - rmdir $TMPDIR - # Recuperar la clave de acceso a Samba. - if [ -n "$SAMBAPASS" ]; then - echoAndLog "${FUNCNAME}(): Restoring client access key" - echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \ - $INSTALL_TARGET/bin/setsmbpass - fi - # Establecer los permisos. - find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \; - find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \; - chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/tftpboot/ogclient - chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst - - # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache - cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot - cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot + # Actaulizar la imagen ISO del ogclient. + echoAndLog "${FUNCNAME}(): Updatting ogLive client" + oglivecli install $FILENAME - # Obtiene versión del Kernel del cliente (con 2 decimales). - KERNELVERSION=$(file -bkr $OGVMLINUZ 2>/dev/null | \ - awk '/Linux/ { for (i=1; i<=NF; i++) - if ($i~/version/) { - v=$(i+1); - printf ("%d",v); - sub (/[0-9]*\./,"",v); - printf (".%02d",v) - } }') - # Actaulizar la base de datos adaptada al Kernel del cliente. - OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-postinst.sql" - if [ -f $OPENGNSYS_DBUPDATEFILE ]; then - perl -pi -e "s/KERNELVERSION/$KERNELVERSION/g" $OPENGNSYS_DBUPDATEFILE - importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE - fi - - # Montar SquashFS para comprobar versión de Rsync. - mkdir -p $TMPDIR - mount -o loop,ro $INSTALL_TARGET/tftpboot/ogclient/ogclient.sqfs $TMPDIR - # Si versión Rsync de servidor > cliente, enlazar a fichero compilado. - RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - if [ -z "$RSYNCSERV" -o ${RSYNCSERV:-0} -gt ${RSYNCCLNT:-1} ]; then - [ -e $INSTALL_TARGET/client/bin/rsync-$RSYNCSERV ] && mv -f $INSTALL_TARGET/client/bin/rsync-$RSYNCSERV $INSTALL_TARGET/client/bin/rsync - else - # Si no, renombrar fichero compilado con nº de protocolo. - [ -e $INSTALL_TARGET/client/bin/rsync ] && mv -f $INSTALL_TARGET/client/bin/rsync $INSTALL_TARGET/client/bin/rsync-$($INSTALL_TARGET/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') - fi - # Desmontar SquashFS. - umount $TMPDIR - rmdir $TMPDIR CLIENTUPDATED=${FILENAME%.*} - echoAndLog "${FUNCNAME}(): Client update successfully" + echoAndLog "${FUNCNAME}(): ogLive successfully updated" else # Si no existe, crear el fichero de claves de Rsync. if [ ! -f /etc/rsyncd.secrets ]; then - echoAndLog "${FUNCNAME}(): Restoring client access key" + echoAndLog "${FUNCNAME}(): Restoring ogLive access key" + OGINITRD=$(oglivecli config install-dir)/$(jq -r ".oglive[.default].directory")/oginitrd.img SAMBAPASS=$(gzip -dc $OGINITRD | \ cpio -i --to-stdout scripts/ogfunctions 2>&1 | \ grep "^[ ].*OPTIONS=" | \ sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') - echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \ - $INSTALL_TARGET/bin/setsmbpass + echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | setsmbpass else - echoAndLog "${FUNCNAME}(): Client is already updated" + echoAndLog "${FUNCNAME}(): ogLive is already updated" fi + # Versión del ogLive instalado. + echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt fi - # Versión del ogLive instalado - echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt } # Comprobar permisos y ficheros. @@ -878,13 +985,13 @@ function checkFiles() { # Comprobar permisos adecuados. if [ -x $INSTALL_TARGET/bin/checkperms ]; then - echoAndLog "${FUNCNAME}(): Checking permissions." + echoAndLog "${FUNCNAME}(): Checking permissions" OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms fi # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes if [ -f /tmp/dstate ]; then - echoAndLog "${FUNCNAME}(): Delete unused files." + echoAndLog "${FUNCNAME}(): Deleting unused files" rm -f /tmp/dstate fi } @@ -896,11 +1003,11 @@ function updateSummary() local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt" local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}') - [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE + [ -f $VERSIONFILE ] || echo "OpenGnsys" >$VERSIONFILE perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE echo - echoAndLog "OpenGnSys Update Summary" + echoAndLog "OpenGnsys Update Summary" echo "========================" echoAndLog "Project version: $(cat $VERSIONFILE)" echoAndLog "Update log file: $LOG_FILE" @@ -912,29 +1019,32 @@ function updateSummary() # Indicar si se debe reiniciar servicios manualmente o usando el Cron. [ -f /etc/default/opengnsys ] && source /etc/default/opengnsys if [ "$RUN_CRONJOB" == "no" ]; then - echoAndLog " WARNING: you must restart OpenGnSys services manually." + echoAndLog " WARNING: you must to restart OpenGnsys services manually" else - echoAndLog " New OpenGnSys services will be restarted by the cronjob." + echoAndLog " New OpenGnsys services will be restarted by the cronjob" fi fi echoAndLog "Warnings:" - echoAndLog " - You must to clear web browser cache before loading OpenGnSys page." + echoAndLog " - You must to clear web browser cache before loading OpenGnsys page" + echoAndLog " - Generated new key to access Repository REST API (file ogAdmRepo.cfg)" if [ -n "$CLIENTUPDATED" ]; then echoAndLog " - ogLive Client is updated to: $CLIENTUPDATED" fi - echoAndLog " - Launch $INSTALL_TARGET/bin/installoglive script and select new ogLive" - echoAndLog " for clients' hardware compatibilty." + if [ -n "$MYSQLCONFIG" ]; then + echoAndLog " - MySQL must be reconfigured, run next code as DB root user and restart service:" + echoAndLog " $MYSQLCONFIG" + fi echo } ##################################################################### -####### Proceso de actualización de OpenGnSys +####### Proceso de actualización de OpenGnsys ##################################################################### -echoAndLog "OpenGnSys update begins at $(date)" +echoAndLog "OpenGnsys update begins at $(date)" pushd $WORKDIR @@ -942,19 +1052,27 @@ pushd $WORKDIR checkNetworkConnection if [ $? -ne 0 ]; then errorAndLog "Error connecting to server. Causes:" - errorAndLog " - Network is unreachable, review devices parameters." - errorAndLog " - You are inside a private network, configure the proxy service." - errorAndLog " - Server is temporally down, try agian later." + errorAndLog " - Network is unreachable, check device parameters" + errorAndLog " - You are inside a private network, configure the proxy service" + errorAndLog " - Server is temporally down, try again later" exit 1 fi getNetworkSettings +# Comprobar si se intanta actualizar a una versión anterior. +checkVersion +if [ $? -ne 0 ]; then + errorAndLog "Cannot downgrade to an older version ($OLDVERSION to $NEWVERSION)" + errorAndLog "You must to uninstall OpenGnsys and install desired release" + exit 1 +fi + # Comprobar auto-actualización del programa. if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then checkAutoUpdate if [ $? -ne 0 ]; then - echoAndLog "OpenGnSys updater has been overwritten." - echoAndLog "Please, re-execute this script." + echoAndLog "OpenGnsys updater has been overwritten" + echoAndLog "Please, rerun this script" exit fi fi @@ -965,14 +1083,14 @@ autoConfigure # Instalar dependencias. installDependencies ${DEPENDENCIES[*]} if [ $? -ne 0 ]; then - errorAndLog "Error: you may install all needed dependencies." + errorAndLog "Error: you must to install all needed dependencies" exit 1 fi -# Arbol de directorios de OpenGnSys. +# Arbol de directorios de OpenGnsys. createDirs ${INSTALL_TARGET} if [ $? -ne 0 ]; then - errorAndLog "Error while creating directory paths!" + errorAndLog "Error while creating directory paths" exit 1 fi @@ -980,32 +1098,23 @@ fi if [ $USESVN -eq 1 ]; then svnExportCode $SVN_URL if [ $? -ne 0 ]; then - errorAndLog "Error while getting code from svn" + errorAndLog "Error while getting code from svn server" exit 1 fi else ln -fs "$(dirname $PROGRAMDIR)" opengnsys fi -# Si existe fichero de actualización de la base de datos; aplicar cambios. -INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt) -REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt) -if [ "$INSTVERSION" == "$REPOVERSION" ]; then - OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION.sql" -else - OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql" -fi -if [ -f $OPENGNSYS_DBUPDATEFILE ]; then - echoAndLog "Updating tables from file: $(basename $OPENGNSYS_DBUPDATEFILE)" - importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE -else - echoAndLog "Database unchanged." -fi +# Comprobar configuración de MySQL. +checkMysqlConfig $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD + +# Actualizar la BD. +updateDatabase # Actualizar ficheros complementarios del servidor updateServerFiles if [ $? -ne 0 ]; then - errorAndLog "Error updating OpenGnSys Server files" + errorAndLog "Error updating OpenGnsys Server files" exit 1 fi @@ -1020,9 +1129,11 @@ updateInterfaceAdm apacheConfiguration updateWebFiles if [ $? -ne 0 ]; then - errorAndLog "Error updating OpenGnSys Web Admin files" + errorAndLog "Error updating OpenGnsys Web Admin files" exit 1 fi +# Actaulizar ficheros descargables. +updateDownloadableFiles # Generar páginas Doxygen para instalar en el web makeDoxygenFiles @@ -1032,7 +1143,7 @@ compileServices # Actaulizar ficheros auxiliares del cliente updateClient if [ $? -ne 0 ]; then - errorAndLog "Error updating clients" + errorAndLog "Error updating client files" exit 1 fi @@ -1043,7 +1154,7 @@ checkFiles updateSummary #rm -rf $WORKDIR -echoAndLog "OpenGnSys update finished at $(date)" +echoAndLog "OpenGnsys update finished at $(date)" popd diff --git a/installer/vagrant/README.es.txt b/installer/vagrant/README.es.txt new file mode 100644 index 00000000..ce40f709 --- /dev/null +++ b/installer/vagrant/README.es.txt @@ -0,0 +1,75 @@ + +Preparar entorno virtual de desarrollo para OpenGnsys +===================================================== + + +Ficheros de configuración disponibles: + + - Vagrantfile-trunk-vbox Vagrantfile para OpenGnsys estable con proveedor VirtualBox. + - Vagrantfile-devel-vbox Vagrantfile para OpenGnsys en desarrollo con proveedor VirtualBox. + - Vagrantfile-boottools-vbox Vagrantfile para preparar el entorno de generación del cliente ogLive (recomendado solo para desarrolladores experimentados). + - Vagrantfile-browser-vbox Vagrantfile para preparar el entorno de desarrollo del Browser del cliente (recomendado solo para miembros del grupo de desarrollo). + - Vagrantfile-ogagent-vbox Vagrantfile para preparar el entorno de desarrollo del agente OGAgent (recomendado solo para miembros del grupo de desarrollo). + + +Requisitos previos. + + - Instalar Oracle VM VirtualBox 5.x con su Extension Pack. + - Instalar la última versión oficial de Vagrant (no usar la incluida en Ubuntu 14.04). + + +El entorno de trabajo de OpenGnsys. + + - ogAdministrator: MV para servidor OpenGnsys basada en Ubuntu 16.04 y 2º disco para repositorio. + - pc11: MV cliente mlodelo con Ubuntu 16.04 instalado. + - pc12 - ogclientN: MV clientes para restaurar con disco vacío. + + +Ejecutar el entorno virtual (Vagrantfile-trunk-vbox y Vagrantfile-devel-vbox). + + - Crear un directorio de trabajo. + - Copiar el fichero Vagrantfile-...-vbox correspondiente en dicho directorio como Vagrantfile. + - Opcional: editar las variables de configuración del fichero Vagrantfile para el entorno personal. + - LANGUAGE: idioma (se aceptan es_ES, ca_ES y en_GB). + - NCLIENTS: nº de clientes a generar (de 2 a 9). + - REPODISK, REPOSIZE: fichero y tamaño (en GB) del disco virtual para el repositorio de imágenes. + - SERVERMEM, CLIENTMEM: memoria virtual (en MB) para servidor y clientes (mínimo 256 MB). + - NETPREFIX: prefijo para las direcciones IP de la red virtual. + - MACPREFIX: prefijo para las direcciones MAC de los clientes. + - SERVERIP: dirección IP del servidor OpenGnsys + - LOCALWEBPORT: puerto local para acceder al web de administración del servidor. + - Opcional: para una definición automática del aula virtual con sus clientes, descomentar las líneas del fichero Vagrantfile de los comandos "mysql" y "setclientmode". + + - Iniciar la MV del servidor: + vagrant up + - Iniciar las MV de los clientes (tras iniciar el servidor): + - Cliente modelo: + vagrant up pc11 + - Clientes vacíos para restaurar: + vagrant up pcX (siendo X de 12 al nº máximo definido + 10) + +Notas: + - Los procesos de inicio pueden tardar varios minutos en la primera ejecución, porque descargan y configuran las máquinas virtuales. + - Si se producen errores al instalar paquetes en el servidor, volver a aprovisionarlo ejecutando "vagrant provision" (o "vagrant up --provision", si la MV está parada). + - Antes de iniciar las MV de los clientes, debe accederse a la web de OpenGnsys para crear el aula e incorporar los equipos (o revisar que los datos son correctos). + - Ignorar los errores de conexión de Vagrant con los clientes vacíos. + + +Descripción de las MV. + + - Máquina virtual para servidor OpenGnsys. + - Debe estar iniciada en primer lugar y activa para gestionar los clientes. + - Usuario de acceso SSH: vagrant, clave: vagrant. + - La interfaz 2 de VirtualBox está definida en la red privada para las MV del entorno. + - Instalación de OpenGnsys Server con datos por defecto. + - Acceder desde un navegador del host local a la web de OpenGnsys en la URL: + https://localhost:8443/opengnsys/ + - Configurar el DHCP usando las direcciones MAC de los clientes según lo indicado en la definición de la interfaz 2 de cada MV en Virtual Box. + + - Máquinas virtuales para cliente modelo y clientes para clonar. + - La interfaz 2 de cada MV VirtualBox está definida en la red privada del entorno. + - Ignorar los posibles errores de conexión de Vagrant. + - Usar VirtualBox para deshabilitar la interfaz 1 de la MV del cliente modelo. + - Una vez desplegadas las MV deberán ser controladas directamente con VirtaulBox. + + diff --git a/installer/vagrant/Vagrantfile-1.0.6b-vbox b/installer/vagrant/Vagrantfile-1.0.6b-vbox new file mode 100644 index 00000000..2db25e1c --- /dev/null +++ b/installer/vagrant/Vagrantfile-1.0.6b-vbox @@ -0,0 +1,152 @@ +# Vagrantfile to install old OpenGnSys 1.0.6b virtual environment using VirtualBox provider. + +VAGRANTFILE_API_VERSION = "2" +# VM provider: Oracle VM VirtualBox. +ENV['VAGRANT_DEFAULT_PROVIDER'] = "virtualbox" +# Language (accepted values: es_ES, ca_ES, en_GB). +LANGUAGE = "es_ES" +ENV['LC_ALL'] = LANGUAGE + ".UTF-8" +# Number of OpenGnsys clients (accepted values: from 2 to 9). +NCLIENTS = 4 +# Repository virtual disk: file and size (GB). +REPODISK = "ogRepo.vdi" +REPOSIZE = 50 +# Amount of memory for server and clients (MB) +SERVERMEM = 1024 # Minimum: 512 +CLIENTMEM = 512 # Minimum: 256 +# Clients MAC address prefix. +MACPREFIX = "08:00:27:0E:65" +NETPREFIX = "192.168.2" +# Local port to access OpenGnsys Server. +LOCALWEBPORT = 8443 + +# OpenGnsys Server provisioning script: prepare repo disk, install OpenGnsys, change default interface, configure DHCP server. +OGSERVERSCRIPT = </dev/null; then + apt-get update + apt-get install -y lvm2 + fi + pvcreate /dev/sdb + vgcreate og /dev/sdb + vgchange -ay + lvcreate -ay -n images -l 100%VG og + mkfs -t ext4 /dev/mapper/og-images + mkdir -p /opt/opengnsys/images + echo "/dev/mapper/og-images /opt/opengnsys/images ext4 defaults 0 0" >> /etc/fstab + mount -a +fi +# Install OpenGnsys and change server address. +wget -q https://opengnsys.es/svn/tags/opengnsys-1.0.6b/installer/opengnsys_installer.sh -O - | bash || exit $? +mv /opt/opengnsys/log/bash.log /opt/opengnsys/log/opengnsys_installer.log +echo y | /opt/opengnsys/bin/setserveraddr eth1 +# Insert DHCP data. +for ((i=#{NCLIENTS+10}; i>10; i--)); do + sed -i "/^}$/ i host pc${i} { hardware ethernet #{MACPREFIX}:${i}; fixed-address #{NETPREFIX}.${i}; }" /etc/dhcp/dhcpd.conf +done +service isc-dhcp-server restart +# Set language. +export LANG="#{LANGUAGE}.UTF-8" +echo "LANG=\"$LANG\"" > /etc/default/locale +echo "LANG=\"$LANG\"" >> /etc/environment +locale-gen --lang #{LANGUAGE} +sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\"${LANG%_*}\"/" /etc/default/keyboard +dpkg-reconfigure -fnoninteractive console-setup +# Comment out next lines for automatic data insertion. +#SQL="INSERT INTO aulas (nombreaula, idcentro, urlfoto, grupoid, ubicacion, puestos, modomul, ipmul, pormul, velmul, router, netmask, dns, proxy, modp2p, timep2p) VALUES ('Aula virtual', 1, 'aula.jpg', 0, 'Despliegue virtual con Vagrant.', 5, 2, '239.194.2.11', 9000, 70, '#{NETPREFIX}.1', '255.255.255.0', '', '', 'peer', 30); INSERT INTO ordenadores (nombreordenador, ip, mac, idaula, idrepositorio, idperfilhard, idmenu, idproautoexec, grupoid, router, mascara, arranque, netiface, netdriver, fotoord) VALUES" +#for ((i=11; i<=#{NCLIENTS+10}; i++)); do +# SQL="$SQL ('pc$i', '#{NETPREFIX}.$i', REPLACE('#{MACPREFIX}$i',':',''), 1, 1, 0, 0, 0, 0, '#{NETPREFIX}.1', '255.255.255.0', '00unknown', 'eth0', 'generic', 'fotoordenador.gif')," +#done +#mysql -u usuog -ppassusuog -D ogAdmBD -e "${SQL%,}" +#if ! grep -q "1\.0" /opt/opengnsys/doc/VERSION.txt; then AUX=1; fi +#/opt/opengnsys/bin/setclientmode ogAdmin pc11 $AUX +#for ((i=12; i<=#{NCLIENTS+10}; i++)); do +# /opt/opengnsys/bin/setclientmode ogClient pc$i $AUX +#done +echo "New OpenGnsys local URL: https://localhost:#{LOCALWEBPORT}/opengnsys/" +EOT + +# Client 1 OS provisioning script. +MODELSCRIPT = < /etc/default/locale +echo "LANG=\"$LANG\"" >> /etc/environment +locale-gen --lang #{LANGUAGE} +sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\"${LANG%_*}\"/" /etc/default/keyboard +dpkg-reconfigure -fnoninteractive console-setup +# Install dependencies. +apt-get update -y +apt-get install -y subversion +# Prepare environment. +groupadd opengnsys +mkdir -p /opt/opengnsys/client /tmp/opengnsys_installer/opengnsys +ln -fs /var/lib/tftpboot /opt/opengnsys +svn export https://opengnsys.es/svn/trunk/client /tmp/opengnsys_installer/opengnsys/client +echo "Connect to this VM, launch boot-tools generation script and follow instructions:" +echo " sudo /tmp/opengnsys_installer/opengnsys/client/boot-tools/boottoolsgenerator.sh" +echo "Warning: this process may take a long time." +echo "ogLive ISO file will be located in /opt/opengnsys/tftpboot/ogclient directory." +EOT + +Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| + + # OpenGnsys boot-tools environment VM definition. + config.vm.define "ogBootTools" do |bt| + # Specific VirtualBox configuration. + bt.vm.provider "virtualbox" do |vb| + # VM name, memory and CPUs. + vb.name = "ogBootTools" + vb.memory = VMMEM + vb.cpus = 1 + end + # VM base and host name. + bt.vm.box = "ubuntu/xenial64" + bt.vm.hostname = "ogBootTools" + # Comment out to disable synced folder. + #bt.vm.synced_folder ".", "/vagrant", disabled: true + # Launch provisioning script. + bt.vm.provision "shell", inline: SCRIPT + end + +end + diff --git a/installer/vagrant/Vagrantfile-browser-vbox b/installer/vagrant/Vagrantfile-browser-vbox new file mode 100644 index 00000000..9cf3661c --- /dev/null +++ b/installer/vagrant/Vagrantfile-browser-vbox @@ -0,0 +1,69 @@ +# Vagrantfile to compile OpenGnsys Browser using VirtualBox provider. + +VAGRANTFILE_API_VERSION = "2" +# VM provider: Oracle VM VirtualBox. +ENV['VAGRANT_DEFAULT_PROVIDER'] = "virtualbox" +# Language. +LANGUAGE = "es_ES" +ENV['LC_ALL'] = LANGUAGE + ".UTF-8" +# Amount of virtual memory and virtual CPUs. +VMMEM = 2048 +VMCPUS = 2 +# OpenGnsys boot-tools environment provisioning script. +SCRIPT = < /etc/default/locale +echo "LANG=\"$LANG\"" >> /etc/environment +locale-gen --lang #{LANGUAGE} +sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\"${LANG%_*}\"/" /etc/default/keyboard +dpkg-reconfigure -fnoninteractive console-setup +# Install main dependencies. +apt-get update +apt-get install -y build-essential gettext libssl-dev libucommon-dev libxtst-dev subversion +# Compile Qt-Embedded 4.8 (aceptar la licencia Open Source). +wget http://download.qt.io/official_releases/qt/4.8/4.8.7/qt-everywhere-opensource-src-4.8.7.tar.gz +tar xvzf qt-everywhere-opensource-src-4.8.7.tar.gz +cd qt-everywhere-opensource-src-4.8.7 +echo "yes" | ./configure -opensource -embedded x86 -webkit -openssl -qt-gfx-vnc -qvfb -prefix /usr/local/ -nomake demos -nomake examples +make +make install +# Compile Browser. +svn export https://opengnsys.es/svn/branches/version1.1/client/browser ../browser +cd browser +qmake browser.pro +make +strip browser +# Instructions. +echo "Browser's code is in /home/vagrant/browser directory." +echo "To compile a new Browser, run as root user:" +echo " cd /home/vagrant/browser && qmake browser.pro && make" +echo "Do not forget to copy all Browser's files to OpenGnsys Server:" +echo " - Browser binary to /opt/opengnsys/client/bin directory on server." +echo " - Qt linked libraries to /opt/opengnsys/client/lib/qtlibs directory." +echo " - 64-bit-based ogLive only: libssl and libcrypto to /opt/opengnsys/client/lib/qtlibs directory." +EOT + +Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| + + # OpenGnsys boot-tools environment VM definition. + config.vm.define "ogBrowser" do |br| + # Specific VirtualBox configuration. + br.vm.provider "virtualbox" do |vb| + # VM name, memory and CPUs. + vb.name = "ogBrowser" + vb.memory = VMMEM + vb.cpus = VMCPUS + vb.gui = true + end + # VM base and host name. + br.vm.box = "ubuntu/trusty32" + br.vm.hostname = "ogBrowser" + # Comment out to disable synced folder. + #br.vm.synced_folder ".", "/vagrant", disabled: true + # Launch provisioning script. + br.vm.provision "shell", inline: SCRIPT + end + +end + diff --git a/installer/vagrant/Vagrantfile-devel-vbox b/installer/vagrant/Vagrantfile-devel-vbox new file mode 100644 index 00000000..c8eb022f --- /dev/null +++ b/installer/vagrant/Vagrantfile-devel-vbox @@ -0,0 +1,185 @@ +# Vagrantfile to install OpenGnsys 1.1 virtual environment using VirtualBox provider. + +VAGRANTFILE_API_VERSION = "2" +# VM provider: Oracle VM VirtualBox. +ENV['VAGRANT_DEFAULT_PROVIDER'] = "virtualbox" +# Language (accepted values: es_ES, ca_ES, en_GB). +LANGUAGE = "es_ES" +ENV['LC_ALL'] = LANGUAGE + ".UTF-8" +# Number of OpenGnsys clients (accepted values: from 2 to 9). +NCLIENTS = 4 +# Repository virtual disk: file and size (GB). +REPODISK = "ogRepo.vdi" +REPOSIZE = 50 +# Amount of memory for server and clients (MB) +SERVERMEM = 1024 # Minimum: 512 +CLIENTMEM = 512 # Minimum: 256 +# Prefixes for MAC and IP addresses. +MACPREFIX = "08:00:27:0E:65" +NETPREFIX = "192.168.2" +# OpenGnsys Server IP address. +SERVERIP = "#{NETPREFIX}.10" +# Local port to access OpenGnsys Server. +LOCALWEBPORT = 8443 + +# OpenGnsys Server provisioning script: prepare repo disk, install OpenGnsys, change default interface, configure DHCP server. +OGSERVERSCRIPT = <> /etc/fstab + mount -a +fi +# Install OpenGnsys and change server address. +wget -q https://opengnsys.es/svn/branches/version1.1/installer/opengnsys_installer.sh -O - | bash || exit $? +mv /opt/opengnsys/log/bash.log /opt/opengnsys/log/opengnsys_installer.log +echo y | /opt/opengnsys/bin/setserveraddr enp0s8 +# Insert DHCP data. +for ((i=#{NCLIENTS+10}; i>10; i--)); do + sed -i "/^}$/ i host pc${i} { hardware ethernet #{MACPREFIX}:${i}; fixed-address #{NETPREFIX}.${i}; }" /etc/dhcp/dhcpd.conf +done +service isc-dhcp-server restart +# Set language. +export LANG="#{LANGUAGE}.UTF-8" +echo "LANG=\"$LANG\"" > /etc/default/locale +echo "LANG=\"$LANG\"" >> /etc/environment +locale-gen --lang #{LANGUAGE} +sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\"${LANG%_*}\"/" /etc/default/keyboard +dpkg-reconfigure -fnoninteractive console-setup +# Comment out next lines for automatic data insertion. +#SQL="INSERT INTO aulas (nombreaula, idcentro, urlfoto, grupoid, ubicacion, puestos, modomul, ipmul, pormul, velmul, router, netmask, ntp, dns, proxy, modp2p, timep2p) VALUES ('Aula virtual', 1, 'aula.jpg', 0, 'Despliegue virtual con Vagrant.', 5, 2, '239.194.2.11', 9000, 70, '#{NETPREFIX}.1', '255.255.255.0', '', '', '', 'peer', 30); INSERT INTO ordenadores (nombreordenador, ip, mac, idaula, idrepositorio, idperfilhard, idmenu, idproautoexec, grupoid, router, mascara, arranque, netiface, netdriver, fotoord) VALUES" +#for ((i=11; i<=#{NCLIENTS+10}; i++)); do +# SQL="$SQL ('pc$i', '#{NETPREFIX}.$i', REPLACE('#{MACPREFIX}$i',':',''), 1, 1, 0, 0, 0, 0, '#{NETPREFIX}.1', '255.255.255.0', '00unknown', 'eth0', 'generic', 'fotoordenador.gif')," +#done +#mysql -u usuog -ppassusuog -D ogAdmBD -e "${SQL%,}" +#/opt/opengnsys/bin/setclientmode ogLiveAdmin pc11 PERM +#for ((i=12; i<=#{NCLIENTS+10}; i++)); do +# /opt/opengnsys/bin/setclientmode ogLive pc$i PERM +#done +# Comment out next lines to install new Angular-based web application (on early development). +#apt-get install -y git nodejs npm +#ln -fs nodejs /usr/bin/node +#npm install bower -g +#svn export https://opengnsys.es/svn/branches/version1.1-tickets/ogWebAdmin-ticket761/admin/WebConsole/angular /opt/opengnsys/www/angular +#cd /opt/opengnsys/www/angular +#chown -R vagrant.vagrant . +#su vagrant -c "bower install -F" +#sed -i 's!BASE_URL = .*$!BASE_URL = "https://localhost:#{LOCALWEBPORT}/opengnsys";!' ogWebAdmin/assets/js/config.constants.js +#### TEMPORAL PATCHES +#su vagrant -c "bower install angular-sanitize -F" +#su vagrant -c "bower install angular-translate-loader-static-files -F" +#su vagrant -c "bower install angular-ui-select -F" +#su vagrant -c "bower install bootstrap -F" +#su vagrant -c "bower install isteven-angular-multiselect -F" +#ln -s globunet-util.min.css ogWebAdmin/lib/globunet/dist/css/globunet-util.css +#cp -a ogWebAdmin/assets/i18n/es.json ogWebAdmin/assets/i18n/en.json +#sed -i 's/jm.bardallo/usuog/' ogWebAdmin/assets/js/controllers/login.controller.js +#sed -i "s/DirectoryIndex index.php/DirectoryIndex index.php index.html/" /etc/apache2/sites-enabled/opengnsys.conf +#service apache2 reload +echo "Notes:" +echo "- OpenGnsys Server URL: https://localhost:#{LOCALWEBPORT}/opengnsys/" +[ -d /opt/opengnsys/www/angular ] && echo "- Angular-based web URL: https://localhost:#{LOCALWEBPORT}/opengnsys/angular/ogWebAdmin/" +exit 0 +EOT + +# Client 1 OS provisioning script. +OGAGENTPKG = "ogagent_1.1.0_all.deb" +MODELSCRIPT = </dev/null +localectl set-locale LANG=$LANG +localectl set-keymap ${LANG%_*} +localectl set-x11-keymap ${LANG%_*} +# Update repositories. +dnf install -y http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm +# Install main dependencies. +dnf install -y gcc-c++ debhelper dpkg-dev pyqt4-devel rpm-build subversion samba-winbind wine.i686 mingw32-wine-gecko wine-mono cabextract xar +setsebool -P wine_mmap_zero_ignore=on mmap_low_allowed=on +# Install desktop (XFCE) and GUI utils. +dnf install -y @xfce-desktop-environment firefox VirtualBox-guest kmod-VirtualBox akmod-VirtualBox akmods +systemctl set-default graphical.target +sed -i '$d' /usr/lib/udev/rules.d/60-vboxguest.rules +akmods && systemctl restart systemd-modules-load.service +# Install ATOM editor by default (less disk space). +wget -q https://atom.io/download/rpm -O /tmp/atom.rpm && dnf install -y /tmp/atom.rpm && rm -f /tmp/atom.rpm +# Comment out next line if you prefer to install Eclipse IDE for Python (it needs more disk space). +#dnf install -y eclipse-pydev eclipse-nls-${LANG%_*} +# Download OGAgent environment installer. +svn export https://opengnsys.es/svn/trunk/installer/ogagent-devel-installer.sh /home/vagrant +# Instructions. +echo "Manual operations:" +echo "- Reboot VM or launch desktop: startxfce4 &" +echo "- Enlarge VM window." +echo "- To prepare OGAgent environment, execute: ./ogagent-devel-installer.sh" +echo "- If you use the default Atom IDE:" +echo " - Open a Project located in /home/vagrant/ogagent/src directory." +echo "- Only if you enable Eclipse IDE installation, you need to configure it before coding:" +echo " - Set Python interpreter on Preferences/PyDev/Interpreters/Python Interpreter." +echo " - Create a new PyDev Project located in /home/vagrant/ogagent/src directory." +EOT + +Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| + + # OpenGnsys boot-tools environment VM definition. + config.vm.define "ogAgent" do |ag| + ag.ssh.insert_key = false + # Specific VirtualBox configuration. + ag.vm.provider "virtualbox" do |vb| + # VM name, memory and CPUs. + vb.name = "ogAgent" + vb.memory = VMMEM + vb.cpus = VMCPUS + vb.gui = true + end + # VM base and host name. + ag.vm.box = "fedora/25-cloud-base" + ag.vm.hostname = "ogAgent" + # Comment to disable synced folder. + ag.vm.synced_folder ".", "/vagrant" + # Launch provisioning script. + ag.vm.provision "shell", inline: SCRIPT + end + +end + diff --git a/installer/vagrant/Vagrantfile-trunk-vbox b/installer/vagrant/Vagrantfile-trunk-vbox new file mode 100644 index 00000000..75dbcd11 --- /dev/null +++ b/installer/vagrant/Vagrantfile-trunk-vbox @@ -0,0 +1,164 @@ +# Vagrantfile to install OpenGnsys Trunk (v1.1.0) virtual environment using VirtualBox provider. + +VAGRANTFILE_API_VERSION = "2" +# VM provider: Oracle VM VirtualBox. +ENV['VAGRANT_DEFAULT_PROVIDER'] = "virtualbox" +# Language (accepted values: es_ES, ca_ES, en_GB). +LANGUAGE = "es_ES" +ENV['LC_ALL'] = LANGUAGE + ".UTF-8" +# Number of OpenGnsys clients (accepted values: from 2 to 9). +NCLIENTS = 4 +# Repository virtual disk: file and size (GB). +REPODISK = "ogRepo.vdi" +REPOSIZE = 50 +# Amount of memory for server and clients (MB) +SERVERMEM = 1024 # Minimum: 512 +CLIENTMEM = 512 # Minimum: 256 +# Prefixes for MAC and IP addresses. +MACPREFIX = "08:00:27:0E:65" +NETPREFIX = "192.168.2" +# OpenGnsys Server IP address. +SERVERIP = "#{NETPREFIX}.10" +# Local port to access OpenGnsys Server. +LOCALWEBPORT = 8443 + +# OpenGnsys Server provisioning script: prepare repo disk, install OpenGnsys, change default interface, configure DHCP server. +OGSERVERSCRIPT = <> /etc/fstab + mount -a +fi +# Install OpenGnsys and change server address. +wget -q https://opengnsys.es/svn/trunk/installer/opengnsys_installer.sh -O - | bash || exit $? +mv /opt/opengnsys/log/bash.log /opt/opengnsys/log/opengnsys_installer.log +echo y | /opt/opengnsys/bin/setserveraddr enp0s8 +# Insert DHCP data. +for ((i=#{NCLIENTS+10}; i>10; i--)); do + sed -i "/^}$/ i host pc${i} { hardware ethernet #{MACPREFIX}:${i}; fixed-address #{NETPREFIX}.${i}; }" /etc/dhcp/dhcpd.conf +done +service isc-dhcp-server restart +# Set language. +export LANG="#{LANGUAGE}.UTF-8" +echo "LANG=\"$LANG\"" > /etc/default/locale +echo "LANG=\"$LANG\"" >> /etc/environment +locale-gen --lang #{LANGUAGE} +sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\"${LANG%_*}\"/" /etc/default/keyboard +dpkg-reconfigure -fnoninteractive console-setup +# Comment out next lines for automatic data insertion. +#SQL="INSERT INTO aulas (nombreaula, idcentro, urlfoto, grupoid, ubicacion, puestos, modomul, ipmul, pormul, velmul, router, netmask, ntp, dns, proxy, modp2p, timep2p) VALUES ('Aula virtual', 1, 'aula.jpg', 0, 'Despliegue virtual con Vagrant.', 5, 2, '239.194.2.11', 9000, 70, '#{NETPREFIX}.1', '255.255.255.0', '', '', '', 'peer', 30); INSERT INTO ordenadores (nombreordenador, ip, mac, idaula, idrepositorio, idperfilhard, idmenu, idproautoexec, grupoid, router, mascara, arranque, netiface, netdriver, fotoord) VALUES" +#for ((i=11; i<=#{NCLIENTS+10}; i++)); do +# SQL="$SQL ('pc$i', '#{NETPREFIX}.$i', REPLACE('#{MACPREFIX}$i',':',''), 1, 1, 0, 0, 0, 0, '#{NETPREFIX}.1', '255.255.255.0', '00unknown', 'eth0', 'generic', 'fotoordenador.gif')," +#done +#mysql -u usuog -ppassusuog -D ogAdmBD -e "${SQL%,}" +#/opt/opengnsys/bin/setclientmode ogLiveAdmin pc11 PERM +#for ((i=12; i<=#{NCLIENTS+10}; i++)); do +# /opt/opengnsys/bin/setclientmode ogLive pc$i PERM +#done +echo "Notes:" +echo "- OpenGnsys Server URL: https://localhost:#{LOCALWEBPORT}/opengnsys/" +exit 0 +EOT + +# Client 1 OS provisioning script. +OGAGENTPKG = "ogagent_1.1.0_all.deb" +MODELSCRIPT = </dev/null)" == '["directory","images","ous"]' ]; then + # Common image. + if [ -z "$OUNAME" ]; then + # Check if the image is defined into JSON file. + n=$(jq ".images | length" $INFOFILE) + for ((i=0; i $INFOFILE +{"directory":"$IMAGESDIR","images":[$JSON],"ous":[]} +EOT + else + cat << EOT | jq . > $INFOFILE +{"directory":"$IMAGESDIR","images":[],"ous":[{"subdir":"$OUNAME","images":[$JSON]}]} +EOT + fi + fi +} + +# Show an error message. +function raiseError() { + case "$1" in + usage) + echo "$PROG: Usage error: Type \"$PROG help\"" >&2 + exit 1 ;; + notfound) + echo "$PROG: Resource not found: $2" >&2 + exit 2 ;; + access) + echo "$PROG: Access error: $2" >&2 + exit 3 ;; + *) + echo "$PROG: Unknown error" >&2 + exit 1 ;; + esac +} + +# Command functions. + +# Show help message. +function help() { + cat << EOT +$PROG: maintain the repository information. +Usage: $PROG +EOT +} + +# Check for file-based images to update the repository configuration file. +function checkfiles() { + local IMAGES IMG INFO DATA + + # File-stored images. + IMAGES=$(find $IMAGESDIR -maxdepth 2 -type f \( -name "*.img" -o -name "*.dsk" \) -print) + for IMG in $IMAGES; do + # Skip locked images. + [ -e "$IMG.lock" ] && continue + # Retrieve image creation data and delete temporary file. + INFO="$IMG.info" + [ -e "$INFO" -a "$INFO" -ot "$IMG" ] && rm -f "$INFO" && echo "Warning: Deleted outdated file $INFO" + DATA="" + [ -r "$INFO" ] && DATA=$(cat "$INFO") + # Add data to configuration file (name, type and data) and remove image info file. + IMG=${IMG#$IMAGESDIR/} + addToJson "${IMG%.*}" "${IMG##*.}" "$DATA" && rm -f "$INFO" + done +} + +# Check for directory-based images to update the repository configuration file. +function checkdirs() { + local IMAGES IMG INFO DATA + + # Directory-based images. + IMAGES=$(find $IMAGESDIR -maxdepth 3 -type f -name ogimg.info -print) + for INFO in $IMAGES; do + IMG="$(dirname "${INFO#$IMAGESDIR/}")" + # Skip repository root directory and locked images. + [ "$IMG" == "$IMAGESDIR" -o -e "$IMG.lock" ] && continue + DATA=$(awk -F= '$1=="# fstype" {fs=$2} $1=="# sizedata" {sz=$2} END {printf "rsync::%s:%s:",fs,sz}' "$INFO") + # Add data to configuration file (name, type and data). + addToJson "$IMG" "dir" "$DATA" + done +} + +# Check if images are removed to update the repository configuration file. +function checkremoved() { + local IMG TYPE OU i j n m + [ ! -w "$INFOFILE" ] && raiseError access "$INFOFILE" + + # Check if global images are defined into JSON file. + n=$(jq ".images | length" $INFOFILE) + for ((i=0; i/dev/null) || raiseError notfound "Need to install \"jq\"." +which sponge &>/dev/null || raiseError notfound "Need to install \"moreutils\"." + +checkfiles +checkdirs +checkremoved + diff --git a/repoman/bin/createfileimage b/repoman/bin/createfileimage new file mode 100755 index 00000000..4fcd7d9d --- /dev/null +++ b/repoman/bin/createfileimage @@ -0,0 +1,65 @@ +#!/bin/bash +#/** +# createtimage +#@brief Crea o redimensiona el archivo de la imagen. +#@param 1 imagen +#@param 2 extension [ img|diff ] +#@param 3 tamaño de la imagen en kb. +#@return +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@exception OG_ERR_DONTSYNC_IMAGE #71 Imagen no sincronizable (es monolitica) +#@version 1.0 - Montar imagen sincronizable +#@author Irina Gomez +#@date 2013-05-23 +#*/ ## +BASEDIR=/opt/opengnsys +REPODIR="$BASEDIR/images" +REPOLOG=$BASEDIR/log/ogAdmRepo.log +# Cargamos los mensajes en el idioma del sistema. +# Comprobamos que el fichero de idioma existe. Si no "es_ES" por defecto. +ls $BASEDIR/client/etc/lang.$LANG.conf &>/dev/null +[ $? -eq 0 ] || LANG="es_ES" +source $BASEDIR/client/etc/lang.$LANG.conf + +PROG="$(basename $0)" +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + echo -e " $PROG: $MSG_HELP_ogCreateFileImage \n" \ + "$MSG_FORMAT: $PROG image [ img|diff ] size_kb \n" \ + "base -> $PROG Windows7 img 3900000 \n" \ + "diff -> $PROG Ubuntu12 diff 450000" + exit 0 +fi + +[ $# -lt 3 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ] size_Kb " && exit 1 + +if [ "$USER" != "root" ]; then + echo "$PROG: Error: solo ejecutable por root" >&2 + exit 1 +fi + +IMGEXT="$2" + +# Si existe imagen, Comprobamos que no esta bloqueada y que es sincronizable +IMGFILE="$REPODIR/$1.$IMGEXT" +if [ -f $IMGFILE ]; then + [ -f $IMGFILE.lock ] && echo "$PROG: Error: $MSG_ERR_LOCKED $1 $IMGEXT" && exit 4 + + + if ! file $IMGFILE | grep -i -e " BTRFS Filesystem " -e " ext4 filesystem " >/dev/null ; then + echo "$PROG: Error: $MSG_ERR_DONTSYNC_IMAGE $1 $2" + exit 71 + fi +fi + +touch $IMGFILE.lock + +# El tamaño minimo de la imagen es 300000 para poder formatear en fs btrfs. +SIZEREQUIRED=$3 +[ $SIZEREQUIRED -lt 300000 ] && SIZEREQUIRED=300000 + +echo CREATE_IMAGE "$1" $IMGEXT $SIZEREQUIRED +echo -ne CREATE_IMAGE "$1" $IMGEXT $SIZEREQUIRED| /opt/opengnsys/sbin/ogAdmRepoAux || exit $? +echo "Los resultado se registran en $REPOLOG. " + +rm $IMGFILE.lock diff --git a/repoman/bin/deleteimage b/repoman/bin/deleteimage index 7741177f..2da477e4 100755 --- a/repoman/bin/deleteimage +++ b/repoman/bin/deleteimage @@ -1,10 +1,11 @@ #!/bin/bash -# deleteimage [ -b | -r ] str_image +# deleteimage [ -b | -r ] [ str_image | str_dir/str_image ] #@file deleteimage #@brief Borra del repositorio los ficheros de una imagen. #@param -b Elimina también la copia de seguridad de la imagen (opcional). #@param -r Recupera la copia de seguridad de la imagen (opcional). -#@param str_image Nombre canónico de la imagen, sin extensión. +#@param str_image Nombre canónico de la imagen, sin extensión. Permite directorio. +#@exception 1 Error de formato #@version 1.0 - Versión inicial. #@date 2012-10-14 #@author Ramón Gómez, ETSII Univ. Sevilla @@ -19,7 +20,6 @@ #@author Irina Gómez, ETSII Univ. Sevilla #*/ ## - PROG=$(basename $0) OPENGNSYS=${OPENGNSYS:-"/opt/opengnsys"} OGIMG=$OPENGNSYS/images @@ -31,10 +31,11 @@ DIFFEXT="diff" if [ "$*" == "help" ]; then cat << EOT $PROG: Borra los ficheros de una imagen del repositorio. -Formato: $PROG [ -b | -r ] str_image +Formato: $PROG [ -b | -r ] [ str_image | str_dir/str_image ] -b Elimina también la copia de seguridad de la imagen. -r Recupera la copia de seguridad de la imagen. Ejemplo: $PROG imagen1 + $PROG -r dir2/imagen2 EOT exit 0 fi @@ -49,17 +50,17 @@ while getopts br OPTION; do done [ -n "$DELETEBACKUP" ] && [ -n "$RECOVERBACKUP" ] && ERR=1 if [ $# != 1 -o -n "$ERR" ]; then - echo "$PROG Error: Formato: $PROG [ -b | -r ] str_image" + echo "$PROG Error: Formato: $PROG [ -b | -r ] [ str_image | str_dir/str_image ]" exit 1 fi -# Eliminar ficheros de imagen monolítica o sincronizada básica. +# Eliminar ficheros de imagen monolítica o sincronizada. for IMG in "$OGIMG/$1.$IMGEXT" "$OGIMG/$1.$IMGEXT.$DIFFEXT" "$OGIMG/$1"; do # Borro la imagen si existe if [ -r $IMG ] ; then IMGPATH=$IMG echo "Borrando imagen $IMGPATH" - rm -f $IMGPATH{,.sum,.full.sum,.torrent} + rm -f $IMGPATH{,.sum,.full.sum,.torrent} break fi # Compruebo si existe copia de seguridad @@ -67,7 +68,6 @@ for IMG in "$OGIMG/$1.$IMGEXT" "$OGIMG/$1.$IMGEXT.$DIFFEXT" "$OGIMG/$1"; do done [ "_${IMGPATH}_" == "__" ] && IMGPATH=$OLDPATH - # Recuperar copia de seguridad de la imagen. if [ -n "$RECOVERBACKUP" ]; then [ -e $IMGPATH.$BAKEXT ] && echo "Recuperando copia $IMGPATH.$BAKEXT" @@ -79,7 +79,6 @@ fi # Borrar copia de seguridad de la imagen. if [ -n "$DELETEBACKUP" ]; then - [ -e $IMGPATH ] && echo "Eliminando copia $IMGPATH.$BAKEXT" + [ -e $IMGPATH.$BAKEXT ] && echo "Eliminando copia $IMGPATH.$BAKEXT" rm -f $IMGPATH.$BAKEXT && rm -f $IMGPATH.{sum,full.sum,torrent}.$BAKEXT fi - diff --git a/repoman/bin/deletepreimage b/repoman/bin/deletepreimage index 39077483..19d6f2c7 100755 --- a/repoman/bin/deletepreimage +++ b/repoman/bin/deletepreimage @@ -1,9 +1,10 @@ #!/bin/bash -# Eliminar las imagenees del repositiro seg�raca de la consola web .img -#Version 0.3 Ejecuci�n desde cron cada minuto. +# Eliminar las imágenees del repositiro seg�raca de la consola web. +#Version 0.3 Ejecución desde cron cada minuto. #echo "* * * * * root /opt/opengnsys/bin/image-delete" > /etc/cron.d/imagedelete +# Version 1.1.0 - Llamar a script "checkrepo". -# Comprobar si el proceso ya est� en ejecuci�n.on. +# Comprobar si el proceso ya está en ejecución. PROG=$(basename $0) [ "$(pgrep "$PROG")" != "$$" ] && exit @@ -14,49 +15,40 @@ OGIMG="$OPENGNSYS/images" REPOCFG="$OPENGNSYS/etc/ogAdmRepo.cfg" LOGFILE="$OPENGNSYS/log/$PROG.log" -# Error si no est� bien configurado el repositorio de im�genes.nes. +# Error si no está bien configurado el repositorio de imágenes. [ -d $OGIMG -a -f $REPOCFG ] || exit 1 -# Procesar ficheros de im�genes.s. +# Procesar ficheros de imágenes. trap 'echo "`date` : Proceso interrumpido" >> $LOGFILE; exit ' 1 2 3 6 9 15 -#TODO en LOCAL: si existe algun fichero *.delete lo movemos al repositorio -ls /opt/opengnsys/www/tmp/*.delete &>/dev/null || exit -#[ -f /opt/opengnsys/www/tmp/*.delete ] && -mv /opt/opengnsys/www/tmp/*.* /opt/opengnsys/images/ +#TODO en LOCAL: si existe algún fichero *.delete lo movemos al repositorio +ls $OPENGNSYS/www/tmp/*.delete &>/dev/null || (checkrepo; exit) +mv $OPENGNSYS/www/tmp/*.* $OGIMG #TODO: iniciar blucle siempre y cuando haya algun delete ls /opt/opengnsys/images/*.delete &>/dev/null || exit +for IMG in `ls $OGIMG/*.delete`; do + # Obtenemos el nombre de la imagen + DELETEIMAGE=$(echo ${IMG%%.*} | awk -F"$OGIMG/" '{print $2}') -for IMG in `ls /opt/opengnsys/images/*.delete`; do - ## Obtenemos el nombre de la imagen - DELETEIMAGE=$(echo $IMG | awk -F"." '{print $1}' | awk -F"/opt/opengnsys/images/" '{print $2}') + # Borramos marca .delete para que el próximo cron no trabaje sobre este conjunto. + [ -f $IMG ] && rm $IMG - # Borramos marca .delete para que el proximo cron no trabaje sobre este conjunto. - [ -f $IMG ] && rm $IMG - - ## Comprobamos si es un Directorio .delete - DELETEdir=$(echo $IMG | awk -F"." '{print $2}') ## .delete + ## Comprobamos si es una imagen de backup DELETEant=$(echo $IMG | awk -F"." '{print $3}') ## .ant - DELETEdiff=$(echo $IMG | awk -F"." '{print $3}') ## .diff - ## Si NO es ninguno es un img - ## se llama al escript de borrado de imagen. - ## Si es un Directorio Borramos - if [[ $DELETEdir == "delete" ]]; then - /opt/opengnsys/bin/deleteimage $DELETEIMAGE - - # Si es un Imagen Backup Borramos - elif [[ $DELETEant == "ant" ]]; then - DELETEIMAGE=$DELETEIMAGE".ant" - /opt/opengnsys/bin/deleteimage $DELETEIMAGE - - # Si es un Imagen diff Borramos - elif [[ $DELETEdiff == "diff" ]]; then - /opt/opengnsys/bin/deleteimage $DELETEIMAGE - - # Si no es una de las anteriores lo que queda es img - else - /opt/opengnsys/bin/deleteimage $DELETEIMAGE + ## Si la imagen es un backup se añade la extensión ant + if [[ $DELETEant == "ant" ]]; then + DELETEIMAGE=$DELETEIMAGE".ant" fi -done \ No newline at end of file + ## si directorio:imagen cambiamos : por / + DELETEIMAGE=$(echo $DELETEIMAGE|tr : /) + + ## se llama al escript de borrado de imagen. + deleteimage $DELETEIMAGE + +done + +# Actualizar información del repositorio. +checkrepo + diff --git a/repoman/bin/mountimage b/repoman/bin/mountimage new file mode 100755 index 00000000..fa059fd7 --- /dev/null +++ b/repoman/bin/mountimage @@ -0,0 +1,71 @@ +#!/bin/bash +#/** +# mountimage +#@brief Monta imagen sincronizable en el repositorio con permisos de escritura +#@param 1 imagen +#@param 2 extension [ img|diff ] opcional, por defecto img +#@return Directorio de montaje de la imagen. +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado +#@exception OG_ERR_DONTSYNC_IMAGE #71 Imagen no sincronizable (es monolitica) +#@exception OG_ERR_DONTMOUNT_IMAGE # 70 Error al montar una imagen sincronizada +#@version 1.0 - Montar imagen sincronizable +#@author Irina Gomez +#@date 2013-05-23 +#*/ ## +BASEDIR=/opt/opengnsys +REPODIR="$BASEDIR/images" +# Cargamos los mensajes en el idioma del sistema. +# Comprobamos que el fichero de idioma existe. Si no "es_ES" por defecto. +ls $BASEDIR/client/etc/lang.$LANG.conf &>/dev/null +[ $? -eq 0 ] || LANG="es_ES" +source $BASEDIR/client/etc/lang.$LANG.conf + + +PROG="$(basename $0)" +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + echo -e " $PROG: $MSG_HELP_ogMountImage \n" \ + "$MSG_FORMAT: $PROG nombre_image [ img|diff ] \n" \ + "base -> $PROG Windows7 \n" \ + "diff -> $PROG Ubuntu12 diff" + exit 0 +fi + +[ $# -lt 1 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ]" && exit 1 + +if [ "$USER" != "root" ]; then + echo "$PROG: Error: solo ejecutable por root" >&2 + exit 1 +fi + +[ "$2" == "" -o "$2" == "img" ] && IMGEXT="img" || IMGEXT="img.diff" + +# Comprobamos que existe imagen +IMGFILE="$REPODIR/$1.$IMGEXT" +[ ! -f $IMGFILE ] && echo "$PROG: Error: $MSG_ERR_NOTFOUND $1 $IMGEXT" && exit 2 + + +# Comprobar que la imagen es sincronizable +file $IMGFILE | grep -i -e " BTRFS Filesystem " >/dev/null && IMGFS=BTRFS +file $IMGFILE | grep -i -e " ext4 filesystem " >/dev/null && IMGFS=EXT4 +if [ "$IMGFS" != "BTRFS" -a "$IMGFS" != "EXT4" ] ; then + echo "$PROG: Error: $MSG_ERR_DONTSYNC_IMAGE $1 $2" + exit 71 +fi + +MOUNTDIR="$REPODIR/mount/$1" +[ "$IMGEXT" == "img.diff" ] && MOUNTDIR="$MOUNTDIR.${IMGEXT#*\.}" +mkdir -p "$MOUNTDIR" + +# Comprobamos si la imagen esta montada y si es así nos salimos. +df |grep "$MOUNTDIR$" 2>&1 >/dev/null && echo "$MOUNTDIR" && exit 0 + +if [ "$IMGFS" == "EXT4" ] ; then + mount -t ext4 "$IMGFILE" "$MOUNTDIR" +else + mount -o compress=lzo "$IMGFILE" "$MOUNTDIR" +fi +[ $? -eq 0 ] || ( echo "$MSG_ERR_DONTMOUNT_IMAGE $1 $2" ; exit 70) +echo "$MOUNTDIR" + diff --git a/repoman/bin/opengnsys.cron b/repoman/bin/opengnsys.cron index be5a0508..78f01db5 100755 --- a/repoman/bin/opengnsys.cron +++ b/repoman/bin/opengnsys.cron @@ -1,5 +1,5 @@ #!/bin/bash -# opengnsys.cron - Script para comprobar si los servicios de OpenGnSys están levantados +# opengnsys.cron - Script para comprobar si los servicios de OpenGnsys están levantados # e iniciarlos automáticamente. # Nota: este script debe ser lanzado por Cron cada minuto. @@ -16,7 +16,7 @@ typeset -i OGCPU # % uso CPU # Salir si no se debe ejecutar la revisión en el cron. [ "$RUN_CRONJOB" == "no" ] && exit -# Comprobar si está activo el servidor OpenGnSys. +# Comprobar si está activo el servidor OpenGnsys. if [ "$RUN_OGADMSERVER" == "yes" ]; then # Parar procesos ogAdmServer si consume más de 90% de CPU. OGPID=$(pgrep ogAdmServer) diff --git a/repoman/bin/partclone2sync b/repoman/bin/partclone2sync new file mode 100755 index 00000000..0b66fa55 --- /dev/null +++ b/repoman/bin/partclone2sync @@ -0,0 +1,178 @@ +#!/bin/bash +#/** +# partclone2sync +#@brief Convierte imagen de partclone en imagen sincronizable. +#@param 1 imagen partclone. +#@param 2 imagen sincronizable. +#@param 3 tipo de sincronización y formato de la imagen SYNC1 (directorio) y SYNC2 (fichero) +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado +#@exception OG_ERR_LOCKED # 4 Imagen de partclone bloqueada. +#@exception OG_ERR_IMAGE # 5 Error al crear la imagen. +#@exception OG_CACHESIZE # 16 No hay espacio suficiente en el disco. +#@note Necesita tener instalado partclone-utils y lzop +#@version 1.0 - +#@author Irina Gomez +#@date 2014-01-22 +#*/ ## +trap "onexit \"$1\" \"$2\" $3" 0 5 16 9 15 + +function onexit() { + local exit_status=$? + # Desmontamos el cliente de opengnsys y la imagen temporal. + umount $OGCLIENTDIR/ogclientmount $AUXDIR + rm -rf $IMGINFO $FILEHEAD $TMPLOG + + # Borramos los ficheros de bloqueo de las imagenes nuevas. + rm -rf $RSYNCIMG.img.lock $AUXIMG.lock + # Borramos los ficheros de bloqueo dela imagen de partclone si no estaba bloqueada. + [ $exit_status -eq 4 ] || rm -rf $PARTCLONEIMG.lock + + # Borramos las imagenes y directorios temporales. + rm $AUXIMG + rmdir $AUXDIR $OGCLIENTDIR/ogclientmount + + exit $exit_status +} + +TIME1=$SECONDS + +BASEDIR=/opt/opengnsys +REPODIR="$BASEDIR/images" +BINDIR="$BASEDIR/bin" +PROG="$(basename $0)" +# Cargamos los mensajes en el idioma del sistema. +# Comprobamos que el fichero de idioma existe. Si no "es_ES" por defecto. +ls $BASEDIR/client/etc/lang.$LANG.conf &>/dev/null +[ $? -eq 0 ] || LANG="es_ES" + +source $BASEDIR/client/etc/lang.$LANG.conf + +# Sistema de fichero de la imagen según kernel, menor que 3.7 EXT4. comparamos revision +[ $(uname -r|cut -d. -f2) -lt 7 ] && IMGFS="EXT4" || IMGFS="BTRFS" + +# Mostrar ayuda: Si se solicita, si faltan parametros o $3 no es SYNC1 o SYNC2. +if [ "$*" == "help" -o $# -lt 3 ] && ! [[ "$3" == SYNC[1,2] ]]; then + echo -e "$PROG: $MSG_HELP_partclone2sync \n" \ + "$MSG_FORMAT: $PROG image_partclone image_rsync [ SYNC1 | SYNC2 ] \n" \ + " $PROG Windows7 Windows72013 SYNC1 " + exit 0 +fi + +if [ "$USER" != "root" ]; then + echo "$PROG: Error: solo ejecutable por root" >&2 + exit 1 +fi + + +PARTCLONEIMG="$REPODIR/$1.img" +RSYNCIMG="$REPODIR/$2" +AUXIMG="$REPODIR/$1.tmp.img" +AUXDIR="/tmp/partclone2rsync$$" +TYPE="$3" +TMPLOG=/tmp/rsync$$.sal + +# Comprobamos que exista la imagen. +! [ -f $PARTCLONEIMG ] && echo "$MSG_ERR_NOTFOUND: $1" && exit 2 + +# Comprobamos que la imagen no este bloqueada. +[ -f $PARTCLONEIMG.lock ] && echo "$MSG_ERR_LOCKED: $1" && exit 4 + +# Usamos el partclone del ogclient. +OGCLIENTDIR=$BASEDIR/tftpboot/ogclient +[ -d $OGCLIENTDIR/ogclientmount ] || mkdir $OGCLIENTDIR/ogclientmount +mount $OGCLIENTDIR/ogclient.sqfs $OGCLIENTDIR/ogclientmount +PATHPARTCLONE=$OGCLIENTDIR/ogclientmount/usr/sbin + +# Creamos fichero de bloqueo +touch $PARTCLONEIMG.lock $AUXIMG.lock + + +# Datos imagen. +echo [10] Obtenemos datos del partclone. +FILEHEAD=/tmp/$(basename $PARTCLONEIMG).infohead +COMPRESSOR=`file $PARTCLONEIMG | awk '{print $2}'` +$COMPRESSOR -dc $PARTCLONEIMG 2>/dev/null | head > $FILEHEAD +PARTCLONEINFO=$(LC_ALL=C partclone.info $FILEHEAD 2>&1) +if `echo $PARTCLONEINFO | grep size > /dev/null` +then + FS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($8);}') + echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024 + IMGSIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{gsub(/\: /,"\n"); printf "%d\n", $11*FACTOR;}') +else + echo "Error: partclone.info no detecta la imagen" + exit 5 +fi +[ "$FS" == "NTFS" ] && echo "Error: Todavia no podemos convertir imagenes de Windows" && exit 6 + +# Calculamos el espacio disponible en la particion de opengnsys. +echo -n "[20]$MSG_SCRIPTS_CREATE_SIZE " +for DIR in "/" "/opt" "/opt/opengnsys" "/opt/opengnsys/images" +do + AUXSIZE=$(df|grep $DIR$|awk '{print $3}') + [ "$AUXSIZE" != "" ] && PARTSIZE=$AUXSIZE +done +let REQUIRESIZE=2*$IMGSIZE +if [ $PARTSIZE -lt $REQUIRESIZE ]; then + echo "No hay espacio suficiente para descomprimir y crear la imagen: $REQUIRESIZE." + exit 16 +fi +echo "$REQUIRESIZE $PARTSIZE" + +# Descomprimimos la imagen de partclone. +echo [30] Descomprimimos la imagen de partclone. +$COMPRESSOR -dc $PARTCLONEIMG | $PATHPARTCLONE/partclone.restore -C -s - -O $AUXIMG + +TIME2=$[SECONDS-TIME1] +echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME2/60]m $[TIME2%60]s" + +# Montamos la imagen: +mkdir -p $AUXDIR +mount $AUXIMG $AUXDIR + +# Sincronizamos de la imagen del partclone a la del rsync. +echo "[60] Sincronizamos desde la imagen de partclone a la de rsync." +if [ "$TYPE" == "SYNC1" ]; then + mkdir -p $RSYNCIMG + echo " * Log temporal en: $TMPLOG" + echo rsync -aHAX $AUXDIR/ $RSYNCIMG --- log: $TMPLOG + rsync -aHAXv $AUXDIR/ $RSYNCIMG >> $TMPLOG +TIME3=$[SECONDS-TIME2] +echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME3/60]m $[TIME3%60]s" +else + IMGINFO="/tmp/ogimg.info$$" + IMGDIR="$REPODIR/mount/$(basename $RSYNCIMG)" + # Calculamos el tamaño de la imagen + SIZE=$(df -k|awk -v P="$AUXDIR" '{if ($6==P) print $3}') + # Creo fichero de informacion de la imagen + echo "#$FSIMG:LZO:$FS:$SIZE" > $IMGINFO + # Factor de compresion de la imagen + [ "$FS" == "NTFS" ] && ZFACTOR=120 || ZFACTOR=110 + [ "$FSIMG" == "BTRFS" ] && let ZFACTOR=$ZFACTOR-30 + let SIZE=$SIZE*$ZFACTOR/100 + + # Creamos el fichero de la imagen vacio (queda montado) + echo " * $MSG_HELP_ogCreateFileImage" + $BINDIR/createfileimage $(basename $RSYNCIMG) img $SIZE || exit 5 + touch $RSYNCIMG.img.lock + TIME3=$[SECONDS-TIME2] + echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME3/60]m $[TIME3%60]s" + + # Sincronizo las imagenes antigua y nueva. + echo " * Sincroniza las imagenes antigua y nueva. log temporal en: $TMPLOG" + echo rsync -aHAX $AUXDIR/ $IMGDIR + rsync -aHAXv $AUXDIR/ $IMGDIR >> $TMPLOG + TIME4=$[SECONDS-TIME3] + echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME4/60]m $[TIME4%60]s" + # copiamos el fichero de informacion dentro de la imagen. + mv $IMGINFO $IMGDIR/ogimg.info + # Desmontamos la imagen y la reducimos al minimo. + $BINDIR/unmountimage $(basename $RSYNCIMG) img + echo " * $MSG_HELP_ogReduceImage." + rm $RSYNCIMG.img.lock + $BINDIR/reduceimage $(basename $RSYNCIMG) img + +fi + +TIME=$[SECONDS-TIME1] +echo " $MSG_SCRIPTS_END: $MSG_SCRIPTS_TIME_TOTAL: $[TIME/60]m $[TIME%60]s" diff --git a/repoman/bin/reduceimage b/repoman/bin/reduceimage new file mode 100755 index 00000000..c83f2d50 --- /dev/null +++ b/repoman/bin/reduceimage @@ -0,0 +1,58 @@ +#!/bin/bash +#/** +# reduceimage +#@brief Reduce el archivo de la imagen a tamaño datos + 500M +#@param 1 imagen +#@param 2 extension [ img|diff ] opcional, por defecto img +#@return +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado +#@exception OG_ERR_LOCKED # 4 Partición o fichero bloqueado +#@exception OG_ERR_DONTSYNC_IMAGE #71 Imagen no sincronizable (es monolitica) +#@version 1.0 - Reducir tamaño imagen sincronizable +#@author Irina Gomez +#@date 2013-05-23 +#*/ ## +BASEDIR=/opt/opengnsys +REPODIR="$BASEDIR/images" +REPOLOG=$BASEDIR/log/ogAdmRepo.log +# Cargamos los mensajes en el idioma del sistema. +# Comprobamos que el fichero de idioma existe. Si no "es_ES" por defecto. +ls $BASEDIR/client/etc/lang.$LANG.conf &>/dev/null +[ $? -eq 0 ] || LANG="es_ES" +source $BASEDIR/client/etc/lang.$LANG.conf + +PROG="$(basename $0)" +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + echo -e " $PROG: $MSG_HELP_ogReduceImage \n" \ + "$MSG_FORMAT: $PROG nombre_image [ img|diff ] \n" \ + "base -> $PROG Windows7 \n" \ + "diff -> $PROG Ubuntu12 diff" + exit 0 +fi + +[ $# -lt 1 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ]" && exit 1 + +if [ "$USER" != "root" ]; then + echo "$PROG: Error: solo ejecutable por root" >&2 + exit 1 +fi + +[ "$2" == "" -o "$2" == "img" ] && IMGEXT="img" || IMGEXT="img.diff" +# Comprobamos que existe imagen y que no este bloqueada +IMGFILE="$REPODIR/$1.$IMGEXT" +[ ! -f $IMGFILE ] && echo "$PROG: Error: $MSG_ERR_NOTFOUND $1 $IMGEXT" && exit 2 +[ -f $IMGFILE.lock ] && echo "$PROG: Error: $MSG_ERR_LOCKED $1 $IMGEXT" && exit 4 + +# Comprobar que la imagen es sincronizable +if ! file $IMGFILE | grep -i -e " BTRFS Filesystem " -e " ext4 filesystem " >/dev/null ; then + echo "$PROG: Error: $MSG_ERR_DONTSYNC_IMAGE $1 $2" + exit 71 +fi + +touch $IMGFILE.lock +echo -ne REDUCE_IMAGE "$1" ${IMGEXT#*\.} | /opt/opengnsys/sbin/ogAdmRepoAux +echo "Los resultado se registran en $REPOLOG. " + +rm $IMGFILE.lock diff --git a/repoman/bin/torrent-creator b/repoman/bin/torrent-creator index 1ede98c5..958683ed 100755 --- a/repoman/bin/torrent-creator +++ b/repoman/bin/torrent-creator @@ -25,7 +25,7 @@ pushd $OGIMG >/dev/null # Procesar ficheros de imágenes. trap 'echo "`date` : Proceso interrumpido" >> $LOGFILE; exit ' 1 2 3 6 9 15 -for IMG in *.{img,pgz,diff}; do +for IMG in *.{img,pgz,diff,dsk} */*.{img,pgz,diff,dsk} ; do # Saltar al siguiente si la imagen está bloqueada o si no existe el fichero. LOCKFILE="$IMG.lock" if [ -f "$LOCKFILE" -o ! -f "$IMG" ]; then @@ -62,6 +62,6 @@ for IMG in *.{img,pgz,diff}; do # Modificación realizada en la corrección temporal de la incidencia #535 break done - + popd >/dev/null diff --git a/repoman/bin/unmountimage b/repoman/bin/unmountimage new file mode 100755 index 00000000..031ae9ee --- /dev/null +++ b/repoman/bin/unmountimage @@ -0,0 +1,52 @@ +#!/bin/bash +#/** +# unmountimage +#@brief Desmonta imagen sincronizable +#@param 1 imagen +#@param 2 extension [ img|diff ] opcional, por defecto img +#@return +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@version 1.0 - Desmontar imagen sincronizable +#@author Irina Gomez +#@date 2013-05-23 +#*/ ## +BASEDIR=/opt/opengnsys +REPODIR="$BASEDIR/images" +REPOLOG=$BASEDIR/log/ogAdmRepo.log +# Cargamos los mensajes en el idioma del sistema. +# Comprobamos que el fichero de idioma existe. Si no "es_ES" por defecto. +ls $BASEDIR/client/etc/lang.$LANG.conf &>/dev/null +[ $? -eq 0 ] || LANG="es_ES" + +source $BASEDIR/client/etc/lang.$LANG.conf + +PROG="$(basename $0)" +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + echo -e " $PROG: $MSG_HELP_ogUnmountImage \n" \ + "$MSG_FORMAT: $PROG nombre_image [ img|diff ] \n" \ + "base -> $PROG Windows7 \n" \ + "diff -> $PROG Ubuntu12 diff" + exit 0 +fi + +[ $# -lt 1 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ]" && exit 1 + +if [ "$USER" != "root" ]; then + echo "$PROG: Error: solo ejecutable por root" >&2 + exit 1 +fi + +# Comprobamos que imagen la imagen esta montada +MOUNTDIR="$REPODIR/mount/$1" +if [ "$2" == "diff" ]; then + IMGEXT="diff" + MOUNTDIR="$MOUNTDIR.diff" +else + IMGEXT="img" +fi +# Si la imaen no está montada me salgo +df |grep "$MOUNTDIR$" 2>&1 >/dev/null || exit 0 + +echo -ne UMOUNT_IMAGE "$1" $IMGEXT | /opt/opengnsys/sbin/ogAdmRepoAux +echo "Los resultado se registran en $REPOLOG. " diff --git a/server/README.es.txt b/server/README.es.txt index 47fc9601..1535cde3 100644 --- a/server/README.es.txt +++ b/server/README.es.txt @@ -1,11 +1,12 @@ -OpenGnSys Server Manager RREADME +OpenGnsys Server Manager RREADME =================================== -Este directorio contiene la estructura de datos del servidor central de OpenGnSys. +Este directorio contiene la estructura de datos del servidor central de OpenGnsys. - bin binarios y scripts de gestión del servidor. - etc ficheros o plantillas de configuración del servidor. +- lib librerías y funciones adicionales para el servidor. - tftpboot plantillas de configuración del servicio de arranque remoto. diff --git a/server/bin/checkperms b/server/bin/checkperms index f2ed84a0..0d80183c 100755 --- a/server/bin/checkperms +++ b/server/bin/checkperms @@ -2,7 +2,7 @@ # checkperms: Comprueba que los permisos de los ficheros sean correctos. # Nota: Las siguientes variables de entorno pueden usarse para retocar los # valores por defecto: -# - OPENGNSYS_USER - usuario de OpenGnSys. +# - OPENGNSYS_USER - usuario de OpenGnsys. # - OPENGNSYS_DIR - directorio de instalación. # - APACHE_USER - usuario de Apache. # - APACHE_GROUP - grupo de Apache. @@ -14,10 +14,10 @@ # Variables. OPENGNSYS_USER=${OPENGNSYS_USER:-"opengnsys"} # Usuario del cliente para acceso remoto -OPENGNSYS_DIR=${OPENGNSYS_DIR:-/opt/opengnsys} # Directorio de instalación de OpenGnSys +OPENGNSYS_DIR=${OPENGNSYS_DIR:-/opt/opengnsys} # Directorio de instalación de OpenGnsys APACHE_USER=${APACHE_USER:-"www-data"} # Usuario de ejecución de Apache APACHE_GROUP=${APACHE_GROUP:-"www-data"} # Grupo de ejecución de Apache -PROG=$(basename $0) +PROG=$(basename "$0") # Control de errores. if [ "$USER" != "root" ]; then @@ -25,11 +25,11 @@ if [ "$USER" != "root" ]; then exit 1 fi if [ "$OPENGNSYS_USER" == "root" -o -z "$(getent passwd "$OPENGNSYS_USER" 2>/dev/null)" ]; then - echo "$PROG: Error: el usuario de OpenGnSys debe existir y no ser root (OPENGNSYS_USER=\"$OPENGNSYS_USER\")" >&2 + echo "$PROG: Error: el usuario de OpenGnsys debe existir y no ser root (OPENGNSYS_USER=\"$OPENGNSYS_USER\")" >&2 exit 1 fi if [ ! -d "$OPENGNSYS_DIR" ]; then - echo "$PROG: Error: sin acceso al directorio de OpenGnSys (OPENGNSYS_DIR=\"$OPENGNSYS_DIR\")". >&2 + echo "$PROG: Error: sin acceso al directorio de OpenGnsys (OPENGNSYS_DIR=\"$OPENGNSYS_DIR\")". >&2 exit 1 fi if [ -z "$(getent passwd "$APACHE_USER" 2>/dev/null)" -o -z "$(getent group "$APACHE_GROUP" 2>/dev/null)" ]; then @@ -37,19 +37,24 @@ if [ -z "$(getent passwd "$APACHE_USER" 2>/dev/null)" -o -z "$(getent group "$AP exit 1 fi -chown -R :$OPENGNSYS_USER $OPENGNSYS_DIR/{log/clients,images} -chmod -R 775 $OPENGNSYS_DIR/{log/clients,images} +chown -R :$OPENGNSYS_USER $OPENGNSYS_DIR/{log/clients,images/groups} +find $OPENGNSYS_DIR/log/clients -type f -exec chmod 664 {} \; +find $OPENGNSYS_DIR/images -maxdepth 1 -exec chown :$OPENGNSYS_USER {} \; +find $OPENGNSYS_DIR/images -maxdepth 1 -type d -exec chmod 775 {} \; +find $OPENGNSYS_DIR/images -maxdepth 1 -type f -exec chmod 664 {} \; find $OPENGNSYS_DIR/client/{interfaceAdm,scripts} ! -name "*.txt" -exec chmod +x {} \; chown $OPENGNSYS_USER:$OPENGNSYS_USER $OPENGNSYS_DIR/client/interfaceAdm/CambiarAcceso chmod 700 $OPENGNSYS_DIR/client/interfaceAdm/CambiarAcceso chown root:root $OPENGNSYS_DIR/etc/{ogAdmServer,ogAdmAgent}*.cfg chmod 600 $OPENGNSYS_DIR/etc/{ogAdmServer,ogAdmAgent}*.cfg -chown $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/www/controlacceso*.php -chmod 600 $OPENGNSYS_DIR/www/controlacceso*.php +chown root:$APACHE_GROUP $OPENGNSYS_DIR/{www/controlacceso*.php,etc/ogAdmRepo*.cfg} +chmod 640 $OPENGNSYS_DIR/{www/controlacceso*.php,etc/ogAdmRepo*.cfg} chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/www/images/{fotos,iconos} chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/www/api -chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/tftpboot/{menu.lst,pxelinux.cfg} -chown -R :$OPENGNSYS_USER $OPENGNSYS_DIR/tftpboot/ogclient +chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/www/tmp # ??? +chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/tftpboot/menu.lst +chown -R :$OPENGNSYS_USER $OPENGNSYS_DIR/tftpboot/ogLive* find -L $OPENGNSYS_DIR/tftpboot -type d -exec chmod 755 {} \; find -L $OPENGNSYS_DIR/tftpboot -type f -exec chmod 644 {} \; +chown $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/log/ogagent.log diff --git a/server/bin/comparedhcpopengnsys b/server/bin/comparedhcpopengnsys index c303995a..38b05710 100755 --- a/server/bin/comparedhcpopengnsys +++ b/server/bin/comparedhcpopengnsys @@ -40,7 +40,7 @@ EOT trap "rm -f $TMP_DHCP $TMP_MYSQL $TMP_MYCNF" 1 2 3 9 15 # Creo fichero temporal del dhcp grep -v "#" $DHCPFILE |egrep -e "host " -e "hardware ethernet" -e fixed-address | sed -e 's/.$//' \ - | sed -e s/"^.*host[[:space:]]*"//g -e s/\{/\;/g -e s/"^.*hardware ethernet[[:space:]]*"/=/g -e s/"^.*fixed-address[[:space:]]*"/=/g \ + | sed -e s/"^.*host[[:space:]]*"//g -e s/\{/\;/g -e s/"^.*hardware ethernet[[:space:]]*"/=/g -e s/"^.*fixed-address[[:space:]]*"/=/g \ | sed -e :a -e '$!N;s/\n=/ \;/;ta' -e 'P;D'\ | sed -e s/\ //g -e s/://g -e s/\;$//g -e s/\;\;/\;/g |sort > $TMP_DHCP diff --git a/server/bin/comparemac b/server/bin/comparemac index e3b2a24e..0596c323 100755 --- a/server/bin/comparemac +++ b/server/bin/comparemac @@ -1,6 +1,6 @@ #!/bin/bash # comparemac - script para comparar las direcciones MAC (ethernet) de los clientes -# conectados a la red con las registradas en OpenGnSys. +# conectados a la red con las registradas en OpenGnsys. # Requisitos: arp-scan # Autores: Manuel González, Ramón M. Gómez - Univ. Sevilla, Junio 2014. diff --git a/server/bin/createfileimage b/server/bin/createfileimage deleted file mode 100755 index 73c57711..00000000 --- a/server/bin/createfileimage +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/bash -#/** -# createtimage -#@brief Crea o redimensiona el archivo de la imagen. -#@param 1 imagen -#@param 2 extension [ img|diff ] -#@param 3 tamaño de la imagen en kb. -#@return -#@exception OG_ERR_FORMAT # 1 formato incorrecto. -#@exception OG_ERR_DONTSYNC_IMAGE #71 Imagen no sincronizable (es monolitica) -#@version 1.0 - Montar imagen sincronizable -#@author Irina Gomez -#@date 2013-05-23 -#*/ ## -BASEDIR=/opt/opengnsys -REPODIR="$BASEDIR/images" -REPOLOG=$BASEDIR/log/ogAdmRepo.log -source $BASEDIR/client/etc/lang.$LANG.conf - -PROG="$(basename $0)" -# Si se solicita, mostrar ayuda. -if [ "$*" == "help" ]; then - echo -e " $PROG: $MSG_HELP_ogCreateFileImage \n" \ - "$MSG_FORMAT: $PROG image [ img|diff ] size_kb \n" \ - "base -> $PROG Windows7 img 3900000 \n" \ - "diff -> $PROG Ubuntu12 diff 450000" - exit 0 -fi - -[ $# -lt 3 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ] size_Kb " && exit 1 - -if [ "$USER" != "root" ]; then - echo "$PROG: Error: solo ejecutable por root" >&2 - exit 1 -fi - -IMGEXT="$2" - -# Si existe imagen, Comprobamos que no esta bloqueada y que es sincronizable -IMGFILE="$REPODIR/$1.$IMGEXT" -if [ -f $IMGFILE ]; then - [ -f $IMGFILE.lock ] && echo "$PROG: Error: $MSG_ERR_LOCKED $1 $IMGEXT" && exit 4 - - - if ! file $IMGFILE | grep -i -e " BTRFS Filesystem " -e " ext4 filesystem " >/dev/null ; then - echo "$PROG: Error: $MSG_ERR_DONTSYNC_IMAGE $1 $2" - exit 71 - fi -fi - -touch $IMGFILE.lock - -# El tamaño minimo de la imagen es 300000 para poder formatear en fs btrfs. -SIZEREQUIRED=$3 -[ $SIZEREQUIRED -lt 300000 ] && SIZEREQUIRED=300000 - -echo CREATE_IMAGE "$1" $IMGEXT $SIZEREQUIRED -echo -ne CREATE_IMAGE "$1" $IMGEXT $SIZEREQUIRED| /opt/opengnsys/sbin/ogAdmRepoAux || exit $? -echo "Los resultado se registran en $REPOLOG. " - -rm $IMGFILE.lock diff --git a/server/bin/installmodule b/server/bin/installmodule new file mode 100755 index 00000000..4625bd04 --- /dev/null +++ b/server/bin/installmodule @@ -0,0 +1,97 @@ +#!/bin/bash +# isntallmodule - instalar módulo de kernel en Initrd de cliente ogLive. +# Uso: installmodule tarfile +# Nota: tarfile es un fichero tar.gz con el fichero .ko del módulo y un fichero "module.conf" +# para configuración de instalación (debe incluir nombre, fichero y camino del módulo). +# Autor: Ramón M. Gómez +# Fecha: 2015-12-03 + + +# Variables. +PROG=$(basename $0) +OPENGNSYS=/opt/opengnsys +INITRD=$OPENGNSYS/tftpboot/ogclient/oginitrd.img +TARFILE=$(realpath $1 2>/dev/null) +tmpmod=/tmp/module$$ +tmpinit=/tmp/initrd$$ + +# Comprobar errores. +if [ $# -ne 1 ]; then + echo "$PROG: Incorrect operand. Format: $PROG moduletarfile" >&2 + exit 1 +fi +if [ "$USER" != "root" ]; then + echo "$PROG: Need to be root." >&2 + exit 1 +fi + +# Mostrar ayuda. +if [ "$1" == "help" ]; then + cat << EOT + +$PROG: installs kernel module into ogLive image (initrd). + +Format: $PROG moduletarfile + +moduletarfile must be a tar.gz archive with 2 files: + - *.ko: compiled module + - module.conf: configuration file + +Configuration file format: + module=ModuleName + file=ModuleFile + path=ModulePath + +ModuleName must be a single word. +ModuleFile must be a kernel compiled module file (*.ko). +ModulePath must be the kernel target directory, started by "kernel/". + +EOT + exit 0 +fi + +# Comprobar acceso al fichero de módulos. +if [ ! -r "$TARFILE" ]; then + echo "$PROG: Cannot access module file." >&2 + exit 1 +fi + +pushd /tmp >/dev/null + +# Borrar al salir del programa. +trap "popd 2>/dev/null; rm -fr $tmpmod $tmpinit" 0 1 2 3 6 9 15 + +# Descompresión de módulos para el ogLive actual. +mkdir -p $tmpmod +cd $tmpmod +tar xvzf $TARFILE >/dev/null || exit + +# Fichero de configuración. +source module.conf || exit +[ -z "$module" ] && echo "Module not detected." && exit 1 + +# Descomprimir Initrd. +mkdir -p $tmpinit +cd $tmpinit +gzip -dc $INITRD | cpio -im 2>/dev/null + +# Versión del Kernel del Initrd. +KERNEL=$(ls -d lib/modules/[0-9]* | head -1) +[ -z "$KERNEL" ] && echo "Kernel not detected." && exit 1 +# Avisar si el Kernel del módulo es distinto del del Initred. +echo "$(basename $KERNEL) $(modinfo -F vermagic $tmpmod/$file | cut -f1 -d' ')" | awk '$1!=$2 {print "WARNING: installing module for Kernel",$1,"on Kernel",$2}' + +# Copiar módulo y reconstruir dependencias. +echo "Installing module: $module" +cp -a $tmpmod/$file $KERNEL/$path +depmod -b . -a $(basename $KERNEL) + +# Recomponer el Initrd. +find . | cpio -H newc -oa | gzip -9c >$INITRD +md5sum $INITRD | cut -f1 -d" " > $INITRD.sum +cp -a $INITRD $INITRD.sum $OPENGNSYS/tftpboot + +# Limpiar. +popd >/dev/null +rm -fr $tmpmod $tmpinit + diff --git a/server/bin/installoglive b/server/bin/installoglive deleted file mode 100755 index a5cbcc57..00000000 --- a/server/bin/installoglive +++ /dev/null @@ -1,94 +0,0 @@ -#!/bin/bash -# installoglive - descarga e instala cliente ogLive. -# Nota: El usuario debe elegir el número del ogLive que desea instalar. -# Uso: installoglive -# Autor: Ramón M. Gómez - ETSII Univ. Sevilla -# Fecha: 2015-01-26 -# Versión: 1.0.6b - Adaptar la versión de Rsync de cliente y servidor. -# Autor: Ramón M. Gómez - ETSII Univ. Sevilla -# Fecha: 2015-12-16 - - -# Control de acceso. -PROG=$(basename $0) -if [ "$USER" != "root" ]; then - echo "$PROG: Need to be root." >&2 - exit 1 -fi - -# Constantes. -DOWNLOADURL="http://opengnsys.es/downloads" -OPENGNSYS=/opt/opengnsys -OGINITRD=$OPENGNSYS/tftpboot/ogclient/oginitrd.img -OGVMLINUZ=$OPENGNSYS/tftpboot/ogclient/ogvmlinuz - -# Listar todos los ficheros ogLive que pueden ser descargados. -OGLIVE=( $(wget $DOWNLOADURL -O - 2>/dev/null|grep ogLive.*iso) ) -NISOS=${#OGLIVE[@]} -echo "Descargas disponibles (+- = instalado):" -for i in $(seq 1 $NISOS); do - [ -e $OPENGNSYS/lib/${OGLIVE[i-1]} ] && OGLIVE[i-1]="+-${OGLIVE[i-1]}" -done -select opt in ${OGLIVE[@]}; do - [ -n "$opt" ] && OGLIVEFILE=${opt/+-/} && break -done - -# Tamaño del fichero a descargar. -SOURCELENGTH=$(LANG=C wget --spider $DOWNLOADURL/$OGLIVEFILE 2>&1 | awk '/Length:/ {print $2}') -[ -n "$SOURCELENGTH" ] || exit - -# Descarga de ogLive. -TARGETFILE=$OPENGNSYS/lib/$OGLIVEFILE -wget $DOWNLOADURL/$OGLIVEFILE -O $TARGETFILE || exit - -# Obtener la clave actual de acceso a Samba para restaurarla tras la descarga. -if [ -f $OGINITRD ]; then - SAMBAPASS=$(gzip -dc $OGINITRD | \ - cpio -i --to-stdout scripts/ogfunctions 2>&1 | \ - grep "^[ ].*OPTIONS=" | \ - sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') -fi - -# Hacer copia de seguridad del ogLive actual. -rm -fr $OPENGNSYS/tftpboot/ogclient.old -mv -f $OPENGNSYS/tftpboot/ogclient $OPENGNSYS/tftpboot/ogclient.old - -# Montar la imagen ISO del ogclient, actualizar ficheros y desmontar. -TMPDIR=/tmp/${OGLIVEFILE%.iso} -mkdir -p $TMPDIR -mount -o loop,ro $TARGETFILE $TMPDIR -cp -va $TMPDIR/ogclient $OPENGNSYS/tftpboot/ogclient -umount $TMPDIR - -# Recuperar la clave de acceso a Samba o solicitar una nueva clave. -if [ -n "$SAMBAPASS" ]; then - echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass -else - $OPENGNSYS/bin/setsmbpass -fi - -# Establecer los permisos. -find -L $OPENGNSYS/tftpboot/ogclient -type d -exec chmod 755 {} \; -find -L $OPENGNSYS/tftpboot/ogclient -type f -exec chmod 644 {} \; -chown -R :opengnsys $OPENGNSYS/tftpboot/ogclient - -# Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache -cp -av $OPENGNSYS/tftpboot/ogclient/{ogvmlinuz,oginitrd.img}* $OPENGNSYS/tftpboot - -# Montar SquashFS para comprobar versión de Rsync. -mount -o loop,ro $OPENGNSYS/tftpboot/ogclient/ogclient.sqfs $TMPDIR -# Si versión Rsync de servidor > cliente, enlazar a fichero compilado. -RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}') -RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') -if [ -z "$RSYNCSERV" -o ${RSYNCSERV:-0} -gt ${RSYNCCLNT:-1} ]; then - [ -e $OPENGNSYS/client/bin/rsync-$RSYNCSERV ] && mv -f $OPENGNSYS/client/bin/rsync-$RSYNCSERV $OPENGNSYS/client/bin/rsync -else - # Si no, renombrar fichero compilado con nº de protocolo. - [ -e $OPENGNSYS/client/bin/rsync ] && mv -f $OPENGNSYS/client/bin/rsync $OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') -fi -# Desmontar SquashFS. -umount $TMPDIR -rmdir $TMPDIR -# Versión del ogLive instalado -echo "${OGLIVEFILE%.*}" > $OPENGNSYS/doc/veroglive.txt - diff --git a/server/bin/installoglive b/server/bin/installoglive new file mode 120000 index 00000000..f7b0fa3e --- /dev/null +++ b/server/bin/installoglive @@ -0,0 +1 @@ +oglivecli \ No newline at end of file diff --git a/server/bin/listclientlive b/server/bin/listclientlive new file mode 100755 index 00000000..3aeccce3 --- /dev/null +++ b/server/bin/listclientlive @@ -0,0 +1,50 @@ +#!/bin/bash +# listclientlive: Lista la distribución ogLive asociada a los clientes, +# ya sea un equipo o un aula. +# Uso: listclienlive NombrePC | NombreAula +# Autor: Ramón M. Gómez - Univ. Sevilla, junio 2017 + + +# Variables. +PROG=$(basename "$0") +OPENGNSYS=${OPENGNSYS:-"/opt/opengnsys"} +SERVERCONF=$OPENGNSYS/etc/ogAdmServer.cfg +TFTPDIR=$OPENGNSYS/tftpboot +MYCNF=/tmp/.my.cnf.$$ + +# Control básico de errores. +if [ $# -ne 1 ]; then + echo "$PROG: Error de ejecución" >&2 + echo "Formato: $PROG [NOMBRE_PC|NOMBRE_AULA]" >&2 + exit 1 +fi +if [ ! -r $SERVERCONF ]; then + echo "$PROG: Sin acceso a fichero de configuración" >&2 + exit 2 +fi + +# Obtener datos de acceso a la Base de datos. +source $SERVERCONF +# Sustituir caracteres ' por \' para evitar inyección SQL. +RESOURCE="${1//\'/\'}" +# Componer fichero con credenciales de conexión. +touch $MYCNF +chmod 600 $MYCNF +cat << EOT > $MYCNF +[client] +user=$USUARIO +password=$PASSWORD +EOT +# Borrar el fichero temporal si termina el proceso. +trap "rm -f $MYCNF" 0 1 2 3 6 9 15 +# Obtener nombre de ordenador individual o todos los de una aula e indicar su plantilla asociada. +mysql --defaults-extra-file="$MYCNF" -D "$CATALOG" -s -N -e \ + "SELECT ord.nombreordenador, ord.oglivedir + FROM ordenadores AS ord + JOIN aulas USING (idaula) + WHERE aulas.nombreaula='$RESOURCE' + OR ord.nombreordenador='$RESOURCE';" | \ + while read -r PC OGLIVE; do + echo "Equipo \"$PC\" asociado a cliente \"$OGLIVE\" $([ -e $TFTPDIR/$OGLIVE ] || echo "(inexistente)")" + done + diff --git a/server/bin/listclientmode b/server/bin/listclientmode index 2496a6da..5d02bcee 100755 --- a/server/bin/listclientmode +++ b/server/bin/listclientmode @@ -46,6 +46,6 @@ mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -s -N -e \ WHERE aulas.nombreaula='$RESOURCE' OR nombreordenador='$RESOURCE';" | \ while read PC TMPL; do - echo "Equipo $PC asociado a arranque tipo \"$(head -1 $TMPLDIR/$TMPL |cut -f2 -d" ")\" (fichero $TMPL)" + echo "Equipo \"$PC\" asociado a arranque tipo \"$(head -1 $TMPLDIR/$TMPL |cut -f2 -d" ")\" (fichero $TMPL)" done diff --git a/server/bin/mountimage b/server/bin/mountimage deleted file mode 100755 index 6187724d..00000000 --- a/server/bin/mountimage +++ /dev/null @@ -1,66 +0,0 @@ -#!/bin/bash -#/** -# mountimage -#@brief Monta imagen sincronizable en el repositorio con permisos de escritura -#@param 1 imagen -#@param 2 extension [ img|diff ] opcional, por defecto img -#@return Directorio de montaje de la imagen. -#@exception OG_ERR_FORMAT # 1 formato incorrecto. -#@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado -#@exception OG_ERR_DONTSYNC_IMAGE #71 Imagen no sincronizable (es monolitica) -#@exception OG_ERR_DONTMOUNT_IMAGE # 70 Error al montar una imagen sincronizada -#@version 1.0 - Montar imagen sincronizable -#@author Irina Gomez -#@date 2013-05-23 -#*/ ## -BASEDIR=/opt/opengnsys -REPODIR="$BASEDIR/images" -source $BASEDIR/client/etc/lang.$LANG.conf - -PROG="$(basename $0)" -# Si se solicita, mostrar ayuda. -if [ "$*" == "help" ]; then - echo -e " $PROG: $MSG_HELP_ogMountImage \n" \ - "$MSG_FORMAT: $PROG nombre_image [ img|diff ] \n" \ - "base -> $PROG Windows7 \n" \ - "diff -> $PROG Ubuntu12 diff" - exit 0 -fi - -[ $# -lt 1 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ]" && exit 1 - -if [ "$USER" != "root" ]; then - echo "$PROG: Error: solo ejecutable por root" >&2 - exit 1 -fi - -[ "$2" == "" -o "$2" == "img" ] && IMGEXT="img" || IMGEXT="img.diff" - -# Comprobamos que existe imagen -IMGFILE="$REPODIR/$1.$IMGEXT" -[ ! -f $IMGFILE ] && echo "$PROG: Error: $MSG_ERR_NOTFOUND $1 $IMGEXT" && exit 2 - - -# Comprobar que la imagen es sincronizable -file $IMGFILE | grep -i -e " BTRFS Filesystem " >/dev/null && IMGFS=BTRFS -file $IMGFILE | grep -i -e " ext4 filesystem " >/dev/null && IMGFS=EXT4 -if [ "$IMGFS" != "BTRFS" -a "$IMGFS" != "EXT4" ] ; then - echo "$PROG: Error: $MSG_ERR_DONTSYNC_IMAGE $1 $2" - exit 71 -fi - -MOUNTDIR="$REPODIR/mount/$1" -[ "$IMGEXT" == "img.diff" ] && MOUNTDIR="$MOUNTDIR.${IMGEXT#*\.}" -mkdir -p "$MOUNTDIR" - -# Comprobamos si la imagen esta montada y si es así nos salimos. -df |grep "$MOUNTDIR$" 2>&1 >/dev/null && echo "$MOUNTDIR" && exit 0 - -if [ "$IMGFS" == "EXT4" ] ; then - mount -t ext4 "$IMGFILE" "$MOUNTDIR" -else - mount -o compress=lzo "$IMGFILE" "$MOUNTDIR" -fi -[ $? -eq 0 ] || ( echo "$MSG_ERR_DONTMOUNT_IMAGE $1 $2" ; exit 70) -echo "$MOUNTDIR" - diff --git a/server/bin/ogagentqueue.cron b/server/bin/ogagentqueue.cron new file mode 100755 index 00000000..0cf0dd5d --- /dev/null +++ b/server/bin/ogagentqueue.cron @@ -0,0 +1,100 @@ +#!/bin/bash + +#/** +#@file ogagentqueue.cron +#@brief Cronfile to send pending operations to OGAgent. +#warning This file must be executed under system Cron every minute. +#@version 1.1.0 - Initial version. +#@date 2017-10-26 +#@author Ramón M. Gómez - Univ. Sevilla +#*/ ## + + +# Variables. +PROG=$(basename "$0") +OPENGNSYS=${OPENGNSYS:-"/opt/opengnsys"} +SERVERCONF=$OPENGNSYS/etc/ogAdmServer.cfg +LOGFILE=$OPENGNSYS/log/remotepc.log +MYCNF=/tmp/.my.cnf.$$ + +# Basic error control +if [ ! -r "$SERVERCONF" ]; then + echo "$PROG: Cannot access to configuration file." >&2 + exit 2 +fi +if ! touch "$LOGFILE"; then + echo "$PROG: Cannot write to log file." >&2 + exit 2 +fi + +# Fetching database access data. +source "$SERVERCONF" +# Composing connection credentils file. +touch $MYCNF +chmod 600 $MYCNF +cat << EOT > $MYCNF +[client] +user=$USUARIO +password=$PASSWORD +EOT +# Trap to delete temporal file if process ends. +trap "rm -f $MYCNF" 0 1 2 3 6 9 15 +# Reading pending operations. +mysql --defaults-extra-file="$MYCNF" -D "$CATALOG" -Nse " +SELECT ogagent_queue.id, ogagent_queue.exectime, ogagent_queue.operation, + ordenadores.idordenador, ordenadores.ip, ordenadores.agentkey, remotepc.language + FROM ogagent_queue + JOIN ordenadores ON ogagent_queue.clientid=ordenadores.idordenador + JOIN remotepc ON ogagent_queue.clientid=remotepc.id + WHERE exectime < NOW() + ORDER BY exectime;" | \ + while read -r OPERID DATE TIME OPER CLNTID AGNTIP AGNTKEY LANGUAGE; do + # Preparing operation data. + case "$OPER" in + popup-10) # Message: 10 min. before power off. + AGNTURL=https://$AGNTIP:8000/opengnsys/popup + case "$LANGUAGE" in + es) DATA='{"title":"Apagado en 10 min.","message":"Fin del tiempo de acceso remoto.\nEl ordenador se apagará automáticamente dentro de 10 minutos."}' ;; + *) DATA='{"title":"Shutdown after 10 min.","message":"Remote access time is ended.\nComputer will be powered off automaticly after 10 minutes."}' ;; + esac + ;; + popup-5) # Message: 5 min. before power off. + AGNTURL=https://$AGNTIP:8000/opengnsys/popup + case "$LANGUAGE" in + es) DATA='{"title":"Apagado en 5 min.","message":"El ordenador se apagará automáticamente dentro de 5 minutos.\nATENCIÓN: Este es el último aviso."}' ;; + *) DATA='{"title":"Shutdown after 5 min.","message":"The computer will be powered off automaticly after 5 minutes.\nATTENTION: This is the last warning."}' + esac + ;; + poweroff) # Power off client. + AGNTURL=https://$AGNTIP:8000/opengnsys/poweroff + DATA= + ;; + *) # Unknown operation. + AGNTURL= + ;; + esac + # Sending operation to OGAgent. + if [ -n "$AGNTURL" ]; then + CODE=$(curl -ksm 1 -w "%{http_code}" -o /dev/null -H "Authorization: $AGNTKEY" ${DATA:+"-d $DATA"} "$AGNTURL") + case "$CODE" in + 000) # Client does not respond may be halted). + ;; + 200) # Operation sended. + echo "$(date +"%FT%T%z"): $PROG: Operation sended to OGAgent: client=$AGNTIP, oper=$OPER, exectime=\"$DATE $TIME\"" >> $LOGFILE ;; + *) # Operation error. + echo "$(date +"%FT%T%z"): $PROG: Operation error: client=$AGNTIP, oper=$OPER, code=$CODE" >> $LOGFILE ;; + esac + else # Unknown operation. + echo "$(date +"%FT%T%z"): $PROG: Unknown operation: client=$AGNTIP, oper=$OPER" >> $LOGFILE + fi + # Deleting operation from database. + SQL="DELETE FROM ogagent_queue WHERE id='$OPERID';" + [ "$OPER" == "poweroff" ] && SQL="$SQL +UPDATE remotepc + SET reserved = NOW() - INTERVAL 1 SECOND, urllogin=NULL, urllogout=NULL, language=NULL + WHERE id = '$CNLTID'; +DELETE FROM acciones + WHERE idordenador = '$CLNTID' + AND descriaccion = 'RemotePC Session';" + mysql --defaults-extra-file="$MYCNF" -D "$CATALOG" -Nse "$SQL" + done diff --git a/server/bin/oglivecli b/server/bin/oglivecli new file mode 100755 index 00000000..451c3c12 --- /dev/null +++ b/server/bin/oglivecli @@ -0,0 +1,482 @@ +#!/bin/bash + +#/** +# oglivecli command [options ...] +#@file oglivecli +#@brief Command line tool to manage ogLive clients. +#@param $1 command Command to execute. +#@param $2 options Parameters and options. +#@warning This script uses "jq" command. +#@version 1.1.0 - Initial version. +#@author Ramón M. Gómez - ETSII Univ. Sevilla +#@date 2016-12-05 +#*/ ## + + +# Global constants definition. +PROG=$(basename "$(realpath "$0")") +OPENGNSYS=/opt/opengnsys +DOWNLOADDIR=$OPENGNSYS/lib +DOWNLOADURL="https://opengnsys.es/trac/downloads" +TFTPDIR=$OPENGNSYS/tftpboot +DEFOGLIVE="ogLive" +INFOFILE=$OPENGNSYS/etc/ogliveinfo.json + + +# Auxiliar functions. + +# Metafunction to check if JSON result exists. +function jq() { + local OUTPUT + OUTPUT=$($JQ "$@") || return $? + [[ "$OUTPUT" = "null" ]] && return 1 + echo "$OUTPUT" +} + +# Create/edit JSON file about installed ogLive clients. +function addToJson() { + local DATA OGLIVEDIST="$1" OGLIVEKRNL="$2" OGLIVEARCH="$3" OGLIVEREV="$4" + local OGLIVEDIR=$(basename $5 2>/dev/null) OGLIVEISO=$(basename $6 2>/dev/null) + # JSON data for installed ogLive. + DATA=$(cat << EOT | jq . +{"distribution":"$OGLIVEDIST","kernel":"$OGLIVEKRNL","architecture":"$OGLIVEARCH","revision":"$OGLIVEREV","directory":"$OGLIVEDIR","iso":"$OGLIVEISO"} +EOT + ) + # Check JSON file consistency. + if [ "$(jq -c keys $INFOFILE 2>/dev/null)" == '["default","oglive"]' ]; then + # Check if ogLive is defined into JSON file. + n=$(jq ".oglive | length" $INFOFILE) + for ((i=0; i&2 + exit 1 ;; + notfound) + echo "$PROG: Resource not found: $2" >&2 + exit 2 ;; + access) + echo "$PROG: Access error: $2" >&2 + exit 3 ;; + download) + echo "$PROG: Download error: $2" >&2 + exit 4 ;; + *) + echo "$PROG: Unknown error" >&2 + exit 1 ;; + esac +} + +# Command functions. + +# Show help message. +function help() { + cat << EOT +$PROG: manage ogLive cleints. +Usage: $PROG command [options] +Commands: + help show this help + config show configuration parameters + check check system consistency + convert convert old ogclient to new default ogLive client + list list installed ogLive clients + show all show JSON information about all installed ogLive clients + show default show JSON information about ogLive client marked as default + show Index|Dir show JSON information about an installed ogLive client + search Index|Dir show corresponding index or directory + download show a menu to download an ogLive ISO image from the OpenGnsys website + download Iso download an specific ogLive ISO image from the OpenGnsys website + install Iso install a new ogLive client from a downloaded ISO image + uninstall Iso remove ISO image and uninstall its ogLive client + uninstall Index|Dir uninstall an ogLive client + get-default get index value for default ogLive client + set-default Index set default ogLive client + rebuild rebuild a lost configuration file + assign Iso Index assign an ISO file to a JSON entry +Parameters: + Index a number, starting by 0 + Dir directory (relative to installation directory) + Iso ISO file name (relative to download URL or download directory) +EOT +} + +# Convert default ogclient to a new ogLive format. +function convert() { + local OGCLIENT=ogclient OLDINFOFILE=$OPENGNSYS/doc/veroglive.txt + local OGLIVEKRNL OGLIVEDIR OGLIVEISO + [ $# -ne 0 ] && raiseError usage + [ ! -w $(dirname $INFOFILE) ] && raiseError access "Configuration file." + [ -n "$(stat -c "%N" $TFTPDIR/ogclient | awk '$3~/'$DEFOGLIVE'/ {print}')" ] && raiseError access "ogLive is already converted." + pushd $TFTPDIR >/dev/null || raiseError access "Installation directory." + [ ! -f $OGCLIENT/ogvmlinuz ] && raiseError notfound "ogclient" + # Add entry to JSON file using ogclient kernel version. + OGLIVEKRNL=$(file -bkr $OGCLIENT/ogvmlinuz | awk '/Linux/ {for(i=1;i<=NF;i++) if($i~/version/) {v=$(i+1);sub(/-.*/,"",v);print v}}') + OGLIVEDIR=$DEFOGLIVE-$OGLIVEKRNL + [ -r $OLDINFOFILE ] && OGLIVEISO="$(head -1 $OLDINFOFILE)" + addToJson "$(echo $OGLIVEISO|cut -f2 -d-)" "$OGLIVEKRNL" "i386" "${OGLIVEISO##*-}" "$OGLIVEDIR" "$OGLIVEISO.iso" + # Rename directory, link to default and clean old files. + mv -v $OGCLIENT $OGLIVEDIR + ln -vfs $OGLIVEDIR $DEFOGLIVE + rm -f $OGCLIENT + ln -vfs $DEFOGLIVE $OGCLIENT + mv -v $OGCLIENT.old $OGLIVEDIR.old 2>/dev/null + rm -fv {ogvmlinuz,oginitrd.img}{,.sum} $OLDINFOFILE + popd >/dev/null + # Delete old config file. + rm -f $OLDINFOFILE +} + +# Show script configuration parameters. +function config() { + case $# in + 0) # Show all parameters. + cat << EOT +Configuration file: $INFOFILE +ogLive download URL: $DOWNLOADURL +ogLive download directory: $DOWNLOADDIR +ogLive installation directory: $TFTPDIR +Default ogLive name: $DEFOGLIVE +EOT + ;; + 1) # Show specified parameter. + case "$1" in + config-file) echo "$INFOFILE" ;; + download-url) echo "$DOWNLOADURL" ;; + download-dir) echo "$DOWNLOADDIR" ;; + install-dir) echo "$TFTPDIR" ;; + default-name) echo "$DEFOGLIVE" ;; + *) raiseError notfound "$1" ;; + esac + ;; + *) # Usage error. + raiseError usage + ;; +esac +} + +# Check consistency, showing configuration problems. +function check() { + local ERR=0 AUX INST DEF + [ $# -ne 0 ] && raiseError usage + # Check for old system that needs conversion. + if [ -z "$(stat -c "%N" $TFTPDIR/ogclient | awk '$3~/'$DEFOGLIVE'/ {print}')" ]; then + echo "This server uses old ogclient, please run \"$PROG convert\" to update." + let ERR++ + [ ! -f $INFOFILE ] && return $ERR + fi + # Check for other problems. + [ ! -f $INFOFILE ] && echo "Configuration file does not exists: $INFOFILE" && let ERR++ + [ -f $INFOFILE -a "$(jq -c keys $INFOFILE 2>/dev/null)" != "[\"default\",\"oglive\"]" ] && echo "Format error in configuration file: $INFOFILE" && let ERR++ + [ ! -e $TFTPDIR ] && echo "TFTP directory does not exist: $TFTPDIR." && let ERR++ + # Check for installed ogLive clients. + INST=( $(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort) ) + [[ ${#INST[@]} -eq 0 ]] && echo "No ogLive clients are installed." && let ERR++ + DEF=( $(jq -r .oglive[].directory $INFOFILE 2>/dev/null | sort) ) + # Compare installed and defined ogLive clients. + AUX=$(comm -23 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]})) + [ -n "$AUX" ] && echo "Some ogLive are installed but not defined: ${AUX//$'\n'/, }" && let ERR++ + AUX=$(comm -13 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]})) + [ -n "$AUX" ] && echo "Some ogLive are defined but not installed: ${AUX//$'\n'/, }" && let ERR++ + # Compare downloaded and defined ISO images. + INST=( $(find $DOWNLOADDIR/ -type f -name "$DEFOGLIVE-*.iso" -printf "%f\n" | sort) ) + DEF=( $(jq -r .oglive[].iso $INFOFILE 2>/dev/null | sort) ) + AUX=$(comm -23 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]})) + [ -n "$AUX" ] && echo "Some ISOs are downloaded but not defined: ${AUX//$'\n'/, }" && let ERR++ + AUX=$(comm -13 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]})) + [ -n "$AUX" ] && echo "Some ISOs are defined but not downloaded: ${AUX//$'\n'/, }" && let ERR++ + # Check for new ISO files downloaded after installation. + AUX=$(jq -r '.oglive[] as $og | $og.iso + ":" + $og.directory' $INFOFILE 2>/dev/null | \ + while IFS=":" read -r DEF INST; do + [ $DOWNLOADDIR/$DEF -nt $TFTPDIR/$INST ] && echo "$DEF" + done) + [ -n "$AUX" ] && echo "Some ISOs are downloaded after installation: ${AUX//$'\n'/, }" && let ERR++ + # Print result. + [ $ERR -eq 0 ] && echo "OK!" || echo "Problems detected: $ERR" + return $ERR +} + +# List installed ogLive clients. +function list() { + [ $# -ne 0 ] && raiseError usage + [ ! -r $INFOFILE ] && raiseError access "Configuration file." + # List all defined indexes, directories and check if missing. + jq -r .oglive[].directory $INFOFILE | nl -v 0 | \ + awk '{system("echo -n "$0"; test -d '$TFTPDIR'/"$2" || echo -n \" (missing)\"; echo")}' | column -t +} + +# Show information about an installed ogLive client. +function show() { + local INDEX + [ $# -ne 1 ] && raiseError usage + [ ! -r $INFOFILE ] && raiseError access "Configuration file." + # Show JSON entries. + case "$1" in + default) # Default index. + INDEX="[$(jq -r .default $INFOFILE)]" ;; + all) # All intries. + ;; + [0-9]*) # Index. + INDEX="[$1]" ;; + *) # Directory. + INDEX="[$(search "$1" 2>/dev/null)]" || raiseError notfound "Directory \"$1\"." + ;; + esac + jq ".oglive$INDEX" $INFOFILE || raiseError notfound "Index \"$1\"." +} + +# Show index or directory corresponding to searching parameter. +function search() { + [ $# -ne 1 ] && raiseError usage + [ ! -r $INFOFILE ] && raiseError access "Configuration file." + # Show corresponding index or directory. + list | awk -v d="$1" '{if ($2==d) print $1; if ($1==d) print $2}' | grep . || raiseError notfound "Index/Directory \"$1\"" +} + +# Show a menu to select and download an ogLive ISO image from the OpenGnsys website. +function download() { + local OGLIVE NISOS i SOURCELENGTH TARGETFILE + local ISOREL MINREL=5000 # Mininum compatibility release. + [ $# -gt 1 ] && raiseError usage + [ ! -d $DOWNLOADDIR ] && raiseError notfound "Download directory" + [ ! -w $DOWNLOADDIR ] && raiseError access "Download directory" + # Check parameter. + if [ -n "$1" ]; then + # ogLive to download. + OGLIVEFILE="$1" + else + # Show download menu. + OGLIVE=( $(curl --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") ) + NISOS=${#OGLIVE[@]} + echo "Available downloads (+ = installed, * = full compatibility):" + for i in $(seq 1 $NISOS); do + [ -e $DOWNLOADDIR/${OGLIVE[i-1]} ] && OGLIVE[i-1]="(+) ${OGLIVE[i-1]}" + ISOREL=${OGLIVE[i-1]##*-r}; ISOREL=${ISOREL%.*} + [ $ISOREL -ge $MINREL ] && OGLIVE[i-1]="(*) ${OGLIVE[i-1]}" + done + select opt in "${OGLIVE[@]}"; do + [ -n "$opt" ] && OGLIVEFILE=${opt##* } && break + done + fi + # Get download size. + SOURCELENGTH=$(curl --head --silent $DOWNLOADURL/$OGLIVEFILE | awk -F: '/Content-Length:/ {print $2}') + [ -n "$SOURCELENGTH" ] || raiseError download "$OGLIVEFILE" + # Download ogLive. + TARGETFILE=$DOWNLOADDIR/$OGLIVEFILE + trap "rm -f $TARGETFILE" 1 2 3 6 9 15 + curl $DOWNLOADURL/$OGLIVEFILE -o $TARGETFILE || raiseError download "$OGLIVEFILE" +} + +# Install an ogLive client from a previously downloaded ISO image. +function install() { + local OGLIVEFILE OGLIVEDIST OGLIVEREV OGLIVEKRNL OGLIVEDIR OGINITRD OGSQFS OGCLIENT=ogclient + local SAMBAPASS TMPDIR RSYNCSERV RSYNCCLNT + [ $# -ne 1 ] && raiseError usage + OGLIVEFILE=$(realpath $DOWNLOADDIR/$1) + # Only 1 file in pathname expansion. + [ $(echo $OGLIVEFILE | wc -w) -gt 1 ] && raiseError usage + [ ! -f $OGLIVEFILE ] && raiseError notfound "Downloaded file: \"$1\"." + [ ! -r $OGLIVEFILE ] && raiseError access "Downloaded file: \"$1\"." + [ ! -w $(dirname $INFOFILE) ] && raiseError access "Configuration directory." + [ ! -w $TFTPDIR ] && raiseError access "Installation directory." + [ -z "$(file -b $OGLIVEFILE | grep "ISO.*ogClient")" ] && raiseError access "File is not an ogLive ISO image." + # Working directory (ogLive-Distribution-KernelVersion-Architecture-CodeRevision). + OGLIVEDIST="$(echo $OGLIVEFILE|cut -f2 -d-)" + OGLIVEREV="${OGLIVEFILE##*-}"; OGLIVEREV="${OGLIVEREV%.*}" + OGLIVEKRNL="$(echo $OGLIVEFILE|cut -f3- -d-)"; OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEREV.*}" + OGLIVEARCH="$(echo $OGLIVEFILE|awk -F- '{print $(NF-1)}')" + case "$OGLIVEARCH" in + i386|amd64) # Get architecture. + OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEARCH}" ;; + *) # 32-bit by default. + OGLIVEARCH="i386" ;; + esac + OGLIVEDIR="$TFTPDIR/$DEFOGLIVE-$OGLIVEDIST-${OGLIVEKRNL%%-*}-$OGLIVEARCH-$OGLIVEREV" + # Get current or default Samba key. + OGINITRD=$OGLIVEDIR/oginitrd.img + [ ! -r $OGINITRD ] && OGINITRD=$TFTPDIR/$DEFOGLIVE/oginitrd.img + if [ -r $OGINITRD ]; then + SAMBAPASS=$(gzip -dc $OGINITRD | \ + cpio -i --to-stdout scripts/ogfunctions 2>&1 | \ + grep "^[ ].*OPTIONS=" | \ + sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') + fi + # Make ogLive backup. + rm -fr ${OGLIVEDIR}.old + mv -fv $OGLIVEDIR ${OGLIVEDIR}.old 2>/dev/null + # Mount ogLive ISO image, update its files and unmount it. + TMPDIR=/tmp/${OGLIVEFILE%.iso} + mkdir -p $OGLIVEDIR $TMPDIR + trap "umount $TMPDIR; rm -fr $TMPDIR" 1 2 3 6 9 15 + mount -o loop,ro $OGLIVEFILE $TMPDIR + cp -va $TMPDIR/ogclient/* $OGLIVEDIR || raiseError access "Cannot copy files to ogLive directory." + umount $TMPDIR + # Link to default directory if it's the first ogLive. + if [ ! -f $INFOFILE ]; then + rm -f $TFTPDIR/$DEFOGLIVE $TFTPDIR/$OGCLIENT + ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE + ln -vfs $DEFOGLIVE $TFTPDIR/$OGCLIENT + fi + # Recover or ask for a new Samba access key. + if [ -n "$SAMBAPASS" ]; then + echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" + else + $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)" + fi + # Set permissions. + find -L $OGLIVEDIR -type d -exec chmod 755 {} \; + find -L $OGLIVEDIR -type f -exec chmod 644 {} \; + chown -R :opengnsys $OGLIVEDIR + # Mount SquashFS and check Rsync version. + OGSQFS=$OGLIVEDIR/ogclient.sqfs + mount -o loop,ro $OGSQFS $TMPDIR + # If Rsync server version > client version, link to compiled file. + RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}') + RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') + if [ -z "$RSYNCSERV" -o ${RSYNCSERV:-0} -gt ${RSYNCCLNT:-1} ]; then + [ -e $OPENGNSYS/client/bin/rsync-$RSYNCSERV ] && mv -f $OPENGNSYS/client/bin/rsync-$RSYNCSERV $OPENGNSYS/client/bin/rsync + else + # Else, rename compiled file using Rsync protocol number. + [ -e $OPENGNSYS/client/bin/rsync ] && mv -f $OPENGNSYS/client/bin/rsync $OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}') + fi + # Unmount SquashFS. + umount $TMPDIR + rmdir $TMPDIR + # Update JSON file. + addToJson "$OGLIVEDIST" "$OGLIVEKRNL" "$OGLIVEARCH" "$OGLIVEREV" "$OGLIVEDIR" "$OGLIVEFILE" +} + +# Uninstall an ogLive client. +function uninstall() { + local ISO DIR INDEX DEFINDEX + [ $# -ne 1 ] && raiseError usage + [ ! -r $INFOFILE ] && raiseError access "Configuration file." + [ ! -w $TFTPDIR ] && raiseError access "Installation directory." + # Get index and directory for the entry. + case "$1" in + */*) # Error (access to other directory). + raiseError access "Cannot access outside installation directory." + ;; + *.iso) # ISO file. + ISO="$1" + # Working directory (ogLive-Distribution-KernelVersion-CodeRevision). + DIR="$(echo $ISO|cut -f1,3 -d-)-${ISO##*-}"; DIR=${DIR%.*} + INDEX=$(search $DIR 2>/dev/null) + ;; + [0-9]*) # Index. + INDEX=$1; DIR=$(search $INDEX 2>/dev/null) + ;; + *) # Directory. + DIR="$1"; INDEX=$(search $DIR 2>/dev/null) + ;; + esac + DEFINDEX=$(getdefault) + [[ $INDEX = $DEFINDEX ]] && raiseError access "Cannot uninstall default ogLive." + # Remove files and delete index entry. + rm -vfr ${ISO:+$DOWNLOADDIR/$ISO} ${DIR:+$TFTPDIR/$DIR} ### Remove $TFTPDIR/$DIR.old ? + if [ -n "$INDEX" ]; then + jq "del(.oglive[$INDEX])" $INFOFILE | sponge $INFOFILE + # Decrement default index if needed (removed < default). + [[ $INDEX < $DEFINDEX ]] && jq ".default=$((DEFINDEX-1))" $INFOFILE | sponge $INFOFILE + fi +} + +# Get default ogLive index. +function getdefault() { + [ $# -ne 0 ] && raiseError usage + [ ! -r $INFOFILE ] && raiseError access "Configuration file." + # Read default parameter. + jq -r .default $INFOFILE || raiseError notfound "Undefined default index." +} + +# Set default ogLive index. +function setdefault() { + local INDEX OGLIVEDIR + [ $# -ne 1 ] && raiseError usage + [ ! -w $INFOFILE ] && raiseError access "Configuration file." + INDEX=$1 + # Check if index entry exists. + jq ".oglive[$INDEX]" $INFOFILE || raiseError notfound "Index \"$INDEX\"." + # Get ogLive directory. + OGLIVEDIR=$(jq -r ".oglive[$INDEX].directory" $INFOFILE) || raiseError notfound "Directory for index \"$INDEX\"." + # Update default parameter. + jq ".default=$INDEX" $INFOFILE | sponge $INFOFILE + # Link to default directory. + rm -f $TFTPDIR/$DEFOGLIVE + ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE +} + +# Rebuild a lost configuration file. +function rebuild() { + local INST i NF DEF + [ $# -ne 0 ] && raiseError usage + [ -f $INFOFILE ] && raiseError access "Configuration file exists." + INST=$(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort) + for i in $INST; do + NF=$(echo $i | awk -F- '{print NF-1}') + case $NF in + 1) addToJson "" "$(echo $i|cut -f2 -d-)" "i386" "" "$i" "" ;; + 4) addToJson $(echo $i | awk -F- '{printf "%s %s i386 %s %s '""'",$2,$3,$4,$0}') ;; + 5) addToJson $(echo $i | awk -F- '{printf "%s %s %s %s %s '""'",$2,$3,$4,$5,$0}') ;; + esac + # Check for is default oglive. + [ -n "$(stat -c "%N" $TFTPDIR/$DEFOGLIVE | awk '$3~/'$i'/ {print}')" ] && DEF="$i" + done + # Set default ogLive. + [ -n "$DEF" ] && setdefault $(search $DEF) +} + +# Assign an ISO file to a JSON entry. +function assign() { +local ISOFILE DIR + [ $# -ne 2 ] && raiseError usage + [ ! -w $INFOFILE ] && raiseError access "Configuration file." + # Check if exist ISO file and index directory. + ISOFILE=$DOWNLOADFILE/$1 + [ ! -f $DOWNLOADDIR/$ISOFILE ] && raiseError notfound "ISO file \"$1\"." + DIR=$(search $2 2>/dev/null) + [ ! -d $TFTPDIR/$DIR ] && raiseError notfound "Directory for index \"$2\"." + # Assign ISO file to JSON entry. + jq ".oglive[$2].iso=\"$1\"" $INFOFILE | sponge $INFOFILE && jq ".oglive[$2]" $INFOFILE +} + + +# Main progrram. + +# Access control. +[ -r $OPENGNSYS/www/controlacceso.php ] && ACCESS="web" +[ "$USER" = "root" ] && ACCESS="root" +[ -z "$ACCESS" ] && raiseError access "Need to be root." +# Check dependencies. +JQ=$(which jq 2>/dev/null) || raiseError notfound "Need to install \"jq\"." +which sponge &>/dev/null || raiseError notfound "Need to install \"moreutils\"." +# Commands control. +shopt -s extglob +case "$ACCESS" in + root) CMDS='+(help|convert|config|check|list|show|search|download|install|uninstall|get-default|set-default|rebuild|assign)' ;; + web) CMDS='+(list|show|search|get-default)' ;; +esac +case "$1" in + $CMDS) COMMAND="${1/-/}"; shift; $COMMAND "$@" ;; + *) raiseError usage ;; +esac + +exit $? + diff --git a/server/bin/partclone2sync b/server/bin/partclone2sync deleted file mode 100755 index 4272cf06..00000000 --- a/server/bin/partclone2sync +++ /dev/null @@ -1,174 +0,0 @@ -#!/bin/bash -#/** -# partclone2sync -#@brief Convierte imagen de partclone en imagen sincronizable. -#@param 1 imagen partclone. -#@param 2 imagen sincronizable. -#@param 3 tipo de sincronización y formato de la imagen SYNC1 (directorio) y SYNC2 (fichero) -#@exception OG_ERR_FORMAT # 1 formato incorrecto. -#@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado -#@exception OG_ERR_LOCKED # 4 Imagen de partclone bloqueada. -#@exception OG_ERR_IMAGE # 5 Error al crear la imagen. -#@exception OG_CACHESIZE # 16 No hay espacio suficiente en el disco. -#@note Necesita tener instalado partclone-utils y lzop -#@version 1.0 - -#@author Irina Gomez -#@date 2014-01-22 -#*/ ## -trap "onexit \"$1\" \"$2\" $3" 0 5 16 9 15 - -function onexit() { - local exit_status=$? - # Desmontamos el cliente de opengnsys y la imagen temporal. - umount $OGCLIENTDIR/ogclientmount $AUXDIR - rm -rf $IMGINFO $FILEHEAD $TMPLOG - - # Borramos los ficheros de bloqueo de las imagenes nuevas. - rm -rf $RSYNCIMG.img.lock $AUXIMG.lock - # Borramos los ficheros de bloqueo dela imagen de partclone si no estaba bloqueada. - [ $exit_status -eq 4 ] || rm -rf $PARTCLONEIMG.lock - - # Borramos las imagenes y directorios temporales. - rm $AUXIMG - rmdir $AUXDIR $OGCLIENTDIR/ogclientmount - - exit $exit_status -} - -TIME1=$SECONDS - -BASEDIR=/opt/opengnsys -REPODIR="$BASEDIR/images" -BINDIR="$BASEDIR/bin" -PROG="$(basename $0)" -# Cargamos los mensajes en el idioma del sistema. -source $BASEDIR/client/etc/lang.$LANG.conf - -# Sistema de fichero de la imagen según kernel, menor que 3.7 EXT4. comparamos revision -[ $(uname -r|cut -d. -f2) -lt 7 ] && IMGFS="EXT4" || IMGFS="BTRFS" - -# Mostrar ayuda: Si se solicita, si faltan parametros o $3 no es SYNC1 o SYNC2. -if [ "$*" == "help" -o $# -lt 3 ] && ! [[ "$3" == SYNC[1,2] ]]; then - echo -e "$PROG: $MSG_HELP_partclone2sync \n" \ - "$MSG_FORMAT: $PROG image_partclone image_rsync [ SYNC1 | SYNC2 ] \n" \ - " $PROG Windows7 Windows72013 SYNC1 " - exit 0 -fi - -if [ "$USER" != "root" ]; then - echo "$PROG: Error: solo ejecutable por root" >&2 - exit 1 -fi - - -PARTCLONEIMG="$REPODIR/$1.img" -RSYNCIMG="$REPODIR/$2" -AUXIMG="$REPODIR/$1.tmp.img" -AUXDIR="/tmp/partclone2rsync$$" -TYPE="$3" -TMPLOG=/tmp/rsync$$.sal - -# Comprobamos que exista la imagen. -! [ -f $PARTCLONEIMG ] && echo "$MSG_ERR_NOTFOUND: $1" && exit 2 - -# Comprobamos que la imagen no este bloqueada. -[ -f $PARTCLONEIMG.lock ] && echo "$MSG_ERR_LOCKED: $1" && exit 4 - -# Usamos el partclone del ogclient. -OGCLIENTDIR=$BASEDIR/tftpboot/ogclient -[ -d $OGCLIENTDIR/ogclientmount ] || mkdir $OGCLIENTDIR/ogclientmount -mount $OGCLIENTDIR/ogclient.sqfs $OGCLIENTDIR/ogclientmount -PATHPARTCLONE=$OGCLIENTDIR/ogclientmount/usr/sbin - -# Creamos fichero de bloqueo -touch $PARTCLONEIMG.lock $AUXIMG.lock - - -# Datos imagen. -echo [10] Obtenemos datos del partclone. -FILEHEAD=/tmp/$(basename $PARTCLONEIMG).infohead -COMPRESSOR=`file $PARTCLONEIMG | awk '{print $2}'` -$COMPRESSOR -dc $PARTCLONEIMG 2>/dev/null | head > $FILEHEAD -PARTCLONEINFO=$(LC_ALL=C partclone.info $FILEHEAD 2>&1) -if `echo $PARTCLONEINFO | grep size > /dev/null` -then - FS=$(echo $PARTCLONEINFO | awk '{gsub(/\: /,"\n"); print toupper($8);}') - echo $PARTCLONEINFO | grep GB > /dev/null && SIZEFACTOR=1000000 || SIZEFACTOR=1024 - IMGSIZE=$(echo $PARTCLONEINFO | awk -v FACTOR=$SIZEFACTOR '{gsub(/\: /,"\n"); printf "%d\n", $11*FACTOR;}') -else - echo "Error: partclone.info no detecta la imagen" - exit 5 -fi -[ "$FS" == "NTFS" ] && echo "Error: Todavia no podemos convertir imagenes de Windows" && exit 6 - -# Calculamos el espacio disponible en la particion de opengnsys. -echo -n "[20]$MSG_SCRIPTS_CREATE_SIZE " -for DIR in "/" "/opt" "/opt/opengnsys" "/opt/opengnsys/images" -do - AUXSIZE=$(df|grep $DIR$|awk '{print $3}') - [ "$AUXSIZE" != "" ] && PARTSIZE=$AUXSIZE -done -let REQUIRESIZE=2*$IMGSIZE -if [ $PARTSIZE -lt $REQUIRESIZE ]; then - echo "No hay espacio suficiente para descomprimir y crear la imagen: $REQUIRESIZE." - exit 16 -fi -echo "$REQUIRESIZE $PARTSIZE" - -# Descomprimimos la imagen de partclone. -echo [30] Descomprimimos la imagen de partclone. -$COMPRESSOR -dc $PARTCLONEIMG | $PATHPARTCLONE/partclone.restore -C -s - -O $AUXIMG - -TIME2=$[SECONDS-TIME1] -echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME2/60]m $[TIME2%60]s" - -# Montamos la imagen: -mkdir -p $AUXDIR -mount $AUXIMG $AUXDIR - -# Sincronizamos de la imagen del partclone a la del rsync. -echo "[60] Sincronizamos desde la imagen de partclone a la de rsync." -if [ "$TYPE" == "SYNC1" ]; then - mkdir -p $RSYNCIMG - echo " * Log temporal en: $TMPLOG" - echo rsync -aHAX $AUXDIR/ $RSYNCIMG --- log: $TMPLOG - rsync -aHAXv $AUXDIR/ $RSYNCIMG >> $TMPLOG -TIME3=$[SECONDS-TIME2] -echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME3/60]m $[TIME3%60]s" -else - IMGINFO="/tmp/ogimg.info$$" - IMGDIR="$REPODIR/mount/$(basename $RSYNCIMG)" - # Calculamos el tamaño de la imagen - SIZE=$(df -k|awk -v P="$AUXDIR" '{if ($6==P) print $3}') - # Creo fichero de informacion de la imagen - echo "#$FSIMG:LZO:$FS:$SIZE" > $IMGINFO - # Factor de compresion de la imagen - [ "$FS" == "NTFS" ] && ZFACTOR=120 || ZFACTOR=110 - [ "$FSIMG" == "BTRFS" ] && let ZFACTOR=$ZFACTOR-30 - let SIZE=$SIZE*$ZFACTOR/100 - - # Creamos el fichero de la imagen vacio (queda montado) - echo " * $MSG_HELP_ogCreateFileImage" - $BINDIR/createfileimage $(basename $RSYNCIMG) img $SIZE || exit 5 - touch $RSYNCIMG.img.lock - TIME3=$[SECONDS-TIME2] - echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME3/60]m $[TIME3%60]s" - - # Sincronizo las imagenes antigua y nueva. - echo " * Sincroniza las imagenes antigua y nueva. log temporal en: $TMPLOG" - echo rsync -aHAX $AUXDIR/ $IMGDIR - rsync -aHAXv $AUXDIR/ $IMGDIR >> $TMPLOG - TIME4=$[SECONDS-TIME3] - echo " $MSG_SCRIPTS_TASK_END: $MSG_SCRIPTS_TIME_PARTIAL: $[TIME4/60]m $[TIME4%60]s" - # copiamos el fichero de informacion dentro de la imagen. - mv $IMGINFO $IMGDIR/ogimg.info - # Desmontamos la imagen y la reducimos al minimo. - $BINDIR/unmountimage $(basename $RSYNCIMG) img - echo " * $MSG_HELP_ogReduceImage." - rm $RSYNCIMG.img.lock - $BINDIR/reduceimage $(basename $RSYNCIMG) img - -fi - -TIME=$[SECONDS-TIME1] -echo " $MSG_SCRIPTS_END: $MSG_SCRIPTS_TIME_TOTAL: $[TIME/60]m $[TIME%60]s" diff --git a/server/bin/reduceimage b/server/bin/reduceimage deleted file mode 100755 index cb2d2f37..00000000 --- a/server/bin/reduceimage +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash -#/** -# reduceimage -#@brief Reduce el archivo de la imagen a tamaño datos + 500M -#@param 1 imagen -#@param 2 extension [ img|diff ] opcional, por defecto img -#@return -#@exception OG_ERR_FORMAT # 1 formato incorrecto. -#@exception OG_ERR_NOTFOUND # 2 Fichero o dispositivo no encontrado -#@exception OG_ERR_LOCKED # 4 Partición o fichero bloqueado -#@exception OG_ERR_DONTSYNC_IMAGE #71 Imagen no sincronizable (es monolitica) -#@version 1.0 - Reducir tamaño imagen sincronizable -#@author Irina Gomez -#@date 2013-05-23 -#*/ ## -BASEDIR=/opt/opengnsys -REPODIR="$BASEDIR/images" -REPOLOG=$BASEDIR/log/ogAdmRepo.log -source $BASEDIR/client/etc/lang.$LANG.conf - -PROG="$(basename $0)" -# Si se solicita, mostrar ayuda. -if [ "$*" == "help" ]; then - echo -e " $PROG: $MSG_HELP_ogReduceImage \n" \ - "$MSG_FORMAT: $PROG nombre_image [ img|diff ] \n" \ - "base -> $PROG Windows7 \n" \ - "diff -> $PROG Ubuntu12 diff" - exit 0 -fi - -[ $# -lt 1 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ]" && exit 1 - -if [ "$USER" != "root" ]; then - echo "$PROG: Error: solo ejecutable por root" >&2 - exit 1 -fi - -[ "$2" == "" -o "$2" == "img" ] && IMGEXT="img" || IMGEXT="img.diff" -# Comprobamos que existe imagen y que no este bloqueada -IMGFILE="$REPODIR/$1.$IMGEXT" -[ ! -f $IMGFILE ] && echo "$PROG: Error: $MSG_ERR_NOTFOUND $1 $IMGEXT" && exit 2 -[ -f $IMGFILE.lock ] && echo "$PROG: Error: $MSG_ERR_LOCKED $1 $IMGEXT" && exit 4 - -# Comprobar que la imagen es sincronizable -if ! file $IMGFILE | grep -i -e " BTRFS Filesystem " -e " ext4 filesystem " >/dev/null ; then - echo "$PROG: Error: $MSG_ERR_DONTSYNC_IMAGE $1 $2" - exit 71 -fi - -touch $IMGFILE.lock -echo -ne REDUCE_IMAGE "$1" ${IMGEXT#*\.} | /opt/opengnsys/sbin/ogAdmRepoAux -echo "Los resultado se registran en $REPOLOG. " - -rm $IMGFILE.lock diff --git a/server/bin/registeredsoftware b/server/bin/registeredsoftware index 31357dfb..cc78147c 100755 --- a/server/bin/registeredsoftware +++ b/server/bin/registeredsoftware @@ -7,6 +7,9 @@ #@version 1.0 - Creación del script. #@author Ramón Gómez - Univ. Sevilla #@date 2014-02-27 +#@version 1.1.0 - Incluir sistema operativo. +#@author Ramón Gómez - Univ. Sevilla +#@date 2016-06-08 # Variables. @@ -52,12 +55,18 @@ trap "rm -f $MYCNF" 0 1 2 3 6 9 15 # Obtener lista de componentes del perfil de software asociado a la imagen. mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -s -N -e \ - "SELECT softwares.descripcion + "SELECT descr FROM + ((SELECT 1 AS orden, nombresos.nombreso AS descr + FROM perfilessoft + JOIN imagenes USING(idperfilsoft) + JOIN nombresos USING(idnombreso) + WHERE imagenes.nombreca='$RESOURCE') + UNION + (SELECT 2, softwares.descripcion FROM perfilessoft - LEFT OUTER JOIN perfilessoft_softwares ON perfilessoft.idperfilsoft=perfilessoft_softwares.idperfilsoft - LEFT OUTER JOIN softwares ON softwares.idsoftware=perfilessoft_softwares.idsoftware - LEFT OUTER JOIN tiposoftwares ON softwares.idtiposoftware=tiposoftwares.idtiposoftware - LEFT OUTER JOIN imagenes ON perfilessoft.idperfilsoft=imagenes.idperfilsoft - WHERE imagenes.nombreca='$RESOURCE' - ORDER BY tiposoftwares.idtiposoftware,softwares.descripcion;" + JOIN perfilessoft_softwares USING(idperfilsoft) + JOIN softwares USING(idsoftware) + JOIN imagenes USING(idperfilsoft) + WHERE imagenes.nombreca='$RESOURCE')) AS unidas + ORDER BY orden ASC, descr ASC;" diff --git a/server/bin/setclientlive b/server/bin/setclientlive new file mode 100755 index 00000000..3ce417cb --- /dev/null +++ b/server/bin/setclientlive @@ -0,0 +1,73 @@ +#!/bin/bash + +#/** +# setclientlive DirOGLive | IndiceOGLive { NombrePC | NombreAula } Modo_trabajo +#@file setclientlive +#@brief Configura el archivo de arranque de PXE para asignar el cliente ogLive, ya sea a un equipo o a un aula +#@param $1 DirOGLive, IndiceOGLive o "default" (según script "oglivecli") +#@param $2 Ámbito { NombrePC | NombreAula } +#warning No se admiten cambios temporales. +#@version 1.1.0 - Versión inicial basada en script "setclientmode". +#@author Ramón M. Gómez - Univ. Sevilla, junio 2017 +#*/ ## + + +# Variables. +PROG=$(basename "$0") +PATH=$PATH:$(dirname $(realpath "$0")) +OPENGNSYS=${OPENGNSYS:-"/opt/opengnsys"} +SERVERCONF=$OPENGNSYS/etc/ogAdmServer.cfg +TFTPDIR=$OPENGNSYS/tftpboot +LOGFILE=$OPENGNSYS/log/opengnsys.log +MYCNF=/tmp/.my.cnf.$$ + +# Control básico de errores. +if [ $# -ne 2 ]; then + echo "$PROG: Error de ejecución" >&2 + echo "Formato: $PROG {DIR_OGLIVE|INDICE_OGLIVE|default} {NOMBRE_PC|NOMBRE_AULA}" >&2 + exit 1 +fi +if [ ! -r $SERVERCONF ]; then + echo "$PROG: Sin acceso a fichero de configuración" >&2 + exit 2 +fi +case "$1" in + [0-9]*) DIR=$(oglivecli search $1 2>/dev/null) ;; + "default") DIR="ogLive" ;; + *) if oglivecli search "$1" 2>/dev/null; then DIR="$1"; fi ;; +esac +if [ -z "$DIR" ]; then + echo "$PROG: ogLive no ecncontrado, listar ejecutando \"oglivecli list\"" >&2 + exit 1 +fi +if [ ! -e "$TFTPDIR/$DIR" ]; then + echo "$PROG: directorio de ogLive no ecncontrado: \"DIR\"" >&2 + exit 1 +fi + +# Obtener datos de acceso a la Base de datos. +source $SERVERCONF +# Sustituir caracteres ' por \' para evitar inyección SQL. +OGLIVEDIR="${DIR//\'/\'}" +RESOURCE="${2//\'/\'}" +# Componer fichero con credenciales de conexión. +touch $MYCNF +chmod 600 $MYCNF +cat << EOT > $MYCNF +[client] +user=$USUARIO +password=$PASSWORD +EOT +# Borrar el fichero temporal si termina el proceso. +trap "rm -f $MYCNF" 0 1 2 3 6 9 15 +# Actualizar ogLive asignado al aula. +mysql --defaults-extra-file="$MYCNF" -D "$CATALOG" -e \ + "UPDATE aulas SET oglivedir='$OGLIVEDIR' WHERE nombreaula='$RESOURCE';" +# Actualizar ogLive para todos los clientes y reasignar plantilla PXE. +listclientmode "$RESOURCE" | awk -F\" '{print $2,$4}' | \ + while read -r PC BOOTMODE; do + date +"%b %d %T $PROG: Configurando \"$PC\" con cliente \"$OGLIVEDIR\"" | tee -a $LOGFILE + mysql --defaults-extra-file="$MYCNF" -D "$CATALOG" -e \ + "UPDATE ordenadores SET oglivedir='$OGLIVEDIR' WHERE nombreordenador='$PC';" + setclientmode "$BOOTMODE" "$PC" PERM >/dev/null + done diff --git a/server/bin/setclientmode b/server/bin/setclientmode index 98db3630..53ccf26e 100755 --- a/server/bin/setclientmode +++ b/server/bin/setclientmode @@ -1,13 +1,25 @@ #!/bin/bash -# setclientmode: Configura el archivo de arranque de PXE para los clientes, -# ya sea un equipo o un aula, generando enlaces a archivos usados como plantilla. -# Nota: El archivo PXE por defecto "default" se deja en modo de ejecución "user" -# y se eliminan los enlaces para equipos con la plantilla por defecto. -# Uso: clienmode NombrePlatilla { NombrePC | NombreAula } -# Autores: Irina Gomez y Ramon Gomez - Univ. Sevilla, noviembre 2010 + +#/** +# setclientmode NombrePlatilla { NombrePC | NombreAula } Modo_trabajo +#@file setclientmode +#@brief Configura el archivo de arranque de PXE para los clientes, ya sea un equipo o un aula, generando enlaces a archivos usados como plantilla. +#@warning El archivo PXE por defecto "default" se deja en modo de ejecución "user" y se eliminan los enlaces para equipos con la plantilla por defecto. +#@param $1 NombrePlatilla +#@param $2 Ámbito { NombrePC | NombreAula } +#@param $3 Modo_trabajo = { 0, TEMP, 1, PERM } - 0 si es temporal y 1 si es permanente. +#@version 1.0 - Versión inicial. +#@author Irina Gomez y Ramon Gomez - Univ. Sevilla, noviembre 2010 #@version 1.0.1 - Identificacion de la plantilla por nombre en consola = en primera linea de la plantilla -#@author Irina Gomez - Univ. Sevilla -#@date 2013-05-31 +#@author Irina Gomez - Univ. Sevilla +#@date 2013-05-31 +#@version 1.0.2 - Cambio en la funcionalidad del script: el cambio del archivo de arranque PXE puede hacerse de manera temporal (codigo 0) modificando solo el fichero de arranque PXE durante 60 sg. y sin tocar la base de datos o permanente (codigo 1), actualizando tanto el fichero PXE como la base de datos. +#@author Juan Carlos Garcia - Univ. Zaragoza +#@date 2015-11-17 +#@version 1.1.0 - Se incluye la unidad organizativa como parametro del kernel: ogunit=directorio_unidad (ticket #678). +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-12-16 +#*/ ## # Variables. @@ -19,9 +31,9 @@ LOGFILE=$OPENGNSYS/log/opengnsys.log MYCNF=/tmp/.my.cnf.$$ # Control básico de errores. -if [ $# -ne 2 ]; then +if [ $# -ne 3 ]; then echo "$PROG: Error de ejecución" - echo "Formato: $PROG PLANTILLA [NOMBRE_PC|NOMBRE_AULA]" + echo "Formato: $PROG PLANTILLA [NOMBRE_PC|NOMBRE_AULA] MODO" exit 1 fi if [ ! -r $SERVERCONF ]; then @@ -33,6 +45,12 @@ if [ -z "$TEMPLATE" ]; then echo "No existe archivo platilla: $1" exit fi +case "$3" in + 0|TEMP) MODE="TEMP" ;; + 1|PERM) MODE="PERM" ;; + *) echo "$PROG: Modo desconodido: 0, TEMP (temporal), 1, PERM (permanente)" + exit 1 ;; +esac # Obtener datos de acceso a la Base de datos. source $SERVERCONF @@ -61,54 +79,75 @@ if [ -z "$ETHERNET" ]; then fi # Copiar fichero de configuración y actualizar base de datos. -date +"%b %d %T $PROG: Configurando \"$1\" en \"$2\"" | tee -a $LOGFILE +date +"%b %d %T $PROG: Configurando \"$1\" en \"$2\" en modo \"$MODE\"" | tee -a $LOGFILE NPC=0 for MAC in $ETHERNET; do date +"%b %d %T $PROG: Detectada ethernet \"$MAC\" en \"$2\"" | tee -a $LOGFILE - # Si existe anteriormente el fichero PXE, lo borra MACFILE="${MAC^^}" PXEFILE=$PXEDIR/01-${MACFILE:0:2}-${MACFILE:2:2}-${MACFILE:4:2}-${MACFILE:6:2}-${MACFILE:8:2}-${MACFILE:10:2} - rm -f $PXEFILE ${PXEFILE,,} + # Renombra el fichero PXE original + [ -e $PXEFILE ] && mv $PXEFILE $PXEFILE.netboot if [ "$1" != "default" ]; then # Si no está definida la variable LANG, usar idioma inglés por defecto. [ -z "$LANG" -o "$LANG" == "C" ] && LANG="en" # Obtener de la BD los parámetros de arranque asociados (separador es TAB). DATOS=$(mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -s -N -e \ "SELECT ' LANG=$LANG', - ' ip=', CONCAT_WS (':', ordenadores.ip, + ' ip=', CONCAT_WS(':', ordenadores.ip, (@repoip:=repositorios.ip), aulas.router, aulas.netmask, ordenadores.nombreordenador, ordenadores.netiface, 'none'), - ' group=', REPLACE (aulas.nombreaula, ' ', '_'), + ' group=', REPLACE(TRIM(aulas.nombreaula), ' ', '_'), ' ogrepo=', @repoip, ' oglive=', @repoip, ' oglog=', (SELECT (@serverip:=ipserveradm) FROM entornos LIMIT 1), ' ogshare=', @serverip, - ' winboot=', IFNULL (perfileshard.winboot, 'reboot'), - IF (aulas.dns IS NULL, '', CONCAT (' ogdns=', aulas.dns)), - IF (aulas.proxy IS NULL, '', CONCAT (' ogproxy=', aulas.proxy)), + ' oglivedir=', ordenadores.oglivedir, + IF(perfileshard.descripcion<>'', CONCAT(' hardprofile=', REPLACE(TRIM(perfileshard.descripcion), ' ', '_')), ''), + IF(aulas.ntp<>'', CONCAT(' ogntp=', aulas.ntp), ''), + IF(aulas.dns<>'', CONCAT(' ogdns=', aulas.dns), ''), + IF(aulas.proxy<>'', CONCAT(' ogproxy=', aulas.proxy), ''), + IF(entidades.ogunit=1 AND NOT centros.directorio='', CONCAT(' ogunit=', centros.directorio), ''), CASE WHEN menus.resolucion IS NULL THEN '' - WHEN menus.resolucion <= '999' THEN CONCAT (' vga=', menus.resolucion) - WHEN menus.resolucion LIKE '%:%' THEN CONCAT (' video=', menus.resolucion) + WHEN menus.resolucion <= '999' THEN CONCAT(' vga=', menus.resolucion) + WHEN menus.resolucion LIKE '%:%' THEN CONCAT(' video=', menus.resolucion) ELSE menus.resolucion END FROM ordenadores - JOIN aulas USING (idaula) - JOIN repositorios USING (idrepositorio) - LEFT JOIN perfileshard USING (idperfilhard) - LEFT JOIN menus USING (idmenu) + JOIN aulas USING(idaula) + JOIN centros USING(idcentro) + JOIN entidades USING(identidad) + JOIN repositorios USING(idrepositorio) + LEFT JOIN perfileshard USING(idperfilhard) + LEFT JOIN menus USING(idmenu) WHERE ordenadores.mac='$MAC';") # Quitar tabuladores, sustituir acentos y dejar resolución por defecto. - DATOS=$(echo ${DATOS// /} | tr 'áéíóúñÁÉÍÓÚÑ' 'aeiounAEIOUN') + DATOS=$(echo ${DATOS// /} | tr 'áéíóúñçÁÉÍÓÚÑÇ' 'aeiouncAEIOUNC') [[ "$DATOS" =~ (vga|video) ]] || DATOS="$DATOS vga=788" + # Obtener directorio ogLive a partir de los datos. + OGLIVEDIR=$(echo "$DATOS" | awk -F= 'BEGIN {RS=" "} $1=="oglivedir" {print $2}') + # Comprobar si existe "oglivedir" en la plantilla para evitar duplicados. + if grep -q "oglivedir=" $TEMPLATE 2>/dev/null; then + DATOS="${DATOS/oglivedir=$OGLIVEDIR/}" + fi # Crear fichero PXE a partir de la plantilla con los datos obtenidos en la BD. - sed -e "s,vga=[0-9]*,,g; s,INFOHOST,${DATOS//,/\\,},g" $TEMPLATE >$PXEFILE - # Ponemos como propietario al usuario y grupo de Apache para que se pueda cambiar desde la consola web. - PERMS=$(ps axho user,group,comm|awk '!/root/ && /httpd|apache/ {u=$1; g=$2} END {if (g) printf "%s:%s",u,g}') + sed -e "s,vga=[0-9]*,,g; s,INFOHOST,${DATOS//,/\\,},g; s,set ISODIR=.*,set ISODIR=$OGLIVEDIR,g" $TEMPLATE >$PXEFILE + # Ponemos como propietario al usuario y grupo de Apache para que se pueda cambiar desde la consola web. + PERMS=$(ps axho user,group,comm|awk '!/root/ && /httpd|apache/ {u=$1; g=$2} END {if (g) printf "%s:%s",u,g}') [ -n "$PERMS" ] && chown $PERMS $PXEFILE - # Actualizar en la BD la plantilla de arranque asociada el cliente. - mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \ - "UPDATE ordenadores SET arranque='$(basename $TEMPLATE)' WHERE mac='$MAC';" + # Si el modo de trabajo es temporal (0) mete un retardo, restaura el fichero PXE a su estado original y no toca la base de datos + if [ "$MODE" == "TEMP" ]; then + sleep 60 + rm $PXEFILE + [ -e $PXEFILE.netboot ] && mv $PXEFILE.netboot $PXEFILE + fi + + # Si el modo de trabajo es permanente (1) borra el fichero PXE.netboot si existe y graba los datos en la base de datos + if [ "$MODE" == "PERM" ]; then + [ -e $PXEFILE.netboot ] && rm $PXEFILE.netboot + mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \ + "UPDATE ordenadores SET arranque='$(basename $TEMPLATE)' WHERE mac='$MAC';" + fi fi let NPC=NPC+1 done diff --git a/server/bin/setserveraddr b/server/bin/setserveraddr index 5ac10c06..bdcfb796 100755 --- a/server/bin/setserveraddr +++ b/server/bin/setserveraddr @@ -77,7 +77,7 @@ if [ -n "$SERVERIP" ]; then # Comprobar si hay que modificar la configuración de OpenGnsys. CHANGE=0 - # Procesar los ficheros de configuración de OpenGnSys. + # Procesar los ficheros de configuración de OpenGnsys. for f in $OPENGNSYS/{etc/{ogAdmServer,ogAdmRepo,ogAdmAgent}.cfg,www/controlacceso.php,client/etc/ogAdmClient.cfg}; do # Error si no existe algún fichero de configuración. if [ ! -f $f ]; then @@ -101,7 +101,7 @@ if [ -n "$SERVERIP" ]; then fi done - # Si ha cambiado la configuración, reiniciar OpenGnSys y actualizar la BD. + # Si ha cambiado la configuración, reiniciar OpenGnsys y actualizar la BD. if [ $CHANGE == 1 ]; then /etc/init.d/opengnsys restart source $OPENGNSYS/etc/ogAdmServer.cfg diff --git a/server/bin/setsmbpass b/server/bin/setsmbpass index 82d7ce46..2162b3be 100755 --- a/server/bin/setsmbpass +++ b/server/bin/setsmbpass @@ -1,61 +1,86 @@ #!/bin/bash -# setsmbpass: cambia la contraseña del usuario del cliente para acceder a los -# servicios Samba. -# Nota: se modifica el Initrd del cliente y se cambia la clave en el servidor. -# Nota: no se modifica el usuario de acceso (usuario "opengnsys"). -# Uso: setsmbpass -# Autor: Ramon Gomez - Univ. Sevilla, julio 2011 + +#/** +# setsmbpass +#@file setsmbpass [ogLive] +#@brief Cambia la contraseña del usuario del cliente para acceder a los servicios Samba. +#@warning Se modifica el Initrd del cliente y se cambia la clave en el servidor. +#@warning No se modifica el usuario de acceso (usuario "opengnsys"). +#@version 1.0.2 - Versión inicial. +#@author Ramón M. Gómez - ETSII Univ. Sevilla +#@date 2011-07-28 +#@version 1.1.0 - Soporte para varios clientes ogLive. +#@author Ramón M. Gómez - ETSII Univ. Sevilla +#@date 2017-06-20 +#*/ ## # Variables. -PROG=$(basename $0) +PROG=$(basename "$0") +PATH=$PATH:$(dirname "$(realpath "$0")") OPENGNSYS=${OPENGNSYS:-"/opt/opengnsys"} SAMBAUSER="opengnsys" # Usuario por defecto. TFTPDIR=$OPENGNSYS/tftpboot -CLIENTINITRD=$TFTPDIR/ogclient/oginitrd.img -TMPDIR=/tmp/ogclient$$ +INITRD=oginitrd.img +TMPDIR=/tmp/oglive$$ +let CHANGES=0 # Control básico de errores. -if [ $# != 0 ]; then - echo "$PROG: Error de ejecución" >&2 - echo "Formato: $PROG" - exit 1 -fi if [ "$USER" != "root" ]; then - echo "$PROG: Error: solo ejecutable por root" >&2 - exit 1 + echo "$PROG: Error: solo ejecutable por root" >&2 + exit 1 fi +case $# in + 0) # Cambios en todos los clientes ogLive instalados. + if which oglivecli &>/dev/null; then + LIST=$(oglivecli list | awk '{print $2}') + else + LIST="ogclient" + fi ;; + 1) # Cambios en único ogLive (AVISO: puede crear inconsistencias con otros ogLive). + LIST="$1" ;; + *) # Error de formato. + echo "$PROG: Error de ejecución" >&2 + echo "Formato: $PROG ogLive" + exit 1 ;; +esac -# Crear clave para usuario de acceso a los recursos. -if [ -r $CLIENTINITRD ]; then - # Recuperar eco de consola si se corta el proceso. - trap "stty echo 2>/dev/null" KILL - # Obtener clave del teclado sin eco en pantalla. - stty -echo 2>/dev/null - echo -n "Clave del usuario Samba: " - read SAMBAPASS - # Solo se deben aceptar números y letras para la clave de acceso. - if [[ "$SAMBAPASS" =~ [^a-zA-Z0-9] ]]; then +# Recuperar eco de consola si se corta el proceso. +trap "stty echo 2>/dev/null" KILL +# Buscar todos los clients ogLive instalados. +for OGLIVE in $LIST; do + # Crear clave para usuario de acceso a los recursos. + CLIENTINITRD="$TFTPDIR/$OGLIVE/$INITRD" + if [ -r "$CLIENTINITRD" ]; then + if [ -z "$SAMBAPASS" ]; then + # Obtener clave del teclado sin eco en pantalla. + stty -echo 2>/dev/null + echo -n "Clave del usuario Samba: " + read -r SAMBAPASS + # Solo se deben aceptar números y letras para la clave de acceso. + if [[ "$SAMBAPASS" =~ [^a-zA-Z0-9] ]]; then echo echo "$PROG: Error: la clave solo debe contener caracteres alfanuméricos" >&2 stty echo 2>/dev/null exit 2 - fi - echo - # Obtener confirmación clave sin eco en pantalla. - echo -n "Confirmar clave: " - read SAMBAPASS2 - echo - stty echo 2>/dev/null - if [ "$SAMBAPASS" != "$SAMBAPASS2" ]; then + fi + echo + # Obtener confirmación clave sin eco en pantalla. + echo -n "Confirmar clave: " + read -r SAMBAPASS2 + echo + stty echo 2>/dev/null + if [ "$SAMBAPASS" != "$SAMBAPASS2" ]; then echo "$PROG: Error: las claves no coinciden" >&2 exit 2 + fi fi # Editar la parte de acceso del cliente: # descomprimir Initrd, sustituir clave y recomprimir Initrd). + echo "Configurando cliente \"$OGLIVE\" ..." mkdir -p $TMPDIR - cd $TMPDIR - gzip -dc $CLIENTINITRD | cpio -im + cd $TMPDIR || exit 3 + gzip -dc "$CLIENTINITRD" | cpio -im if [ -f scripts/ogfunctions ]; then sed -i "s/OPTIONS=\(.*\)user=\w*\(.*\)pass=\w*\(.*\)/OPTIONS=\1user=$SAMBAUSER\2pass=$SAMBAPASS\3/" scripts/ogfunctions # TEMPORAL: solución ticket 554, actualizar cliente en caché (ogLive r3257). @@ -66,21 +91,26 @@ if [ -r $CLIENTINITRD ]; then chown root.root scripts/passrsync chmod 400 scripts/passrsync # Generar Initrd del cliente. - find . | cpio -H newc -oa | gzip -9c > $CLIENTINITRD - # Ticket 565, preparar acceso Rsync servidor. - echo "$SAMBAUSER:$SAMBAPASS" > /etc/rsyncd.secrets - chown root.root /etc/rsyncd.secrets - chmod 600 /etc/rsyncd.secrets + find . | cpio -H newc -oa | gzip -9c > "$CLIENTINITRD" else - echo "$PROG: Aviso: no se ha modificado la clave del cliente." + echo "$PROG: Aviso: no se ha modificado la clave del cliente \"$OGLIVE\"." fi rm -fr $TMPDIR - md5sum $CLIENTINITRD | cut -f1 -d" " > $CLIENTINITRD.sum - cp -a $CLIENTINITRD $TFTPDIR - cp -a $CLIENTINITRD.sum $TFTPDIR + # Calcular suma de comprobación. + md5sum "$CLIENTINITRD" | cut -f1 -d" " > "$CLIENTINITRD.sum" + let CHANGES++ + else + echo "$PROG: Cliente \"$OGLIVE\" no accesible." + fi +done +if [[ $CHANGES != 0 ]]; then + # Ticket 565, preparar acceso Rsync servidor. + echo "$SAMBAUSER:$SAMBAPASS" > /etc/rsyncd.secrets + chown root.root /etc/rsyncd.secrets + chmod 600 /etc/rsyncd.secrets + # Cambiar clave Samba. + echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | smbpasswd -a -s $SAMBAUSER else - SAMBAPASS="og" # Clave por defecto. - echo "$PROG: Aviso: no se ha modificado la clave del cliente." + echo "$PROG: Aviso: no se ha modificado la clave de ningún cliente." fi -echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | smbpasswd -a -s $SAMBAUSER diff --git a/server/bin/unmountimage b/server/bin/unmountimage deleted file mode 100755 index 812fbdd4..00000000 --- a/server/bin/unmountimage +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -#/** -# unmountimage -#@brief Desmonta imagen sincronizable -#@param 1 imagen -#@param 2 extension [ img|diff ] opcional, por defecto img -#@return -#@exception OG_ERR_FORMAT # 1 formato incorrecto. -#@version 1.0 - Desmontar imagen sincronizable -#@author Irina Gomez -#@date 2013-05-23 -#*/ ## -BASEDIR=/opt/opengnsys -REPODIR="$BASEDIR/images" -REPOLOG=$BASEDIR/log/ogAdmRepo.log -source $BASEDIR/client/etc/lang.$LANG.conf - -PROG="$(basename $0)" -# Si se solicita, mostrar ayuda. -if [ "$*" == "help" ]; then - echo -e " $PROG: $MSG_HELP_ogUnmountImage \n" \ - "$MSG_FORMAT: $PROG nombre_image [ img|diff ] \n" \ - "base -> $PROG Windows7 \n" \ - "diff -> $PROG Ubuntu12 diff" - exit 0 -fi - -[ $# -lt 1 ] && echo -e "$PROG: Error: $MSG_ERR_FORMAT \n $MSG_FORMAT: $PROG image [ img | diff ]" && exit 1 - -if [ "$USER" != "root" ]; then - echo "$PROG: Error: solo ejecutable por root" >&2 - exit 1 -fi - -# Comprobamos que imagen la imagen esta montada -MOUNTDIR="$REPODIR/mount/$1" -if [ "$2" == "diff" ]; then - IMGEXT="diff" - MOUNTDIR="$MOUNTDIR.diff" -else - IMGEXT="img" -fi -# Si la imaen no está montada me salgo -df |grep "$MOUNTDIR$" 2>&1 >/dev/null || exit 0 - -echo -ne UMOUNT_IMAGE "$1" $IMGEXT | /opt/opengnsys/sbin/ogAdmRepoAux -echo "Los resultado se registran en $REPOLOG. " diff --git a/server/etc/apache-prev2.4.conf.tmpl b/server/etc/apache-prev2.4.conf.tmpl index 474ea62a..304e3b2c 100644 --- a/server/etc/apache-prev2.4.conf.tmpl +++ b/server/etc/apache-prev2.4.conf.tmpl @@ -1,12 +1,22 @@ -# OpenGnSys Web Console template configuration for Apache. +# OpenGnsys Web Console template configuration for Apache. Alias /opengnsys CONSOLEDIR -# Overrides default CentOS php.ini configuration. -php_value short_open_tag on +RewriteEngine On +# Redirect HTTP to HTTPS and default configuration. + RewriteCond %{HTTPS} !=on + RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R] Options -Indexes FollowSymLinks DirectoryIndex index.php + AddType octet/stream .pkg + +# Redirect HTTP to HTTPS and RESTful configuration. + + RewriteBase /opengnsys/rest/ + RewriteCond %{HTTPS} !=on + RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R] + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^ index.php [QSA,L] - diff --git a/server/etc/apache.conf.tmpl b/server/etc/apache.conf.tmpl index 5613bf11..ab49503d 100644 --- a/server/etc/apache.conf.tmpl +++ b/server/etc/apache.conf.tmpl @@ -1,13 +1,25 @@ -# OpenGnSys Web Console template configuration for Apache. +# OpenGnsys Web Admin Console template configuration for Apache. Alias /opengnsys CONSOLEDIR -# Overrides default CentOS php.ini configuration. -php_value short_open_tag on +RewriteEngine On +# Redirect HTTP to HTTPS and default configuration. + RewriteCond %{HTTPS} !=on + RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R] Require all granted Options -Indexes +FollowSymLinks DirectoryIndex index.php + AddType octet/stream .pkg +# Redirect HTTP to HTTPS and RESTful configuration. + + RewriteBase /opengnsys/rest/ + RewriteRule .? - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] + RewriteCond %{HTTPS} !=on + RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R] + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^ index.php [QSA,L] + diff --git a/server/etc/dhcpd.conf.tmpl b/server/etc/dhcpd.conf.tmpl index fb6afa00..a80b42db 100644 --- a/server/etc/dhcpd.conf.tmpl +++ b/server/etc/dhcpd.conf.tmpl @@ -13,10 +13,21 @@ subnet NETIP netmask NETMASK { filename "grldr"; use-host-decl-names on; +# Ejemplo para PC. # host HOSTNAME1 { # hardware ethernet HOSTMAC1; # fixed-address HOSTIP1; # } +# Ejemplo para Mac. +# group { +# option tftp-server-name="SERVERIP"; +# option bootfile-name "grldr"; +# host MACOSHOST1 { +# hardware ethernet MACOSHOSTMAC1; +# fixed-address MACOSHOSTIP1; +# } +# } + } diff --git a/server/etc/smb-og.conf.tmpl b/server/etc/smb-og.conf.tmpl index 3ce6baad..8975a478 100644 --- a/server/etc/smb-og.conf.tmpl +++ b/server/etc/smb-og.conf.tmpl @@ -1,12 +1,12 @@ [tftpboot] - comment = OpenGnSys init files + comment = OpenGnsys init files browseable = no writeable = no path = OPENGNSYSDIR/tftpboot guest ok = no [ogclient] - comment = OpenGnSys Client + comment = OpenGnsys Client browseable = no writeable = no locking = no @@ -14,14 +14,14 @@ guest ok = no [oglog] - comment = OpenGnSys Log + comment = OpenGnsys Log browseable = no writeable = yes path = OPENGNSYSDIR/log/clients guest ok = no [ogimages] - comment = OpenGnSys Repository + comment = OpenGnsys Repository browseable = no writeable = yes locking = no diff --git a/server/lib/security-config b/server/lib/security-config new file mode 100755 index 00000000..eb8bf5cf --- /dev/null +++ b/server/lib/security-config @@ -0,0 +1,86 @@ +#!/bin/bash +#/** +#@file security-config +#@brief OpenGnsys Server security configuration. +#@note Security configuration tipsx for UFW, FirewallD and SELinux. +#@version 1.1.0 - Initial version. +#@author Ramón M. Gómez, ETSII Univ. Sevilla +#@date 2016-04-18 +#*/ ## + + +# Variables. +PROG=$(basename "$0") +OPENGNSYS=/opt/opengnsys +# Errors control. +if [ "$USER" != "root" ]; then + echo "$PROG: Need to be root." >&2 + exit 1 +fi + +# UFW configuration. +if which ufw 2>/dev/null; then + # Adding active services. + ufw allow "Apache Secure" + ufw allow OpenSSH + ufw allow Samba + ufw allow mysql + ufw allow rsync + ufw allow tftp + ufw allow 67,68/udp # DHCP + ufw allow 2002,2008/tcp # OpenGnsys services + ufw allow 9000:9051/udp # Multicast + ufw allow 6881:6999/udp # BitTorrent + # Applying configuration. + ufw enable +# FirewallD configuration. +elif which firewall-cmd 2>/dev/null; then + # Defining OpenGnsys services. + python -c " +import firewall.core.io.service as ios +s=ios.Service() +s.short = 'OpenGnsys Server' +s.name = 'ogAdmServer' +s.ports = [('2008', 'tcp')] +ios.service_writer(s, '/etc/firewalld/services') +s.short = 'OpenGnsys Repository' +s.name = 'ogAdmRepo' +s.ports = [('2002', 'tcp')] +ios.service_writer(s, '/etc/firewalld/services')" + # Adding active services. + firewall-cmd --permanent --add-service=dhcp + firewall-cmd --permanent --add-service=https + firewall-cmd --permanent --add-service=mysql --zone internal + firewall-cmd --permanent --add-service=ogAdmRepo + firewall-cmd --permanent --add-service=ogAdmServer + # Ubuntu 14.04 does not define "rsyncd" service. + firewall-cmd --permanent --add-service=rsyncd || \ + firewall-cmd --permanent --add-port=873/tcp + firewall-cmd --permanent --add-service=samba + firewall-cmd --permanent --add-service=ssh + firewall-cmd --permanent --add-service=tftp + # Adding Multicast ports. + firewall-cmd --permanent --add-port=9000-9051/udp + # Adding BitTorent ports. + firewall-cmd --permanent --add-port=6881-6999/udp + # Applying configuration. + firewall-cmd --reload +else + echo "$PROG: Warning: Firewall won't be configured (neither ufw or firewalld are installed)." +fi + +# SELinux configuration. +if which setsebool 2>/dev/null; then + # Configuring Apache. + setsebool -P httpd_can_connect_ldap on + semanage fcontext -at httpd_sys_content_t "$OPENGNSYS/www(/.*)?" + # Configuring Samba. + setsebool -P samba_export_all_ro=1 samba_export_all_rw=1 + semanage fcontext -at samba_share_t "$OPENGNSYS/client(/.*)?" + semanage fcontext -at samba_share_t "$OPENGNSYS/images(/.*)?" + # Applying configuration. + restorecon -R $OPENGNSYS +else + echo "$PROG: Warning: SELinux won't be configured (policycoreutils is not installed)." +fi + diff --git a/server/tftpboot/NetbootPXE.es.txt b/server/tftpboot/NetbootPXE.es.txt index b963d50b..a1c7c8ad 100644 --- a/server/tftpboot/NetbootPXE.es.txt +++ b/server/tftpboot/NetbootPXE.es.txt @@ -2,9 +2,9 @@ Notas sobre arranque remoto de los clientes =========================================== -Desde la versión OpenGnSys 1.0.2 se utiliza Grub4Dos como gestor de arranque en sustitución de PXELinux. +Desde la versión OpenGnsys 1.0.2 se utiliza Grub4Dos como gestor de arranque en sustitución de PXELinux. -El instalador de OpenGnSys configura por defecto el servicio DHCP para usar el fichero "grldr" como gestor PXE, incluyendo la siguiente cláusula que debe ser común a todos los equipos afectados: +El instalador de OpenGnsys configura por defecto el servicio DHCP para usar el fichero "grldr" como gestor PXE, incluyendo la siguiente cláusula que debe ser común a todos los equipos afectados: filename "grldr"; @@ -34,13 +34,13 @@ No olvidar reiniciar el servicio DHCP tras cada modificación de su fichero de c Como cambiar el arranque en red PXELinux por Grub4DOS ===================================================== -NOTA: la siguiente información está anticuada y es válido solo para versiones anteriores a OpenGnSys 1.0.2. +NOTA: la siguiente información está anticuada y es válido solo para versiones anteriores a OpenGnsys 1.0.2. -OpenGnSys 1.0.1 usa como gestor PXE el binario pxelinux.0, sin embargo, la actulización a OpenGnSys 1.0.2 sustituye automáticamente dicho gestor por Grub4Dos. +OpenGnsys 1.0.1 usa como gestor PXE el binario pxelinux.0, sin embargo, la actulización a OpenGnsys 1.0.2 sustituye automáticamente dicho gestor por Grub4Dos. -Realizar los siguientes pasos para sutituir "a mano" PXELinux por Grub4Dos como gestor de arranque sin usar el proceso de actualización de OpenGnSys. +Realizar los siguientes pasos para sutituir "a mano" PXELinux por Grub4Dos como gestor de arranque sin usar el proceso de actualización de OpenGnsys. Activar el grldr del grub4dos diff --git a/server/tftpboot/menu.lst/templates/00unknown b/server/tftpboot/menu.lst/templates/00unknown index e52ffa82..eaf70de7 100644 --- a/server/tftpboot/menu.lst/templates/00unknown +++ b/server/tftpboot/menu.lst/templates/00unknown @@ -1,7 +1,6 @@ ##NO-TOCAR-ESTA-LINEA Sin-designar timeout 1 title MBR -keeppxe chainloader (hd0)+1 rootnoverify (hd0) boot \ No newline at end of file diff --git a/server/tftpboot/menu.lst/templates/01 b/server/tftpboot/menu.lst/templates/01 index 1b52bb54..db7a3ee7 100644 --- a/server/tftpboot/menu.lst/templates/01 +++ b/server/tftpboot/menu.lst/templates/01 @@ -1,7 +1,6 @@ ##NO-TOCAR-ESTA-LINEA MBR timeout 1 title MBR -keeppxe chainloader (hd0)+1 rootnoverify (hd0) boot diff --git a/server/tftpboot/menu.lst/templates/11 b/server/tftpboot/menu.lst/templates/11 index 92be0dca..6ff6b10b 100644 --- a/server/tftpboot/menu.lst/templates/11 +++ b/server/tftpboot/menu.lst/templates/11 @@ -1,7 +1,6 @@ ##NO-TOCAR-ESTA-LINEA 1hd-1partition timeout 1 title FirstHardDisk-FirstPartition -keeppxe root (hd0,0) chainloader (hd0,0)+1 boot diff --git a/server/tftpboot/menu.lst/templates/12 b/server/tftpboot/menu.lst/templates/12 index 6f46c742..0843c3b1 100644 --- a/server/tftpboot/menu.lst/templates/12 +++ b/server/tftpboot/menu.lst/templates/12 @@ -1,7 +1,6 @@ ##NO-TOCAR-ESTA-LINEA 1hd-2partition timeout 1 title FirstHardDisk-SecondPartition -keeppxe root (hd0,1) chainloader (hd0,1)+1 boot diff --git a/server/tftpboot/menu.lst/templates/19pxeADMIN b/server/tftpboot/menu.lst/templates/19pxeADMIN index f9f3246f..c2a6e4ba 100644 --- a/server/tftpboot/menu.lst/templates/19pxeADMIN +++ b/server/tftpboot/menu.lst/templates/19pxeADMIN @@ -1,13 +1,20 @@ -##NO-TOCAR-ESTA-LINEA ogAdmin +##NO-TOCAR-ESTA-LINEA ogLiveAdmin default saved timeout 1 hiddenmenu fallback 1 2 3 -title OpenGnSys-NET -keeppxe -kernel (pd)/ogclient/ogvmlinuz ro boot=oginit vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=true ogdebug=true ogupdateinitrd=true INFOHOST -initrd (pd)/ogclient/oginitrd.img +set ISODIR=ogLive + +title OpenGnsys-NET +kernel (pd)/%ISODIR%/ogvmlinuz ro boot=oginit quiet splash vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=true ogdebug=true ogupdateinitrd=true ogtmpfs=15 oglivedir=%ISODIR% INFOHOST +initrd (pd)/%ISODIR%/oginitrd.img +boot + + +title OpenGnsys-NET default +kernel (pd)/ogLive/ogvmlinuz ro boot=oginit vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=true ogdebug=true ogupdateinitrd=true ogtmpfs=15 oglivedir=ogLive INFOHOST +initrd (pd)/ogLive/oginitrd.img boot diff --git a/server/tftpboot/menu.lst/templates/pxe b/server/tftpboot/menu.lst/templates/pxe index 6abbed39..bdf0fc54 100644 --- a/server/tftpboot/menu.lst/templates/pxe +++ b/server/tftpboot/menu.lst/templates/pxe @@ -1,15 +1,17 @@ -##NO-TOCAR-ESTA-LINEA ogClient +##NO-TOCAR-ESTA-LINEA ogLive default saved timeout 1 hiddenmenu -fallback 1 2 3 +fallback 1 2 3 4 + +set ISODIR=ogLive + title firsboot find --set-root --ignore-floppies --ignore-cd /ogboot.me cmp /ogboot.me /ogboot.firstboot || ls FALLBACK write /ogboot.firstboot iniciado chainloader +1 -savedefault fallback boot title secondboot @@ -17,23 +19,20 @@ find --set-root --ignore-floppies --ignore-cd /ogboot.me cmp /ogboot.me /ogboot.secondboot || ls FALLBACK write /ogboot.secondboot iniciado chainloader +1 -savedefault fallback boot title OpenGnsys-CACHE -find --set-root --ignore-floppies --ignore-cd /boot/ogvmlinuz -kernel /boot/ogvmlinuz ro boot=oginit quiet splash vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=false ogdebug=false ogupdateinitrd=true INFOHOST -initrd /boot/oginitrd.img -savedefault fallback +find --set-root --ignore-floppies --ignore-cd /boot/%ISODIR%/ogvmlinuz +kernel /boot/%ISODIR%/ogvmlinuz ro boot=oginit quiet splash vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=false ogdebug=false ogupdateinitrd=true ogtmpfs=15 oglivedir=%ISODIR% INFOHOST +initrd /boot/%ISODIR%/oginitrd.img boot title OpenGnsys-NET -keeppxe -kernel (pd)/ogclient/ogvmlinuz ro boot=oginit quiet splash vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=false ogdebug=false INFOHOST -initrd (pd)/ogclient/oginitrd.img +kernel (pd)/%ISODIR%/ogvmlinuz ro boot=oginit quiet splash vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=false ogdebug=false ogtmpfs=15 oglivedir=%ISODIR% INFOHOST +initrd (pd)/%ISODIR%/oginitrd.img boot - - - - +title OpenGnsys-NET default +kernel (pd)/ogLive/ogvmlinuz ro boot=oginit oglivedir=ogLive quiet splash vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=false ogdebug=false ogtmpfs=15 oglivedir=ogLive INFOHOST +initrd (pd)/ogLive/oginitrd.img +boot -- cgit v1.2.3-18-g5258
   A