diff --git a/CHANGELOG.md b/CHANGELOG.md index c45ab03..fbb8d51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,158 +1,7 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [0.8.0] - 2025-04-23 - -### Added - -- Have the oglive agent send /stopped on poweroff or restart - -## [0.7.2] - 2025-04-21 - -### Fixed - -- Have the partitioning functions return a meaningful rc - -## [0.7.1] - 2025-04-15 - -### Fixed - -- getConfiguration.py: don't fail if NTFS filesystems are mounted ro - -## [0.7.0] - 2025-04-15 - -### Removed - -- Removed references to ogGlobals.OGLOG in python code - -## [0.6.1] - 2025-04-15 - -### Fixed - -- Fixed capturing of partclone output and management of return value - -## [0.6.0] - 2025-04-15 - -### Changed - -- ogGetIpAddress() is no longer required in ogGlobals--move it back into NetLib - -## [0.5.0] - 2025-04-15 - -### Changed - -- Log to /var/log/clone-engine.log and clone-engine.json.log - -## [0.4.1] - 2025-04-10 - -### Fixed - -- restoreImage.py: return negated rc to the shell - -## [0.4.0] - 2025-04-10 - -### Changed - -- Make /opt/opengnsys writable in clients, just like it used to be - -## [0.3.6] - 2025-04-09 - -### Fixed - -- Fixed ogReduceFs - -## [0.3.5] - 2025-04-09 - -### Fixed - -- Fixed syntax - -## [0.3.4] - 2025-04-09 - -### Fixed - -- Fixed usage of ogEcho in FileSystemLib - -## [0.3.3] - 2025-04-09 - -### Fixed - -- Kill coproc'ed browser in all execution branches in Configurar.py - -## [0.3.2] - 2025-04-07 - -### Fixed - -- Handle invalid number of arguments pass to functions/ogCopyFile - -## [0.3.1] - 2025-04-03 - -### Fixed - -- Fixed invocation to ogCheckIpAddress in interfaceAdm/CrearImagen.py - -## [0.3.0] - 2025-04-03 - -### Removed - -- Removed burg and rsync 3.1 - -## [0.2.6] - 2025-03-31 - -### Fixed - -- Restore qt4 browser - -## [0.2.5] - 2025-03-31 - -### Fixed - -- Don't require protoopts in interfaceAdm/RestaurarImagen.py - -## [0.2.4] - 2025-03-28 - -### Removed - -- Removed burg, QT4 stuff, rsync 3.1 and the old browser - -## [0.2.3] - 2025-03-28 - -### Fixed - -- Fixed some errors in Configurar.py, ogCreateCache, ogCreatePartitions and initCache.py - -## [0.2.2] - 2025-03-26 - -### Fixed - -- Prevent EjecutarScript.py from capturing the output of the script - -## [0.2.1] - 2025-03-26 - -### Fixed - -- Run scripts with bash to avoid errno 8 "Exec format error" - -## [0.2.0] - 2025-03-25 - -### Added - -- getConfiguration.py now collects the firmware type -- Configurar.py now creates partition tables of the right type (MSDOS/GPT) for each machine - -## [0.1.1] - 2025-03-19 - -### Added - -- Missing functions in BootLib -- Some interfaceAdm python scripts - +# Changelog ## [0.1.0] - 2025-02-28 -### Added +### Addded - Merge pull request 'Include all client files, build debian package' (#2) from deb-package into main + diff --git a/Jenkins/Jenkinsfile-deb-pkg b/Jenkins/Jenkinsfile-deb-pkg index 157ae91..59886e4 100644 --- a/Jenkins/Jenkinsfile-deb-pkg +++ b/Jenkins/Jenkinsfile-deb-pkg @@ -19,7 +19,7 @@ pipeline { stage('Prepare Workspace') { steps { script { - env.BUILD_DIR = "${WORKSPACE}/ogclient" + env.BUILD_DIR = "${WORKSPACE}/oggui" sh "mkdir -p ${env.BUILD_DIR}" } } @@ -48,50 +48,16 @@ pipeline { } } } - stage('Generate Changelog (Nightly)'){ - when { - branch 'main' - } - steps { - script { - def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME - def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL - generateDebianChangelog(env.BUILD_DIR, devName, devEmail,"nightly") - } - } - } + stage('Build') { steps { - script { - construirPaquete(env.BUILD_DIR, "../artifacts", "172.17.8.68", "/var/tmp/opengnsys/debian-repo/ogclient") - } - } - } - stage ('Publish to Debian Repository') { - when { - expression { - return env.TAG_NAME != null - } - } - agent { label 'debian-repo' } - steps { - script { - // Construir el patrón de versión esperado en el nombre del paquete - def versionPattern = "${env.TAG_NAME}-${env.BUILD_NUMBER}" - publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogclient', 'opengnsys-devel', versionPattern) - } - } - } - stage ('Publish to Debian Repository (Nightly)') { - when { - branch 'main' - } - agent { label 'debian-repo' } - steps { - script { - // Construir el patrón de versión esperado en el nombre del paquete - def versionPattern = "-${env.BUILD_NUMBER}~nightly" - publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogclient', 'nightly', versionPattern) + dir("${env.BUILD_DIR}") { + sh ''' + dpkg-buildpackage -us -uc + mkdir -p ../artifacts && mv ../*.deb ../*.changes ../*.buildinfo ../artifacts/ + ssh aptly@172.17.8.68 "rm -rf /var/tmp/opengnsys/debian-repo && mkdir -p /var/tmp/opengnsys/debian-repo" + scp -r ../artifacts/* aptly@172.17.8.68:/var/tmp/opengnsys/debian-repo/ + ''' } } } @@ -102,4 +68,10 @@ pipeline { } } } +// stage ('Publish to Debian Repository') { +// agent { label 'debian-repo' } +// steps { +// sh "aptly repo add opengnsys-devel /var/tmp/opengnsys/debian-repo/*.deb" +// } +// } diff --git a/debian/ogclient.postinst b/debian/ogclient.postinst index fd0d089..e99fef5 100644 --- a/debian/ogclient.postinst +++ b/debian/ogclient.postinst @@ -23,7 +23,13 @@ case "$1" in cp -a "$OLD_FILE" "$NEW_FILE" # Append our configuration - echo "include = /etc/samba/smb-ogclient.conf" >> "$OLD_FILE" + echo "include = /etc/samba/smb-ogclient.conf" >> "$NEW_FILE" + + # Use ucf to handle the file update + ucf --debconf-ok "$NEW_FILE" "$OLD_FILE" + + # Clean up + rm -f "$NEW_FILE" # Reload Samba if command -v systemctl >/dev/null 2>&1; then @@ -42,8 +48,6 @@ case "$1" in ;; esac -chown -R opengnsys:opengnsys /opt/opengnsys/ogclient -chown -R opengnsys:opengnsys /opt/opengnsys/ogclient_log #DEBHELPER# exit 0 diff --git a/debian/ogclient.preinst b/debian/ogclient.preinst deleted file mode 100644 index 0761132..0000000 --- a/debian/ogclient.preinst +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -set -e - -# Asegurarse de que el usuario exista -USER="opengnsys" -HOME_DIR="/opt/opengnsys" -if id "$USER" &>/dev/null; then - echo "El usuario $USER ya existe." -else - echo "Creando el usuario $USER con home en $HOME_DIR." - useradd -m -d "$HOME_DIR" -s /bin/bash "$USER" -fi - -exit 0 diff --git a/etc/samba/smb-ogclient.conf b/etc/samba/smb-ogclient.conf index 34d5496..a7c3422 100644 --- a/etc/samba/smb-ogclient.conf +++ b/etc/samba/smb-ogclient.conf @@ -1,7 +1,7 @@ [ogclient] comment = OpenGnsys Client browseable = no - writeable = yes + writeable = no locking = no path = /opt/opengnsys/ogclient guest ok = no diff --git a/ogclient/bin/rsync-31 b/ogclient/bin/rsync-31 new file mode 100755 index 0000000..366204f Binary files /dev/null and b/ogclient/bin/rsync-31 differ diff --git a/ogclient/functions/ogBoot b/ogclient/functions/ogBoot deleted file mode 100755 index 23756c1..0000000 --- a/ogclient/functions/ogBoot +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogBoot - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBoot', 'ogBoot int_ndisk int_nfilesys [ NVRAMPERM ] [str_kernel str_initrd str_kernelparams]', ['ogBoot 1 2 "/boot/vmlinuz /boot/initrd.img root=/dev/sda2 ro"', 'ogBoot 1 2 NVRAMPERM']) - sys.exit (0) - -parser = argparse.ArgumentParser (add_help=False) -if 3 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') -elif 4 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') - parser.add_argument ('nvramperm_or_params') -elif 5 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') - parser.add_argument ('nvramperm') - parser.add_argument ('params') - -args = parser.parse_args() - -if 3 == len (sys.argv): - ret = ogBoot (args.disk, args.par) -elif 4 == len (sys.argv): - if 'NVRAMPERM' == args.nvramperm_or_params.upper(): - nvramperm = True - params = '' - else: - nvramperm = False - params = args.nvramperm_or_params - ret = ogBoot (args.disk, args.par, nvramperm, params) -elif 5 == len (sys.argv): - ret = ogBoot (args.disk, args.par, not not args.nvramperm, args.params) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogBootLoaderDefaultEntry b/ogclient/functions/ogBootLoaderDefaultEntry deleted file mode 100755 index fc99085..0000000 --- a/ogclient/functions/ogBootLoaderDefaultEntry +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -import ogGlobals -from SystemLib import ogHelp -from BootLib import ogBootLoaderDefaultEntry - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('diskdefault') -parser.add_argument ('pardefault') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBootLoaderDefaultEntry', ogGlobals.lang.MSG_SEE+' ogGrubDefaultEntry', []) - sys.exit (0) - -args = parser.parse_args() -ret = ogBootLoaderDefaultEntry (args.disk, args.par, args.diskdefault, args.pardefault) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogBootLoaderDeleteEntry b/ogclient/functions/ogBootLoaderDeleteEntry deleted file mode 100755 index 1d1c21d..0000000 --- a/ogclient/functions/ogBootLoaderDeleteEntry +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -import ogGlobals -from SystemLib import ogHelp -from BootLib import ogBootLoaderDeleteEntry - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('diskdel') -parser.add_argument ('pardel') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBootLoaderDeleteEntry', ogGlobals.lang.MSG_SEE+' ogGrubDeleteEntry', []) - sys.exit (0) - -args = parser.parse_args() -ret = ogBootLoaderDeleteEntry (args.disk, args.par, args.diskdel, args.pardel) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogBootLoaderHidePartitions b/ogclient/functions/ogBootLoaderHidePartitions deleted file mode 100755 index 57a4fda..0000000 --- a/ogclient/functions/ogBootLoaderHidePartitions +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -import ogGlobals -from SystemLib import ogHelp -from BootLib import ogBootLoaderHidePartitions - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBootLoaderHidePartitions', ogGlobals.lang.MSG_SEE+' ogGrubHidePartitions', []) - sys.exit (0) - -parser = argparse.ArgumentParser (add_help=False) -if 3 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') -elif 5 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') - parser.add_argument ('datadisk') - parser.add_argument ('datapar') - -args = parser.parse_args() -if 3 == len (sys.argv): - ret = ogBootLoaderHidePartitions (args.disk, args.par) -elif 5 == len (sys.argv): - ret = ogBootLoaderHidePartitions (args.disk, args.par, args.datadisk, args.datapar) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogBootLoaderOgliveDefaultEntry b/ogclient/functions/ogBootLoaderOgliveDefaultEntry deleted file mode 100755 index 17866ae..0000000 --- a/ogclient/functions/ogBootLoaderOgliveDefaultEntry +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -import ogGlobals -from SystemLib import ogHelp -from BootLib import ogBootLoaderOgliveDefaultEntry - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBootLoaderOgliveDefaultEntry', ogGlobals.lang.MSG_SEE+' ogGrubOgliveDefaultEntry', []) - sys.exit (0) - -args = parser.parse_args() -ret = ogBootLoaderOgliveDefaultEntry (args.disk, args.par) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogBootLoaderSetTimeOut b/ogclient/functions/ogBootLoaderSetTimeOut deleted file mode 100755 index b2782e8..0000000 --- a/ogclient/functions/ogBootLoaderSetTimeOut +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -import ogGlobals -from SystemLib import ogHelp -from BootLib import ogBootLoaderSetTimeOut - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('timeout') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBootLoaderSetTimeOut', ogGlobals.lang.MSG_SEE+' ogGrubSetTimeOut', []) - sys.exit (0) - -args = parser.parse_args() -ret = ogBootLoaderSetTimeOut (args.disk, args.par, args.timeout) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogBootMbrGeneric b/ogclient/functions/ogBootMbrGeneric deleted file mode 100755 index 48cde7f..0000000 --- a/ogclient/functions/ogBootMbrGeneric +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogBootMbrGeneric - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBootMbrGeneric', 'ogBootMbrGeneric int_ndisk', ['ogBootMbrGeneric 1']) - sys.exit (0) - -args = parser.parse_args() -ret = ogBootMbrGeneric (args.disk) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogBootMbrXP b/ogclient/functions/ogBootMbrXP deleted file mode 100755 index 8a15f08..0000000 --- a/ogclient/functions/ogBootMbrXP +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogBootMbrXP - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogBootMbrXP', 'ogBootMbrXP int_ndisk', ['ogBootMbrXP 1']) - sys.exit (0) - -args = parser.parse_args() -ret = ogBootMbrXP (args.disk) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogChangeRepo b/ogclient/functions/ogChangeRepo index 78d08e9..0a65304 100755 --- a/ogclient/functions/ogChangeRepo +++ b/ogclient/functions/ogChangeRepo @@ -7,6 +7,7 @@ from NetLib import ogChangeRepo parser = argparse.ArgumentParser (add_help=False) parser.add_argument ('ip_repo') +parser.add_argument ('og_unit', nargs='?', default=None) if 2 == len (sys.argv) and 'help' == sys.argv[1]: #parser.print_help() sale en inglés aunque la locale indique otra cosa @@ -15,7 +16,7 @@ if 2 == len (sys.argv) and 'help' == sys.argv[1]: args = parser.parse_args() -ret = ogChangeRepo (args.ip_repo) +ret = ogChangeRepo (args.ip_repo, args.og_unit) if ret is not None: if ret == True: sys.exit (0) elif ret == False: sys.exit (1) diff --git a/ogclient/functions/ogCopyFile b/ogclient/functions/ogCopyFile index f65663b..04f1784 100755 --- a/ogclient/functions/ogCopyFile +++ b/ogclient/functions/ogCopyFile @@ -55,9 +55,6 @@ elif 6 == len (sys.argv): args = parser.parse_args() src = { 'container': args.src_container, 'file': args.src_file } dst = { 'disk': args.dst_disk, 'par': args.dst_par, 'file': args.dst_file } -else: - ogHelp ('ogCopyFile', 'ogCopyFile [ str_repo | int_ndisk int_npartition ] path_source [ str_repo | int_ndisk int_npartition ] path_target', ['ogCopyFile REPO newfile.txt 1 2 /tmp/newfile.txt']) - sys.exit (1) ret = ogCopyFile (src, dst) if ret is not None: diff --git a/ogclient/functions/ogGetBootMbr b/ogclient/functions/ogGetBootMbr deleted file mode 100755 index 5c3c887..0000000 --- a/ogclient/functions/ogGetBootMbr +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGetBootMbr - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGetBootMbr', 'ogGetBootMbr int_ndisk', ['ogGetBootMbr 1']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGetBootMbr (args.disk) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGetWindowsName b/ogclient/functions/ogGetWindowsName deleted file mode 100755 index a0de62f..0000000 --- a/ogclient/functions/ogGetWindowsName +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGetWindowsName - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGetWindowsName', 'ogGetWindowsName int_ndisk int_npartition', ['ogGetWindowsName 1 1']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGetWindowsName (args.disk, args.par) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrub4dosInstallMbr b/ogclient/functions/ogGrub4dosInstallMbr deleted file mode 100755 index b76ebb3..0000000 --- a/ogclient/functions/ogGrub4dosInstallMbr +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGrub4dosInstallMbr - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrub4dosInstallMbr', 'ogGrub4dosInstallMbr int_ndisk int_part', ['ogGrub4dosInstallMbr 1 1']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGrub4dosInstallMbr (args.disk, args.par) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrubAddOgLive b/ogclient/functions/ogGrubAddOgLive deleted file mode 100755 index 7b50aa7..0000000 --- a/ogclient/functions/ogGrubAddOgLive +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGrubAddOgLive - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('timeout', nargs='?') -parser.add_argument ('offline', nargs='?') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrubAddOgLive', 'ogGrubAddOgLive int_ndisk int_npartition [ time_out ] [ offline|online ]', ['ogGrubAddOgLive 1 1', 'ogGrubAddOgLive 1 6 15 offline']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGrubAddOgLive (args.disk, args.par, args.timeout, args.offline) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrubDefaultEntry b/ogclient/functions/ogGrubDefaultEntry deleted file mode 100755 index e006e74..0000000 --- a/ogclient/functions/ogGrubDefaultEntry +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGrubDefaultEntry - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('diskdefault') -parser.add_argument ('pardefault') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrubDefaultEntry', 'ogGrubDefaultEntry int_ndisk int_npartition int_disk_default_entry int_npartition_default_entry', ['ogGrubDefaultEntry 1 6 1 1']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGrubDefaultEntry (args.disk, args.par, args.diskdefault, args.pardefault) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrubDeleteEntry b/ogclient/functions/ogGrubDeleteEntry deleted file mode 100755 index d10f764..0000000 --- a/ogclient/functions/ogGrubDeleteEntry +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGrubDeleteEntry - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('diskdel') -parser.add_argument ('pardel') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrubDeleteEntry', 'ogGrubDeleteEntry int_ndisk int_npartition int_disk_delete int_npartition_delete', ['ogGrubDeleteEntry 1 6 2 1']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGrubDeleteEntry (args.disk, args.par, args.diskdel, args.pardel) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrubHidePartitions b/ogclient/functions/ogGrubHidePartitions deleted file mode 100755 index 6fa7202..0000000 --- a/ogclient/functions/ogGrubHidePartitions +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -import ogGlobals -from SystemLib import ogHelp -from BootLib import ogGrubHidePartitions - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrubHidePartitions', 'ogGrubHidePartitions int_ndisk int_npartition [ num_disk_partdata num_partdata ]', ['ogGrubHidePartitions 1 2', 'ogGrubHidePartitions 1 2 1 3']) - sys.exit (0) - -parser = argparse.ArgumentParser (add_help=False) -if 3 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') -elif 5 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') - parser.add_argument ('datadisk') - parser.add_argument ('datapar') - -args = parser.parse_args() -if 3 == len (sys.argv): - ret = ogGrubHidePartitions (args.disk, args.par) -elif 5 == len (sys.argv): - ret = ogGrubHidePartitions (args.disk, args.par, args.datadisk, args.datapar) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrubOgliveDefaultEntry b/ogclient/functions/ogGrubOgliveDefaultEntry deleted file mode 100755 index bd4c6b7..0000000 --- a/ogclient/functions/ogGrubOgliveDefaultEntry +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGrubOgliveDefaultEntry - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrubOgliveDefaultEntry', 'ogGrubOgliveDefaultEntry int_ndiskSecondStage int_partitionSecondStage', ['ogGrubOgliveDefaultEntry 1 6']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGrubOgliveDefaultEntry (args.disk, args.par) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrubSecurity b/ogclient/functions/ogGrubSecurity deleted file mode 100755 index 7895ea9..0000000 --- a/ogclient/functions/ogGrubSecurity +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGrubSecurity - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('user', nargs='?', default='root') -parser.add_argument ('passwd', nargs='?', default='') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrubSecurity', 'ogGrubSecurity int_ndiskSecondStage int_partitionSecondStage [USER] [PASSWORD]', ['ogGrubSecurity 1 1', 'ogGrubSecurity 1 2 user clave']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGrubSecurity (args.disk, args.par, args.user, args.passwd) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogGrubSetTimeOut b/ogclient/functions/ogGrubSetTimeOut deleted file mode 100755 index 73a3629..0000000 --- a/ogclient/functions/ogGrubSetTimeOut +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogGrubSetTimeOut - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('timeout') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogGrubSetTimeOut', 'ogGrubSetTimeOut int_ndiskSecondStage int_partitionSecondStage int_timeout_seconds', ['ogGrubSetTimeOut 1 4 50']) - sys.exit (0) - -args = parser.parse_args() -ret = ogGrubSetTimeOut (args.disk, args.par, args.timeout) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogLinuxBootParameters b/ogclient/functions/ogLinuxBootParameters deleted file mode 100755 index 6da5133..0000000 --- a/ogclient/functions/ogLinuxBootParameters +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogLinuxBootParameters - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogLinuxBootParameters', 'ogLinuxBootParameters int_ndisk int_nfilesys', ['ogLinuxBootParameters 1 2']) - sys.exit (0) - -args = parser.parse_args() -ret = ogLinuxBootParameters (args.disk, args.par) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogSetLinuxName b/ogclient/functions/ogSetLinuxName deleted file mode 100755 index 0c66e0e..0000000 --- a/ogclient/functions/ogSetLinuxName +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogSetLinuxName -from NetLib import ogGetHostname - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogSetLinuxName', 'ogSetLinuxName int_ndisk int_nfilesys [str_name]', ['ogSetLinuxName 1 1 practica-pc']) - sys.exit (0) - -parser = argparse.ArgumentParser (add_help=False) -if 3 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') -elif 4 == len (sys.argv): - parser.add_argument ('disk') - parser.add_argument ('par') - parser.add_argument ('hostname') - -args = parser.parse_args() - -if 3 == len (sys.argv): - h = ogGetHostname() - if h: - ret = ogSetLinuxName (args.disk, args.par, h) - else: - ret = ogSetLinuxName (args.disk, args.par) -elif 4 == len (sys.argv): - ret = ogSetLinuxName (args.disk, args.par, args.hostname) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/functions/ogSetWinlogonUser b/ogclient/functions/ogSetWinlogonUser deleted file mode 100755 index 60c82e3..0000000 --- a/ogclient/functions/ogSetWinlogonUser +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/python3 - -import sys -import argparse -from SystemLib import ogHelp -from BootLib import ogSetWinlogonUser - -parser = argparse.ArgumentParser (add_help=False) -parser.add_argument ('disk') -parser.add_argument ('par') -parser.add_argument ('username') - -if 2 == len (sys.argv) and 'help' == sys.argv[1]: - #parser.print_help() sale en inglés aunque la locale indique otra cosa - ogHelp ('ogSetWinlogonUser', 'ogSetWinlogonUser int_ndisk int_npartition str_username', ['ogSetWinlogonUser 1 1 USUARIO']) - sys.exit (0) - -args = parser.parse_args() -ret = ogSetWinlogonUser (args.disk, args.par, args.username) - -if ret is not None: - if ret == True: sys.exit (0) - elif ret == False: sys.exit (1) - else: print (ret) diff --git a/ogclient/interfaceAdm/Apagar.py b/ogclient/interfaceAdm/Apagar.py index b89c3cc..eafc875 100755 --- a/ogclient/interfaceAdm/Apagar.py +++ b/ogclient/interfaceAdm/Apagar.py @@ -1,10 +1,10 @@ -#!/usr/bin/python3 - +#!/usr/bin/env python3 import os import sys -import time -os.system ('pkill -f OGAgent') -time.sleep (3) -os.system ('poweroff') -sys.exit (0) +def main(): + os.system('poweroff') + sys.exit(0) + +if __name__ == "__main__": + main() diff --git a/ogclient/interfaceAdm/CambiarAcceso.py b/ogclient/interfaceAdm/CambiarAcceso.py index ae8f944..61fea66 100755 --- a/ogclient/interfaceAdm/CambiarAcceso.py +++ b/ogclient/interfaceAdm/CambiarAcceso.py @@ -1,62 +1,54 @@ -#!/usr/bin/python3 - -#______________________________________ -# -# PARAMETROS RECIBIDOS DESDE EL CLIENTE -# $1 modo (admin, user) -#______________________________________ - +#!/usr/bin/env python3 import os import sys -import re import subprocess +import NetLib +import SystemLib -import ogGlobals -from SystemLib import ogEcho, ogRaiseError, ogIsRepoLocked -from NetLib import ogGetRepoIp +def main(): + if len(sys.argv) != 2: + print("Usage: CambiarAcceso.py ") + sys.exit(1) -# Error si llamada no se realliza desde OpenGnsys Client. -prog = sys.argv[0] -if len (sys.argv) != 2: - print (f'Usage: {prog} ') - sys.exit (1) + mode = sys.argv[1] + repo_ip = NetLib.ogGetRepoIp() -# Salir si el repositorio está bloquedo (tiene ficheros abiertos). -mode = sys.argv[1] -repoip = ogGetRepoIp() -if not repoip: - ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'repo no montado') - sys.exit (1) -if ogIsRepoLocked(): - ogRaiseError ([], ogGlobals.OG_ERR_LOCKED, f'repo {repoip}') - sys.exit (1) + if not repo_ip: + SystemLib.ogRaiseError("OG_ERR_NOTFOUND", "repo no montado") -# Comprobar protocolo y modo de acceso. -proto = os.getenv ('ogprotocol', 'smb') -if proto not in ['nfs', 'smb']: - ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'protocolo desconocido {proto}') - sys.exit (1) -if 'admin' == mode: mount_mode = 'rw' -elif 'user' == mode: mount_mode = 'ro' -else: - ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'modo desconocido {mode}') - sys.exit (1) + if SystemLib.ogIsRepoLocked(): + SystemLib.ogRaiseError("OG_ERR_LOCKED", f"repo {repo_ip}") -# Desmontar repositorio y volver a montarlo con el modo adecuado. -subprocess.run (['umount', ogGlobals.OGIMG]) -ogEcho ([], 'info', f'Montar repositorio {repoip} por {proto} en modo {mode}') -if 'nfs' == proto: - subprocess.run (['mount', '-t', 'nfs', f'{repoip}:{ogGlobals.OGIMG}', ogGlobals.OGIMG, '-o', mount_mode]) -elif 'smb' == proto: - pass_option = '' - with open ('/scripts/ogfunctions', 'r') as fd: - while True: - line = fd.readline() - if not line: break - if not re.search ('^[\t ]*(export )?OPTIONS=', line): continue - m = re.search (r'pass=(\w*)', line) - if m: - pass_option = m.groups (0)[0] - break - if not pass_option: pass_option = 'og' - subprocess.run (['mount.cifs', f'//{repoip}/ogimages', ogGlobals.OGIMG, '-o', f'{mount_mode},serverino,acl,username=opengnsys,password={pass_option}']) + proto = os.getenv("ogprotocol", "smb") + if proto not in ["nfs", "smb"]: + SystemLib.ogRaiseError("OG_ERR_FORMAT", f"protocolo desconocido {proto}") + + if mode == "admin": + mount_mode = "rw" + elif mode == "user": + mount_mode = "ro" + else: + SystemLib.ogRaiseError("OG_ERR_FORMAT", f"modo desconocido {mode}") + + OGIMG = os.getenv("OGIMG", "/mnt/OGIMG") + OGUNIT = os.getenv("OGUNIT", "") + if OGUNIT: + OGUNIT = f"/{OGUNIT}" + + subprocess.run(["umount", OGIMG], check=True) + SystemLib.ogEcho("info", f"Montar repositorio {repo_ip} por {proto} en modo {mode}") + + if proto == "nfs": + subprocess.run(["mount", "-t", "nfs", f"{repo_ip}:{OGIMG}{OGUNIT}", OGIMG, "-o", mount_mode], check=True) + elif proto == "smb": + with open("/scripts/ogfunctions", "r") as f: + for line in f: + if "OPTIONS=" in line: + pass_option = line.split("pass=")[1].split()[0] + break + else: + pass_option = "og" + subprocess.run(["mount.cifs", f"//{repo_ip}/ogimages{OGUNIT}", OGIMG, "-o", f"{mount_mode},serverino,acl,username=opengnsys,password={pass_option}"], check=True) + +if __name__ == "__main__": + main() diff --git a/ogclient/interfaceAdm/Configurar.py b/ogclient/interfaceAdm/Configurar.py index ab74291..d355c49 100755 --- a/ogclient/interfaceAdm/Configurar.py +++ b/ogclient/interfaceAdm/Configurar.py @@ -9,7 +9,6 @@ import SystemLib import CacheLib import FileSystemLib import DiskLib -import InventoryLib #Load engine configurator from engine.cfg file. #Carga el configurador del engine desde el fichero engine.cfg @@ -62,24 +61,23 @@ sparam = tbprm[1] # Partitioning and formatting parameters # Toma valores de disco y caché, separados por "*". # Los valores están en las variables $dis: disco, $che: existe cache (1, 0), $tch: Tamaño de la cache. tbprm = pparam.split ('*') -dis = tch = None +dis = ptt = tch = None for item in tbprm: if '=' not in item: continue k, v = item.split ('=', 1) - if k not in ['dis', 'tch']: + if k not in ['dis', 'tch', 'ptt']: ## 'ptt' added, unused 'che' removed print (f'ignoring unknown disk parameter ({k})') continue if 'dis' == k: dis = int (v) + elif 'ptt' == k: ptt = v elif 'tch' == k: tch = v # Error si no se define el parámetro de disco (dis). -if dis is None: - coproc.kill() - sys.exit (ogGlobals.OG_ERR_FORMAT) -if tch is None: - tch = '0' +if dis is None: sys.exit (ogGlobals.OG_ERR_FORMAT) +if ptt is None: ptt = 'MSDOS' +if tch is None: tch = '0' # Toma valores de distribución de particiones, separados por "%". tbp = [] # Valores de configuración (parámetros para ogCreatePartitions) @@ -114,7 +112,6 @@ for item in tbprm: if tam is None: missing_params.append ('tam') if missing_params: print (f'partition data ({item}) missing required parameters ({' '.join (missing_params)})') - coproc.kill() sys.exit (1) # Componer datos de particionado. @@ -141,21 +138,18 @@ CacheLib.ogUnmountCache() # Elimina la tabla de particiones cur_ptt = DiskLib.ogGetPartitionTableType (dis) -ptt = 'GPT' if InventoryLib.ogIsEfiActive() else 'MSDOS' if not cur_ptt or ptt != cur_ptt: DiskLib.ogDeletePartitionTable (dis) SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable) + + # Crea tabla de particiones MSDOS (NOTA: adaptar para tablas GPT). DiskLib.ogCreatePartitionTable (dis, ptt) # Inicia la cache. if 'CACHE' in sparam: SystemLib.ogEcho (['session', 'log'], None, f'[30] {ogGlobals.lang.MSG_HELP_ogCreateCache}') SystemLib.ogEcho (['session', 'log'], None, f' initCache {tch}') - rc = SystemLib.ogExecAndLog ('command', CacheLib.initCache, tch) - if rc: - SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_CACHE, f'initCache failed') - coproc.kill() - sys.exit (1) + SystemLib.ogExecAndLog ('command', CacheLib.initCache, tch) # Definir particionado. SystemLib.ogEcho (['session', 'log'], None, f'[50] {ogGlobals.lang.MSG_HELP_ogCreatePartitions}') diff --git a/ogclient/interfaceAdm/CrearImagen.py b/ogclient/interfaceAdm/CrearImagen.py index 2ab2b58..29628e0 100755 --- a/ogclient/interfaceAdm/CrearImagen.py +++ b/ogclient/interfaceAdm/CrearImagen.py @@ -1,109 +1,74 @@ -#!/usr/bin/python3 - -#___________________________________________________ -# -# PARAMETROS RECIBIDOS DESDE EL CLIENTE: -# $1 Número de disco -# $2 Número de particion -# $3 Nombre canónico de la imagen (sin extensión) -# $4 Dirección del repositorio (REPO, por defecto) -#___________________________________________________ - - -#$OG_ERR_NOTEXEC Si no es llamada por OG client -#$OG_ERR_LOCKED=4 Si la particion está bloqueada. - - -#Codigos de error del scripts createImage -#@exception OG_ERR_FORMAT # 1 formato incorrecto. -#@exception OG_ERR_PARTITION # 3 Error en partición de disco o en su sistema de archivos -#@exception OG_ERR_IMAGE # 5 Error en funcion ogCreateImage o ogRestoreImage. -#@exception OG_ERR_NOTWRITE # 14 error de escritura -#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15 -#@exception OG_ERR_CACHESIZE # 16 si espacio de la cache local o remota no tiene espacio 16 -#@exception OG_ERR_REDUCEFS # 17 error al reducir sistema de archivos. -#@exception OG_ERR_EXTENDFS # 18 Errror al expandir el sistema de archivos. - - -#Códigos de error de la funcion ogCreateImage - +#!/usr/bin/env python3 import os import subprocess import sys import time - +import NetLib import ogGlobals -from SystemLib import ogEcho, ogRaiseError -from NetLib import ogGetIpAddress, ogChangeRepo -from StringLib import ogCheckIpAddress -prog = sys.argv[0] -if len (sys.argv) < 4: - ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, 'Incorrect number of arguments') - sys.exit (1) -disk, par, imgname, *other = sys.argv[1:] -arg_repo = other[0] if len (other) > 0 else 'REPO' -dirname = os.path.dirname (prog) +def load_engine_config(): + engine_config_path = "/opt/opengnsys/etc/engine.cfg" + if os.path.exists(engine_config_path): + with open(engine_config_path) as f: + exec(f.read(), globals()) -start_time = time.time() -env_boot = os.getenv ('boot') +def clear_temp_logs(): + open(os.getenv('OGLOGSESSION'), 'w').close() + open(os.getenv('OGLOGCOMMAND'), 'w').close() + open(f"{os.getenv('OGLOGCOMMAND')}.tmp", 'w').close() -#Load engine configurator from engine.cfg file. -#Carga el configurador del engine desde el fichero engine.cfg -## (ogGlobals se encarga) +def log_session_start(script_name, args): + SystemLib.ogEcho("log session", f"{os.getenv('MSG_INTERFACE_START')} {script_name} {' '.join(args)}") -# Clear temporary file used as log track by httpdlog -# Limpia los ficheros temporales usados como log de seguimiento para httpdlog -open (ogGlobals.OGLOGSESSION, 'w').close() -open (ogGlobals.OGLOGCOMMAND, 'w').close() -open (f"{ogGlobals.OGLOGCOMMAND}.tmp", 'w').close() +def log_session_end(retval): + SystemLib.ogEcho("log session", f"{os.getenv('MSG_INTERFACE_END')} {retval}") -# Registro de inicio de ejecución -ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {prog} {disk} {par} {imgname} {arg_repo}') +def ogCheckIpAddress(ip): + try: + subprocess.check_call(["ping", "-c", "1", ip]) + return 0 + except subprocess.CalledProcessError: + return 1 -# Valor por defecto para el repositorio. -repo = arg_repo -if not repo: repo = 'REPO' -if repo == ogGetIpAddress(): repo = 'CACHE' -# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. -if 'REPO' == repo or ogCheckIpAddress (repo): - # Si falla el cambio -> salimos con error repositorio no valido - if not ogChangeRepo (repo): - ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repo) - sys.exit (1) +def create_image(disk_num, partition_num, repo, image_name): + if subprocess.call(["which", "createImageCustom"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0: + return subprocess.call(["createImageCustom", disk_num, partition_num, repo, f"/{image_name}"]) + else: + return subprocess.call(["createImage", disk_num, partition_num, repo, f"/{image_name}"]) -# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura, -if 'REPO' == repo and 'admin' != env_boot: - retval = subprocess.run ([f'{dirname}/CambiarAcceso.py', 'admin']).returncode - if retval: - sys.exit (retval) +def main(): + if len(sys.argv) != 5: + sys.exit(SystemLib.ogRaiseError(OG_ERR_FORMAT, "Incorrect number of arguments")) -ogEcho ([], None, f'createImage "{disk}" "{par}" "{arg_repo}" /"{imgname}"') -# Si existe, ejecuta script personalizado "createImageCustom"; si no, llama al genérico "createImage". -if os.path.exists ('{ogGlobals.OGSCRIPTS}/createImageCustom.py'): - script = f'{ogGlobals.OGSCRIPTS}/createImageCustom.py' -else: - script = f'{ogGlobals.OGSCRIPTS}/createImage.py' + disk_num, partition_num, image_name, repo = sys.argv[1:5] -with open (ogGlobals.OGLOGCOMMAND, 'a') as fd: - p = subprocess.Popen ([script, disk, par, arg_repo, f'/{imgname}'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - while p.poll() is None: - for l in iter (p.stdout.readline, b''): - partial = l.decode ('utf-8', 'ignore') - fd.write (partial) - print (partial, end='') ## so that the agent captures out output and reports progress to ogcore - for l in iter (p.stderr.readline, b''): - partial = l.decode ('utf-8', 'ignore') - fd.write (partial) - print (partial, end='') -retval = p.returncode + start_time = time.time() -# Cambiar acceso a modo usuario, si es necesario. -if 'REPO' == repo and 'admin' != env_boot: - subprocess.run ([f'{dirname}/CambiarAcceso.py', 'user']) + load_engine_config() + clear_temp_logs() + log_session_start(sys.argv[0], sys.argv[1:]) -# Registro de fin de ejecución -ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}') + repo = repo if repo else "REPO" + if repo == NetLib.ogGetIpAddress(): + repo = "CACHE" -sys.exit (retval) + if ogCheckIpAddress(repo) == 0 or repo == "REPO": + OGUNIT = os.getenv('OGUNIT', "") + if not NetLib.ogChangeRepo(repo, OGUNIT): + sys.exit(SystemLib.ogRaiseError(OG_ERR_NOTFOUND, f"{repo}")) + if repo == "REPO" and os.getenv('boot') != "admin": + retval = CambiarAcceso("admin") + if retval > 0: + sys.exit(retval) + + retval = create_image(disk_num, partition_num, repo, image_name) + + if repo == "REPO" and os.getenv('boot') != "admin": + CambiarAcceso("user") + + log_session_end(retval) + sys.exit(retval) + +if __name__ == "__main__": + main() diff --git a/ogclient/interfaceAdm/EjecutarScript.py b/ogclient/interfaceAdm/EjecutarScript.py index 23bbbc3..35dde8d 100755 --- a/ogclient/interfaceAdm/EjecutarScript.py +++ b/ogclient/interfaceAdm/EjecutarScript.py @@ -1,50 +1,62 @@ -#!/usr/bin/python3 - +#!/usr/bin/env python3 import os import time import subprocess import sys - +import SystemLib import ogGlobals -from SystemLib import ogEcho, ogRaiseError +#sys.path.append('/opt/opengnsys/lib/engine/bin') -prog = sys.argv[0] -if len (sys.argv) != 2: - print (f'Usage: {prog} ') - sys.exit (1) +def main(script_path): + start_time = time.time() + print(f"Ejecutando:",script_path) -TIME1 = time.time() -script_path = sys.argv[1] + # Load engine configurator from engine.cfg file. + engine_config_path = '/opt/opengnsys/etc/engine.cfg' +# if 'OGENGINECONFIGURATE' not in os.environ: +# with open(engine_config_path) as f: +# exec(f.read(), globals()) -# Clear temporary file used as log track by httpdlog -# Limpia los ficheros temporales usados como log de seguimiento para httpdlog -open (ogGlobals.OGLOGSESSION, 'w').close() -open (ogGlobals.OGLOGCOMMAND, 'w').close() + # Clear temporary file used as log track by httpdlog + with open(os.environ['OGLOGSESSION'], 'w') as f: + f.write("") + with open(os.environ['OGLOGCOMMAND'], 'w') as f: + f.write("") -# Registro de inicio de ejecución -ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {prog} {script_path}') + # Registro de inicio de ejecución + SystemLib.ogEcho('log session', f"{os.environ['MSG_INTERFACE_START']} {sys.argv[0]} {' '.join(sys.argv[1:])}") -with open (ogGlobals.OGLOGFILE, 'a') as logfd: - with open (script_path) as scriptfd: - logfd.write ('\n Instrucciones a ejecutar: *****************************\n') - logfd.write (scriptfd.read()) + with open(os.environ['OGLOGFILE'], 'a') as log_file: + log_file.write("\n Instrucciones a ejecutar: *****************************\n" + with open(script_path.split()[1]) as script_file: # Obtener solo el nombre del script + log_file.write(script_file.read()) ) - logfd.write ('\n Salida de las instrucciones: *****************************\n') + log_file.write("\n Salida de las instrucciones: *****************************\n") -os.chmod (script_path, 0o755) -# Si mandamos la salida a OGLOGCOMMAND reescribimos lo que manda el comando. -RETVAL = subprocess.run (['bash', script_path]).returncode + # Cambiar permisos y ejecutar el script + os.chmod(script_path.split()[1], 0o755) + result = subprocess.run([sys.executable] + script_path.split(), capture_output=True, text=True) + ret_val = result.returncode + with open(os.environ['OGLOGCOMMAND'], 'a') as log_command_file: + log_command_file.write(result.stdout) + log_command_file.write(result.stderr) -TIME = time.time() - TIME1 -if 0 == RETVAL: - ogEcho (['log', 'session'], None, f'[100] Duracion de la operacion {int(TIME // 60)}m {int(TIME % 60)}s') -else: - ogRaiseError (['log', 'session'], RETVAL, '') - ogEcho (['log', 'session'], 'error', 'Operacion no realizada') + elapsed_time = time.time() - start_time + if ret_val == 0: + SystemLib.ogEcho('log session', f"[100] Duracion de la operacion {int(elapsed_time // 60)}m {int(elapsed_time % 60)}s") + else: + SystemLib.ogRaiseError('log session', ret_val) + SystemLib.ogEcho('log session', 'error "Operacion no realizada"') -# Registro de fin de ejecución -ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {RETVAL}') + # Registro de fin de ejecución + SystemLib.ogEcho('log session', f"{os.environ['MSG_INTERFACE_END']} {ret_val}") -sys.exit (RETVAL) + sys.exit(ret_val) + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Usage: python EjecutarScript.py ") + sys.exit(1) + main(sys.argv[1]) diff --git a/ogclient/interfaceAdm/IniciarSesion.py b/ogclient/interfaceAdm/IniciarSesion.py index 8ccfaaf..48aa5d5 100755 --- a/ogclient/interfaceAdm/IniciarSesion.py +++ b/ogclient/interfaceAdm/IniciarSesion.py @@ -1,23 +1,18 @@ -#!/usr/bin/python3 - +#!/usr/bin/env python3 import sys import subprocess -import ogGlobals -from SystemLib import ogRaiseError +def main(): + args = sys.argv[1:] + + if len(args) == 1: + disk = 1 + part = args[0] + else: + disk = args[0] + part = args[1] + + boot_os(disk, part) -# UHU - Comprobamos el disco, si solo hay un parametro, disco es 1, por compatibilidad con clientes antiguos -prog = sys.argv[0] -if len (sys.argv) < 2 or len (sys.argv) > 3: - ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'{prog} disk [partition]') - sys.exit (1) -args = sys.argv[1:] - -if 1 == len (args): - disk = '1' - part = args[0] -else: - disk = args[0] - part = args[1] - -subprocess.run ([f'{ogGlobals.OGSCRIPTS}/bootOs.py', disk, part]) +if __name__ == "__main__": + main() diff --git a/ogclient/interfaceAdm/InventarioHardware.py b/ogclient/interfaceAdm/InventarioHardware.py index de35025..bb1188d 100755 --- a/ogclient/interfaceAdm/InventarioHardware.py +++ b/ogclient/interfaceAdm/InventarioHardware.py @@ -1,25 +1,33 @@ -#!/usr/bin/python3 -# Script de interfaz para guardar en un fichero el inventario de hardware de un cliente. - -import sys +#!/usr/bin/env python3 import subprocess +import sys -import ogGlobals -from SystemLib import ogRaiseError +def main(output_file): + # Ejecutar el comando `listHardwareInfo.py` y capturar el resultado + try: + print(f"------------------------------------------ loading listHardwareInfo.py") + result = subprocess.run( + ["python3", "/opt/opengnsys/scripts/listHardwareInfo.py"], + capture_output=True, text=True, check=True + ) + output_lines = result.stdout.strip().split('\n') + file_path = output_lines[-1] # Obtener la última línea como la ruta del archivo de salida + print(f"------------------------------------------ archivo:{file_path}") + + # Leer desde la segunda línea del archivo y escribir en el archivo de salida especificado + with open(file_path, 'r') as input_file, open(output_file, 'w') as output: + lines = input_file.readlines()[1:] # Saltar la primera línea + output.writelines(lines) -prog = sys.argv[0] -if len (sys.argv) != 2: - print (f'Usage: {prog} ') - sys.exit (1) -output_file = sys.argv[1] + except subprocess.CalledProcessError as e: + print("Error ejecutando listHardwareInfo.py:", e.stderr, file=sys.stderr) + sys.exit(e.returncode) + except FileNotFoundError as e: + print(f"Archivo no encontrado: {e.filename}", file=sys.stderr) + sys.exit(1) -listhi_out = subprocess.run ( [f'{ogGlobals.OGSCRIPTS}/listHardwareInfo.py'], capture_output=True, text=True).stdout -if listhi_out: - inventory_path = listhi_out.splitlines()[0] -else: - ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'listHardwareInfo.py failed') - sys.exit (1) - -with open (inventory_path, 'r') as fdin, open (output_file, 'w') as fdout: - lines = fdin.readlines()[1:] # 'tail -n +2' - fdout.writelines (lines) +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Uso: python3 InventarioHardware.py ") + sys.exit(1) + main(sys.argv[1]) diff --git a/ogclient/interfaceAdm/InventarioSoftware.py b/ogclient/interfaceAdm/InventarioSoftware.py index e5185b5..29f3420 100755 --- a/ogclient/interfaceAdm/InventarioSoftware.py +++ b/ogclient/interfaceAdm/InventarioSoftware.py @@ -1,40 +1,53 @@ #!/usr/bin/env python3 - import os import time import shutil import subprocess import sys +sys.path.append('/opt/opengnsys/lib/engine/bin') import ogGlobals -from SystemLib import ogEcho, ogRaiseError +import SystemLib + +def main(arg1, arg2, dest_file): + start_time = time.time() + + og_log_session = os.getenv(ogGlobals.OGLOGSESSION) + og_log_command = os.getenv(ogGlobals.OGLOGCOMMAND) + if og_log_session and og_log_command: + with open(og_log_session, 'w') as f: + f.write(" ") + with open(og_log_command, 'w') as f: + f.write(" ") + with open(f"{og_log_command}.tmp", 'w') as f: + f.write(" ") + + msg_interface_start = os.getenv(ogGlobals.lang.MSG_INTERFACE_START) + if msg_interface_start: + SystemLib.ogEcho("log", "session", f"{msg_interface_start} {__file__} {arg1} {arg2}") + + try: + result = subprocess.run( + ["python3", "/opt/opengnsys/scripts/listSoftwareInfo.py", arg1, arg2], + capture_output=True, + text=True, + check=True + ) + file = result.stdout.strip().splitlines()[-1] + except subprocess.CalledProcessError as e: + print(f"Error al ejecutar listSoftwareInfo: {e.stderr}") + sys.exit(e.returncode) + + print(f"Copying:( {file} to {dest_file} )") + shutil.copy(file, dest_file) + + elapsed_time = time.time() - start_time + msg_scripts_time_partial = os.getenv(ogGlobals.lang.MSG_SCRIPTS_TIME_PARTIAL) + if msg_scripts_time_partial: + SystemLib.ogEcho("log", "session", f" [ ] {msg_scripts_time_partial} : {int(elapsed_time // 60)}m {int(elapsed_time % 60)}s") if __name__ == "__main__": - prog = sys.argv[0] - if len (sys.argv) != 4: - print (f'Usage: {prog} ') - sys.exit (1) - - disk, par, dest_file = sys.argv[1:] - - TIME1 = time.time() - -# Limpia los ficheros temporales usados como log de seguimiento para httpdlog - open (ogGlobals.OGLOGSESSION, 'w').close() - open (ogGlobals.OGLOGCOMMAND, 'w').close() - open (f"{ogGlobals.OGLOGCOMMAND}.tmp", 'w').close() - -# Registro de inicio de ejecución - ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {prog} {disk} {par} {dest_file}') - - listsi_out = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/listSoftwareInfo.py', disk, par], capture_output=True, text=True).stdout - if listsi_out: - file = listsi_out.splitlines()[0] - else: - ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'listSoftwareInfo.py failed') - sys.exit (1) - - shutil.copy (file, dest_file) - - TIME = time.time() - TIME1 - ogEcho(['log', 'session'], None, f' [ ] {ogGlobals.lang.MSG_SCRIPTS_TIME_PARTIAL} : {int(TIME // 60)}m {int(TIME % 60)}s') + if len(sys.argv) != 4: + print("Usage: python InventarioSoftware.py ") + sys.exit(1) + main(sys.argv[1], sys.argv[2], sys.argv[3]) diff --git a/ogclient/interfaceAdm/Reiniciar.py b/ogclient/interfaceAdm/Reiniciar.py index ceaa589..f1b0e25 100755 --- a/ogclient/interfaceAdm/Reiniciar.py +++ b/ogclient/interfaceAdm/Reiniciar.py @@ -1,10 +1,8 @@ -#!/usr/bin/python3 - +#!/usr/bin/env python3 import os -import sys -import time -os.system ('pkill -f OGAgent') -time.sleep (3) -os.system ('reboot') -sys.exit (0) +def reboot_system(): + os.system('reboot') + +if __name__ == "__main__": + reboot_system() diff --git a/ogclient/interfaceAdm/RestaurarImagen.py b/ogclient/interfaceAdm/RestaurarImagen.py index 4b5c4b8..a5fda6c 100755 --- a/ogclient/interfaceAdm/RestaurarImagen.py +++ b/ogclient/interfaceAdm/RestaurarImagen.py @@ -1,29 +1,19 @@ -#!/usr/bin/python3 -#_______________________________________________________________________________________________________________________________ -# -# PARAMETROS RECIBIDOS DESDE EL CLIENTE: -# $1 disco -# $2 par=Número de particion -# $3 Nombre canónico de la imagen -# $4 Dirección IP del repositorio -# $5 Protocolo UNICAST MULTICAST TORRENT -# $6 Opciones del protocolo -#_______________________________________________________________________________________________________________________________ - -# Llamar al script de despliegue "deployImage". - +#!/usr/bin/env python3 import sys import subprocess -import ogGlobals +if __name__ == "__main__": + if len(sys.argv) < 7: + print("Usage: python RestaurarImagen.py [additional_args...]") + sys.exit(1) -if __name__ == '__main__': - prog = sys.argv[0] - if len (sys.argv) < 6: - print (f'Usage: {prog} [protocol_options] [additional_args...]') - sys.exit (1) + disk = sys.argv[1] + partition = sys.argv[2] + image_name = sys.argv[3] + ip = sys.argv[4] + protocol = sys.argv[5] + protocol_options = sys.argv[6] + additional_args = sys.argv[7:] - disk, par, imgname, repo, proto, *extra = sys.argv[1:] - - rc = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/deployImage.py', repo, imgname, disk, par, proto] + extra).returncode - sys.exit (rc) + exit_code = deploy_image(ip, image_name, disk, partition, protocol, protocol_options, *additional_args) + sys.exit(exit_code) diff --git a/ogclient/interfaceAdm/getConfiguration.py b/ogclient/interfaceAdm/getConfiguration.py index 29d4ec4..89a1b0a 100755 --- a/ogclient/interfaceAdm/getConfiguration.py +++ b/ogclient/interfaceAdm/getConfiguration.py @@ -1,78 +1,80 @@ -#!/usr/bin/python3 - +#!/usr/bin/env python3 import os -import glob import subprocess -from InventoryLib import ogGetSerialNumber, ogGetOsVersion, ogIsEfiActive -from DiskLib import ogDiskToDev, ogGetPartitionsNumber, ogGetPartitionTableType, ogGetDiskSize, ogGetPartitionId, ogGetPartitionSize -from FileSystemLib import ogMount, ogGetMountPoint, ogGetFsType +def run_command(command): + result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return result.stdout.decode().strip() -ser = ogGetSerialNumber() -fwt = 'UEFI' if ogIsEfiActive() else 'BIOS' -print (f'ser={ser}\nfwt={fwt}') +def main(): + # No registrar los errores. + os.environ["DEBUG"] = "no" + + ser = run_command("ogGetSerialNumber") + cfg = "" + disks = int(run_command("ogDiskToDev | wc -w")) + + for dsk in range(1, disks + 1): + particiones = run_command(f"ogGetPartitionsNumber {dsk}") + particiones = int(particiones) if particiones else 0 + ptt = run_command(f"ogGetPartitionTableType {dsk}") -disks = len (ogDiskToDev()) -if disks: - for dsk in range (1, disks+1): - # Tipo de tabla de particiones: 1=MSDOS, 2=GPT - ptt = ogGetPartitionTableType (dsk) ptt_map = { - 'MSDOS': 1, - 'GPT': 2, - 'LVM': 3, - 'ZPOOL': 4, + "MSDOS": 1, + "GPT": 2, + "LVM": 3, + "ZPOOL": 4 } - ptt = ptt_map.get (ptt, 0) + ptt = ptt_map.get(ptt, 0) - # Información de disco (partición 0) - s = ogGetDiskSize (dsk) - print (f'disk={dsk}\tpar=0\tcpt={ptt}\tfsi=\tsoi=\ttam={s}\tuso=0') + cfg += f"{dsk}:0:{ptt}:::{run_command(f'ogGetDiskSize {dsk}')}:0;" - particiones = ogGetPartitionsNumber (dsk) - particiones = int (particiones) if particiones else 0 - for par in range (1, particiones+1): - # Código del identificador de tipo de partición - cod = ogGetPartitionId (dsk, par) + for par in range(1, particiones + 1): + cod = run_command(f"ogGetPartitionId {dsk} {par} 2>/dev/null") + fsi = run_command(f"getFsType {dsk} {par} 2>/dev/null") or "EMPTY" + tam = run_command(f"ogGetPartitionSize {dsk} {par} 2>/dev/null") or "0" + soi = "" + uso = 0 - # Tipo del sistema de ficheros - fsi = ogGetFsType (dsk, par) - if not fsi: fsi = 'EMPTY' - - # Tamaño de la particón - tam = ogGetPartitionSize (dsk, par) - if not tam: tam = '0' - - # Sistema operativo instalado y porcentaje de uso - soi = '' - uso = '0' - if fsi not in ['', 'EMPTY', 'LINUX-SWAP', 'LINUX-LVM', 'ZVOL']: - if ogMount (dsk, par): - soi = ogGetOsVersion (dsk, par) - # Hacer un 2º intento para algunos casos especiales. + if fsi not in ["", "EMPTY", "LINUX-SWAP", "LINUX-LVM", "ZVOL"]: + if run_command(f"ogMount {dsk} {par} 2>/dev/null"): + soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1] if not soi: - soi = ogGetOsVersion (dsk, par) - if not soi: soi = '' - if soi: soi = soi.split (':')[1] - # Sistema de archivos para datos (sistema operativo "DATA") - if not soi and fsi not in ['EMPTY', 'CACHE']: - soi = 'DATA' - mntpt = ogGetMountPoint (dsk, par) - uso = subprocess.run (['df', mntpt], capture_output=True, text=True).stdout.splitlines()[-1].split()[4].replace ('%', '') - if not uso: uso = '0' + soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1] + if not soi and fsi not in ["EMPTY", "CACHE"]: + soi = "DATA" + uso = int(run_command(f"df $(ogGetMountPoint {dsk} {par}) | awk '{{getline; printf \"%d\",$5}}'") or 0) else: - soi = '' - uso = '0' + soi = "" + uso = 0 - print (f'disk={dsk}\tpar={par}\tcpt={cod}\tfsi={fsi}\tsoi={soi}\ttam={tam}\tuso={uso}') -else: - print ('disk=1\tpar=0\tcpt=0\tfsi=\tsoi=\ttam=0\tuso=0') + cfg += f"{dsk}:{par}:{cod}:{fsi}:{soi}:{tam}:{uso};" -# Crear el menú por defecto a partir del fichero generado (no dar ninguna salida). -# requiere /tmp/getconfig pero este script ya no lo crea -#subprocess.run ([f'{ogGlobals.OGSCRIPTS}/generateMenuDefault']) + if not cfg: + cfg = "1:0:0:::0;" -# Borramos marcas de arranque de Windows -for f in glob.glob ('/mnt/*/ogboot.*') + glob.glob ('/mnt/*/*/ogboot.*'): - try: os.unlink (f) - except: pass + cfgfile = "/tmp/getconfig" + with open(cfgfile, "w") as f: + f.write(f"{ser + ';' if ser else ''}{cfg}") + + run_command("generateMenuDefault &>/dev/null") + + with open(cfgfile, "r") as f: + data = f.read() + + lines = data.split(";") + for line in lines: + if line: + parts = line.split(":") + if len(parts) == 1: + print(f"ser={parts[0]}") + else: + print(f"disk={parts[0]}\tpar={parts[1]}\tcpt={parts[2]}\tfsi={parts[3]}\tsoi={parts[4]}\ttam={parts[5]}\tuso={parts[6]}") + + run_command("rm -f /mnt/*/ogboot.* /mnt/*/*/ogboot.*") + + # Volver a registrar los errores. + os.environ.pop("DEBUG", None) + +if __name__ == "__main__": + main() diff --git a/ogclient/interfaceAdm/getIpAddress.py b/ogclient/interfaceAdm/getIpAddress.py index 18d5150..0ba1389 100755 --- a/ogclient/interfaceAdm/getIpAddress.py +++ b/ogclient/interfaceAdm/getIpAddress.py @@ -1,5 +1,10 @@ -#!/usr/bin/python3 +#!/usr/bin/env python3 +import socket -from NetLib import ogGetIpAddress +def get_ip_address(): + hostname = socket.gethostname() + ip_address = socket.gethostbyname(hostname) + return ip_address -print (ogGetIpAddress()) +if __name__ == "__main__": + print(get_ip_address()) diff --git a/ogclient/lib/burg/themes/OpenGnsys/background-original.png b/ogclient/lib/burg/themes/OpenGnsys/background-original.png new file mode 100644 index 0000000..57861de Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/background-original.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/background.png b/ogclient/lib/burg/themes/OpenGnsys/background.png new file mode 100755 index 0000000..8150330 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/background.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/extended b/ogclient/lib/burg/themes/OpenGnsys/extended new file mode 100644 index 0000000..c61e14a --- /dev/null +++ b/ogclient/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/ogclient/lib/burg/themes/OpenGnsys/icons/hover_debian.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_debian.png new file mode 100644 index 0000000..55d7ce0 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_debian.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_elementary.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_elementary.png new file mode 100644 index 0000000..a2bc2b2 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_elementary.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_freebsd.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_freebsd.png new file mode 100644 index 0000000..eedade7 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_freebsd.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_haiku.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_haiku.png new file mode 100644 index 0000000..f6b21d6 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_haiku.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_linux.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_linux.png new file mode 100644 index 0000000..5064c4a Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_linux.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_opengnsys.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_opengnsys.png new file mode 100644 index 0000000..aea9bfe Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_opengnsys.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_opensuse.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_opensuse.png new file mode 100644 index 0000000..bdc548b Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_opensuse.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_os.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_os.png new file mode 100644 index 0000000..abb4b29 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_os.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_osx.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_osx.png new file mode 100644 index 0000000..8a1c8f5 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_osx.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_recovery.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_recovery.png new file mode 100644 index 0000000..d9144a6 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_recovery.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_restart.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_restart.png new file mode 100644 index 0000000..9c30c23 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_restart.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_shutdown.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_shutdown.png new file mode 100644 index 0000000..39b123f Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_shutdown.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_ubuntu.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_ubuntu.png new file mode 100644 index 0000000..d1cda27 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_ubuntu.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows.png new file mode 100644 index 0000000..96e11c8 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows10.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows10.png new file mode 100644 index 0000000..0eabef7 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows10.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows7.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows7.png new file mode 100644 index 0000000..95d9e18 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows7.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows_metro.png b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows_metro.png new file mode 100644 index 0000000..7ace114 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/hover_windows_metro.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/icons b/ogclient/lib/burg/themes/OpenGnsys/icons/icons new file mode 100644 index 0000000..15d5bec --- /dev/null +++ b/ogclient/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/ogclient/lib/burg/themes/OpenGnsys/icons/normal_debian.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_debian.png new file mode 100644 index 0000000..88b19a3 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_debian.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_elementary.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_elementary.png new file mode 100644 index 0000000..31863ec Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_elementary.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_freebsd.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_freebsd.png new file mode 100644 index 0000000..1162e53 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_freebsd.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_haiku.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_haiku.png new file mode 100644 index 0000000..cab9bfd Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_haiku.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_linux.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_linux.png new file mode 100644 index 0000000..8e215df Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_linux.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_opengnsys.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_opengnsys.png new file mode 100644 index 0000000..687f180 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_opengnsys.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_opensuse.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_opensuse.png new file mode 100644 index 0000000..6ab2c37 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_opensuse.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_os.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_os.png new file mode 100644 index 0000000..7d33f4d Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_os.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_osx.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_osx.png new file mode 100644 index 0000000..5955b67 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_osx.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_recovery.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_recovery.png new file mode 100644 index 0000000..a1c6db3 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_recovery.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_restart.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_restart.png new file mode 100644 index 0000000..1f0e69f Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_restart.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_shutdown.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_shutdown.png new file mode 100644 index 0000000..2176660 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_shutdown.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_ubuntu.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_ubuntu.png new file mode 100644 index 0000000..becf779 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_ubuntu.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows.png new file mode 100644 index 0000000..9609364 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows10.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows10.png new file mode 100644 index 0000000..8caf5c7 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows10.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows7.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows7.png new file mode 100644 index 0000000..34d50eb Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows7.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows_metro.png b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows_metro.png new file mode 100644 index 0000000..8d4974e Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/icons/normal_windows_metro.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/000-70opaque.png b/ogclient/lib/burg/themes/OpenGnsys/images/000-70opaque.png new file mode 100644 index 0000000..8f92c2f Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/000-70opaque.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-bg.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-bg.png new file mode 100644 index 0000000..a3ee24e Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-bg.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-bg.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-bg.png new file mode 100644 index 0000000..cd88d06 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-bg.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-l.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-l.png new file mode 100644 index 0000000..1a9a516 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-l.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-r.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-r.png new file mode 100644 index 0000000..a8befbb Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-hover-r.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-l.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-l.png new file mode 100644 index 0000000..34b3bf0 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-l.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-r.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-r.png new file mode 100644 index 0000000..0cb01e8 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-r.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-tools-hover.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-tools-hover.png new file mode 100644 index 0000000..a8c74b1 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-tools-hover.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/button-tools.png b/ogclient/lib/burg/themes/OpenGnsys/images/button-tools.png new file mode 100644 index 0000000..1cef055 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/button-tools.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-b.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-b.png new file mode 100644 index 0000000..54b5999 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-b.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-bg.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-bg.png new file mode 100644 index 0000000..9d1a625 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-bg.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-bl.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-bl.png new file mode 100644 index 0000000..aaadeae Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-bl.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-br.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-br.png new file mode 100644 index 0000000..eb2fbcb Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-br.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-l.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-l.png new file mode 100644 index 0000000..d2bda89 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-l.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-r.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-r.png new file mode 100644 index 0000000..741e2ba Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-r.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-t.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-t.png new file mode 100644 index 0000000..2ab4a00 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-t.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-title-bg.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-bg.png new file mode 100644 index 0000000..e269395 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-bg.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-title-l.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-l.png new file mode 100644 index 0000000..eb80522 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-l.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-title-r.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-r.png new file mode 100644 index 0000000..4195892 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-r.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-title-t.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-t.png new file mode 100644 index 0000000..6c56bf8 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-t.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-title-tl.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-tl.png new file mode 100644 index 0000000..1d2ad5e Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-tl.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-title-tr.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-tr.png new file mode 100644 index 0000000..dbd43df Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-title-tr.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-tl.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-tl.png new file mode 100644 index 0000000..b12e704 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-tl.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/container-tr.png b/ogclient/lib/burg/themes/OpenGnsys/images/container-tr.png new file mode 100644 index 0000000..92ed266 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/container-tr.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-b.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-b.png new file mode 100644 index 0000000..7fdf4d3 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-b.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bg.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bg.png new file mode 100644 index 0000000..373414b Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bg.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bl.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bl.png new file mode 100644 index 0000000..1ef93ff Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bl.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bl.xcf b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bl.xcf new file mode 100644 index 0000000..e2b417d Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-bl.xcf differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-br.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-br.png new file mode 100644 index 0000000..b877839 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-br.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-lr.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-lr.png new file mode 100644 index 0000000..9ebb1ba Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-lr.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-spacer.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-spacer.png new file mode 100644 index 0000000..e96e664 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-spacer.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-t.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-t.png new file mode 100644 index 0000000..05720e6 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-t.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-tl.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-tl.png new file mode 100644 index 0000000..d9554e6 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-tl.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/dialog-tr.png b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-tr.png new file mode 100644 index 0000000..9d4123e Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/dialog-tr.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-b.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-b.png new file mode 100644 index 0000000..c8295bb Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-b.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-bl.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-bl.png new file mode 100644 index 0000000..1854229 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-bl.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-br.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-br.png new file mode 100644 index 0000000..ff8871c Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-br.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-l.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-l.png new file mode 100644 index 0000000..3a4fc40 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-l.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-r.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-r.png new file mode 100644 index 0000000..dadd4ac Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-r.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-t.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-t.png new file mode 100644 index 0000000..cd99485 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-t.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-tl.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-tl.png new file mode 100644 index 0000000..8341760 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-tl.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-tr.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-tr.png new file mode 100644 index 0000000..72a05f6 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg-tr.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg.png b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg.png new file mode 100644 index 0000000..92db1e0 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/progressbar-bg.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/text-line-l.png b/ogclient/lib/burg/themes/OpenGnsys/images/text-line-l.png new file mode 100644 index 0000000..ed1852c Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/text-line-l.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/text-line-r.png b/ogclient/lib/burg/themes/OpenGnsys/images/text-line-r.png new file mode 100644 index 0000000..5c9f49a Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/text-line-r.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/tick.png b/ogclient/lib/burg/themes/OpenGnsys/images/tick.png new file mode 100644 index 0000000..292ceb8 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/tick.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/txt-about.png b/ogclient/lib/burg/themes/OpenGnsys/images/txt-about.png new file mode 100644 index 0000000..f104c82 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/txt-about.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/txt-help.png b/ogclient/lib/burg/themes/OpenGnsys/images/txt-help.png new file mode 100644 index 0000000..6fad772 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/txt-help.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/txt-select.png b/ogclient/lib/burg/themes/OpenGnsys/images/txt-select.png new file mode 100644 index 0000000..d459597 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/txt-select.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/txt-tools.png b/ogclient/lib/burg/themes/OpenGnsys/images/txt-tools.png new file mode 100644 index 0000000..d8eadd7 Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/txt-tools.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/images/ubuntu-glow-96.png b/ogclient/lib/burg/themes/OpenGnsys/images/ubuntu-glow-96.png new file mode 100644 index 0000000..b8fd92c Binary files /dev/null and b/ogclient/lib/burg/themes/OpenGnsys/images/ubuntu-glow-96.png differ diff --git a/ogclient/lib/burg/themes/OpenGnsys/menus b/ogclient/lib/burg/themes/OpenGnsys/menus new file mode 100644 index 0000000..f9a13fd --- /dev/null +++ b/ogclient/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/ogclient/lib/burg/themes/OpenGnsys/style b/ogclient/lib/burg/themes/OpenGnsys/style new file mode 100644 index 0000000..325e503 --- /dev/null +++ b/ogclient/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/ogclient/lib/burg/themes/OpenGnsys/theme b/ogclient/lib/burg/themes/OpenGnsys/theme new file mode 100644 index 0000000..4307c18 --- /dev/null +++ b/ogclient/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/ogclient/lib/python3/BootLib.py b/ogclient/lib/python3/BootLib.py index 5224539..bf6f0b9 100644 --- a/ogclient/lib/python3/BootLib.py +++ b/ogclient/lib/python3/BootLib.py @@ -12,7 +12,6 @@ import tempfile import subprocess import shutil import glob -import inspect import ogGlobals import SystemLib @@ -22,7 +21,6 @@ import DiskLib import InventoryLib import FileLib import UEFILib -import CacheLib #/** # ogBoot int_ndisk int_nfilesys [ NVRAMPERM ] [str_kernel str_initrd str_krnlparams] @@ -39,168 +37,6 @@ import CacheLib #@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 #*/ ## -def ogBoot (disk, par, nvramperm=False, params=''): -# Detectar tipo de sistema de archivos y montarlo. - part = DiskLib.ogDiskToDev (disk, par) - if not part: return None - type = InventoryLib.ogGetOsType (disk, par) - if not type: return None -# Error si no puede montar sistema de archivos. - mntdir = FileSystemLib.ogMount (disk, par) - if not mntdir: return None - #params = None - #if 'NVRAMPERM' == nvramperm.upper(): - # nvramperm = True - #else: - # params = nvramperm - # nvramperm = False - - if 'Linux' == type or 'Android' == type: - # Si no se indican, obtiene los parámetros de arranque para Linux. - if not params: - params = ogLinuxBootParameters (disk, par) - # Si no existe y el UEFI buscar en particion ESP - if not params and InventoryLib.ogIsEfiActive(): - esp = DiskLib.ogGetEsp() - efidisk, efipart = esp.split() - params = ogLinuxBootParameters (efidisk, efipart) - params += ' ' + esp - # Si no existe, buscar sistema de archivo /boot en /etc/fstab. - if not params and os.path.exists (f'{mntdir}/etc/fstab'): - # Localizar S.F. /boot en /etc/fstab del S.F. actual. - dev = None - with open (f'{mntdir}/etc/fstab', 'r') as fd: - while True: - l = fd.readline() - if not l: break - parts = l.split() - if '#' != parts[0] and '/boot' == parts[1]: - dev = parts[0] - break - if dev: - fstab_part = DiskLib.ogDevToDisk (dev) - else: - return None - # Montar S.F. de /boot. - fstab_disk, fstab_par = fstab_part.split() - mntdir = FileSystemLib.ogMount (fstab_disk, fstab_par) - if not mntdir: return None - # Buscar los datos de arranque. - params = ogLinuxBootParameters (fstab_disk, fstab_par) - kernel = initrd = append = None - if params: - kernel, initrd, append = params.split (maxsplit=2) - # Si no hay kernel, no hay sistema operativo. - if not kernel or not os.path.exists (f'{mntdir}/{kernel}'): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTOS, f'{disk} {par} ({type})') - return None - # Arrancar de partición distinta a la original. - if os.path.exists (f'{mntdir}/etc'): - append = re.sub ('root=[-+=_/a-zA-Z0-9]* ', f'root={part} ', append) - # Comprobar tipo de sistema. - if InventoryLib.ogIsEfiActive(): - # Comprobar si el Kernel está firmado. - file_out = subprocess.run (['file', '-k', f'{mntdir}/{kernel}'], capture_output=True, text=True).stdout - if not file_out or not 'EFI app' in file_out: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTOS, f'{disk} {par} ({type}, EFI)') - return None - - bootlabel = f'Part-{int(disk):02d}-{int(par):02d}' - bootloader = 'shimx64.efi' - # Obtener parcición EFI. - esp = DiskLib.ogGetEsp() - #efidisk, efipart = esp.split() - # TODO: Comprobamos que existe la BOOTLABEL, si no buscamos por sistema operativo - if '' == FileLib.ogGetPath (src=esp, file=f'EFI/{bootlabel}'): - osversion = InventoryLib.ogGetOsVersion (disk, par) - if 'SUSE' in osversion: - bootlabel = 'opensuse' - elif 'Fedora' in osversion: - bootlabel = 'fedora' - elif 'Ubuntu' in osversion: - bootlabel = 'ubuntu' - else: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'{esp} Boot loader') - return None - - # Crear orden de arranque (con unos valores por defecto). - UEFILib.ogNvramAddEntry (bootlabel, f'/EFI/{bootlabel}/Boot/{bootloader}', nvramperm) - # Marcar próximo arranque y reiniciar. - UEFILib.ogNvramSetNext (bootlabel) - subprocess.run (['reboot']) - else: - # Arranque BIOS: configurar kernel Linux con los parámetros leídos de su GRUB. - subprocess.run (['kexec', '-l', f'{mntdir}{kernel}', f'--append={append}', f'--initrd={mntdir}{initrd}']) - subprocess.Popen (['kexec', '-e']) - elif 'Windows' == type: - # Comprobar tipo de sistema. - if InventoryLib.ogIsEfiActive(): - bootlabel = f'Part-{int(disk):02d}-{int(par):02d}' - # Obtener parcición EFI. - esp = DiskLib.ogGetEsp() - efidisk, efipart = esp.split() - if not efipart: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, 'ESP') - return None - efidir = FileSystemLib.ogMount (efidisk, efipart) - if not efidir: return None - # Comprobar cargador (si no existe buscar por defecto en ESP). - loader = FileLib.ogGetPath (file=f'{efidir}/EFI/{bootlabel}/Boot/bootmgfw.efi') - if not loader: - bootlabel = 'Microsoft' - loader = FileLib.ogGetPath (file=f'{efidir}/EFI/Microsoft/Boot/bootmgfw.efi') - if not loader: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTOS, f'{disk} {par} ({type}, EFI)') - return None - - # Crear orden de arranque (con unos valores por defecto). - l = re.sub ('^.*EFI(.*)$', r'\1', loader) - UEFILib.ogNvramAddEntry (bootlabel, l, nvramperm) - # Marcar próximo arranque y reiniciar. - UEFILib.ogNvramSetNext (bootlabel) - subprocess.run (['reboot']) - else: - # Arranque BIOS: comprueba si hay un cargador de Windows. - for f in ['io.sys', 'ntldr', 'bootmgr']: - file = FileLib.ogGetPath (src=f'{disk} {par}', file=f) - if file: loader=f - if not loader: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTOS, f'{disk} {par} ({type})') - return None - winboot = os.environ.get ('winboot', '') - if 'kexec' == winboot: - # Modo de arranque en caliente (con kexec). - for f in glob.glob (f'{ogGlobals.OGLIB}/grub4dos/*'): - shutil.copy2 (f, mntdir) - disk0 = int(disk)-1 - par0 = int(par)-1 - subprocess.run (['kexec', '-l', f'{mntdir}/grub.exe', '--append=--config-file=root (hd{disk0},{par0}); chainloader (hd{disk0},{par0})/{loader}; tpm --init']) - subprocess.Popen (['kexec', '-e']) - else: - # Modo de arranque por reinicio (con reboot). - subprocess.run (['dd', 'if=/dev/zero', f'of={mntdir}/ogboot.me', 'bs=1024', 'count=3']) - subprocess.run (['dd', 'if=/dev/zero', f'of={mntdir}/ogboot.firstboot', 'bs=1024', 'count=3']) - subprocess.run (['dd', 'if=/dev/zero', f'of={mntdir}/ogboot.secondboot', 'bs=1024', 'count=3']) - v = RegistryLib.ogGetRegistryValue (mntdir, 'SOFTWARE', r'\Microsoft\Windows\CurrentVersion\Run\ogcleannboot') - if not v: - RegistryLib.ogAddRegistryValue (mntdir, 'SOFTWARE', r'\Microsoft\Windows\CurrentVersion\Run\ogcleanboot') - RegistryLib.ogSetRegistryValue (mntdir, 'SOFTWARE', r'\Microsoft\Windows\CurrentVersion\Run\ogcleanboot', r'cmd /c del c:\ogboot.*') - # Activar la partición. - DiskLib.ogSetPartitionActive (disk, par) - subprocess.run (['reboot']) - elif 'MacOS' == type: - # Modo de arranque por reinicio. - # Nota: el cliente tiene que tener configurado correctamente Grub. - if not os.path.exists (f'{mntdir}/boot.mac'): - open (f'{mntdir}/boot.mac', 'w').close() - subprocess.run (['reboot']) - elif 'GrubLoader' == type: - # Reiniciar. - #subprocess.run (['reboot']) - pass - else: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTOS, f'{disk} {par} ({type})') - return None #/** @@ -213,12 +49,6 @@ def ogBoot (disk, par, nvramperm=False, params=''): #@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. #*/ ## -def ogGetWindowsName (disk, par): - mntdir = FileSystemLib.ogMount (disk, par) - if not mntdir: return None - -# Obtener dato del valor de registro. - return RegistryLib.ogGetRegistryValue (mntdir, 'system', r'\ControlSet001\Control\ComputerName\ComputerName\ComputerName') #/** @@ -232,52 +62,6 @@ def ogGetWindowsName (disk, par): #@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar. #@warning Función básica usada por \c ogBoot #*/ ## -def ogLinuxBootParameters (disk, par): -# Detectar id. de tipo de partición y codificar al mnemonico. - mntdir = FileSystemLib.ogMount (disk, par) - if not mntdir: return None - -# Fichero de configuración de GRUB. - confdir = mntdir # Sistema de archivos de arranque (/boot). - if os.path.isdir (f'{mntdir}/boot'): - confdir = f'{mntdir}/boot' # Sist. archivos raíz con directorio boot. - ## original bash code: - ## $MNTDIR/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{2,},{,efi/}EFI/*}/{menu.lst,grub.cfg}; do - conffile = None - for _uno in ['', 'boot']: - for _dos in ['grubMBR/boot', 'grubPARTITION/boot', '']: - for _tres in ['grub', 'grub2', 'EFI/*', 'efi/EFI/*']: - for _cuatro in ['menu.lst', 'grub.cfg']: - path = '/'.join ([mntdir, _uno, _dos, _tres, _cuatro]) - if os.path.exists (path): - conffile = path - if not conffile: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'grub.cfg') - return None - -# Toma del fichero de configuracion los valores del kernel, initrd -# y parámetros de arranque usando las cláusulas por defecto -# ("default" en GRUB1, "set default" en GRUB2) -# y los formatea para que sean compatibles con \c kexec . */ - awk_script = '''BEGIN {cont=-1;} - $1~/^default$/ {sub(/=/," "); def=$2;} - $1~/^set$/ && $2~/^default/ { gsub(/[="]/," "); def=$3; - if (def ~ /saved_entry/) def=0; - } - $1~/^(title|menuentry)$/ {cont++} - $1~/^set$/ && $2~/^root=.\\(hd__DISK__,(msdos|gpt)__PAR__\\).$/ { if (def==0) def=cont; } - $1~/^(kernel|linux(16|efi)?)$/ { if (def==cont) { - kern=$2; - sub($1,""); sub($1,""); sub(/^[ \\t]*/,""); app=$0 - } - } - $1~/^initrd(16|efi)?$/ {if (def==cont) init=$2} - END {if (kern!="") printf("%s %s %s", kern,init,app)} - ''' - awk_script = awk_script.replace ('__DISK__', str (int (disk) - 1)) - awk_script = awk_script.replace ('__PAR__', par) - awk_out = subprocess.run (['awk', awk_script, conffile], capture_output=True, text=True).stdout - return awk_out #/** @@ -321,10 +105,6 @@ def ogSetWindowsName (disk, par, name): #@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. #*/ ## -def ogSetWinlogonUser (disk, par, username): - mntdir = FileSystemLib.ogMount (disk, par) - if not mntdir: return None - RegistryLib.ogSetRegistryValue (mntdir, 'SOFTWARE', r'\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName', username) #/** @@ -336,11 +116,6 @@ def ogSetWinlogonUser (disk, par, username): #@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar. #*/ ## -def ogBootMbrXP (disk): - DISK = DiskLib.ogDiskToDev (disk) - if not DISK: return None - subprocess.run (['ms-sys', '-z', '-f', DISK]) - subprocess.run (['ms-sys', '-m', '-f', DISK]) #/** # ogBootMbrGeneric int_ndisk @@ -351,17 +126,6 @@ def ogBootMbrXP (disk): #@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar. #*/ ## -def ogBootMbrGeneric (disk): - DISK = DiskLib.ogDiskToDev (disk) - if not DISK: return None - subprocess.run (['ms-sys', '-z', '-f', DISK]) - subprocess.run (['ms-sys', '-s', '-f', DISK]) - -# Firma necesaria para Windows equipos UEFI - with open ('/proc/sys/kernel/random/uuid', 'r') as fd: - kernel_random_uuid = fd.read().split ('-')[0] - signature = f'0x{kernel_random_uuid}' - subprocess.run (['ms-sys', '-S', signature, DISK]) @@ -405,10 +169,6 @@ fix_first_sector=yes #@exception OG_ERR_FORMAT Formato incorrecto. #@exception OG_ERR_NOTFOUND Dispositivo de disco no encontrado. #*/ ## -def ogGetBootMbr (disk): - DISK = DiskLib.ogDiskToDev (disk) - if not DISK: return None - subprocess.run (['ms-sys', '-f', DISK]) #/** # ogWindowsBootParameters int_ndisk int_parition @@ -654,9 +414,6 @@ def ogGrubInstallMbr (disk, par, checkos='FALSE', kernelparam=''): if InventoryLib.ogIsEfiActive(): esp = DiskLib.ogGetEsp() - if not esp: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, 'ESP') - return None efidisk, efipart = esp.split() # Comprobamos que exista ESP y el directorio para ubuntu efisecondstage = FileSystemLib.ogMount (efidisk, efipart) @@ -682,7 +439,7 @@ def ogGrubInstallMbr (disk, par, checkos='FALSE', kernelparam=''): prefixsecondstage = '' # Reactivamos el grub con el grub.cfg original. else: # SI Reconfigurar segunda etapa (grub.cfg) == TRUE #llamada a updateBootCache para que aloje la primera fase del ogLive - subprocess.run ([f'{ogGlobals.OGSCRIPTS}/updateBootCache.py'], check=True) + subprocess.run ([f'{ogGlobals.OGSCRIPTS}/updateBootCache.py'], check=True) ## TODO: check that this works if InventoryLib.ogIsEfiActive(): # UEFI: grubSintax necesita grub.cfg para detectar los kernels: si no existe recupero backup. @@ -696,7 +453,7 @@ def ogGrubInstallMbr (disk, par, checkos='FALSE', kernelparam=''): fd.write ('GRUB_DISABLE_RECOVERY="true"\n') fd.write ('GRUB_DISABLE_LINUX_UUID="true"\n') - os.makedirs (f'{secondstage}{prefixsecondstage}/boot/grub/', exist_ok=True) #Preparar configuración segunda etapa: crear ubicacion + os.makedirs (f'{secondstage}{prefixsecondstage}/boot/grub/') #Preparar configuración segunda etapa: crear ubicacion subprocess.run (['sed', '-i', 's/^set -e/#set -e/', '/etc/grub.d/00_header']) #Preparar configuración segunda etapa: crear cabecera del fichero (ingnorar errores) # (ogLive 5.0) Si 'pkgdatadir' está vacía ponemos valor de otros ogLive subprocess.run (['sed', '-i', r'/grub-mkconfig_lib/i\pkgdatadir=${pkgdatadir:-"${datarootdir}/grub"}', '/etc/grub.d/00_header']) @@ -818,14 +575,11 @@ def ogGrubInstallPartition (disk, par, checkos='FALSE', kernelparam=''): with open (f'{secondstage}{prefixsecondstage}/boot/grub/grub.cfg', 'a') as fd: fd.write (out + '\n') -#Instalar el grub eval = subprocess.run (['grub-install', '--force'] + efioptgrub + [f'--root-directory={secondstage}{prefixsecondstage}', firststage]).returncode -# Movemos el grubx64.efi - if InventoryLib.ogIsEfiActive(): + if InventoryLib.ogIsEfiActive(): # Movemos el grubx64.efi for b in (glob.glob (f'{efisecondstage}/EFI/{efisubdir}/EFI/BOOT/*')): - bn = os.path.basename (b) - os.rename (f'{efisecondstage}/EFI/{efisubdir}/EFI/BOOT/{bn}', f'{efisecondstage}/EFI/{efisubdir}/Boot/{bn}') + os.rename (f'{efisecondstage}/EFI/{efisubdir}/EFI/BOOT/{b}', f'{efisecondstage}/EFI/{efisubdir}/Boot/{b}') shutil.rmtree (f'{efisecondstage}/EFI/{efisubdir}/EFI') shutil.copy2 ('/usr/lib/shim/shimx64.efi.signed', f'{efisecondstage}/EFI/{efisubdir}/Boot/shimx64.efi') # Nombre OpenGnsys para cargador @@ -914,30 +668,6 @@ def ogConfigureFstab (disk, par): #@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar. #@note Si no se indica nombre, se asigna un valor por defecto. #*/ ## -def ogSetLinuxName (disk, par, hostname='pc'): -# Montar el sistema de archivos. - mntdir = FileSystemLib.ogMount (disk, par) - if not mntdir: return None - - etc = FileLib.ogGetPath (src=f'{disk} {par}', file='/etc') - - if os.path.isdir (etc): - #cambio de nombre en hostname - with open (f'{etc}/hostname', 'w') as fd: - fd.write (f'{hostname}\n') - #Opcion A para cambio de nombre en hosts - #sed "/127.0.1.1/ c\127.0.1.1 \t $HOSTNAME" $ETC/hosts > /tmp/hosts && cp /tmp/hosts $ETC/ && rm /tmp/hosts - #Opcion B componer fichero de hosts - with open (f'{etc}/hosts', 'w') as fd: - fd.write ('127.0.0.1 localhost\n') - fd.write (f'127.0.1.1 {hostname}\n') - fd.write ('\n') - fd.write ('# The following lines are desirable for IPv6 capable hosts\n') - fd.write ('::1 ip6-localhost ip6-loopback\n') - fd.write ('fe00::0 ip6-localnet\n') - fd.write ('ff00::0 ip6-mcastprefix\n') - fd.write ('ff02::1 ip6-allnodes\n') - fd.write ('ff02::2 ip6-allrouters\n') @@ -977,89 +707,17 @@ def ogCleanLinuxDevices (disk, par): # /// FIXME: Solo para el grub instalado en MBR por Opengnsys, ampliar para más casos. #*/ ## - -def ogGrubAddOgLive (disk, par, timeout=None, offline=''): - oglivedir = os.environ.get ('oglivedir', 'ogLive') - # Error si no existe el kernel y el initrd en la cache. - # Falta crear nuevo codigo de error. - if not os.path.exists (f'{ogGlobals.OGCAC}/boot/{oglivedir}/ogvmlinuz') or not os.path.exists (f'{ogGlobals.OGCAC}/boot/{oglivedir}/oginitrd.img'): - SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_NOTFOUND, 'CACHE: ogvmlinuz, oginitrd.img') - return None - - # Archivo de configuracion del grub - dirmount = FileSystemLib.ogMount (disk, par) - grubcfg = f'{dirmount}/boot/grubMBR/boot/grub/grub.cfg' - - # Error si no existe archivo del grub - if not os.path.exists (grubcfg): - SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_NOTFOUND, grubcfg) - return None - - # Si existe la entrada de opengnsys, se borra - grubcfg_contents = '' - with open (grubcfg, 'r') as fd: - grubcfg_contents = fd.read() - if 'menuentry Opengnsys' in grubcfg_contents: - subprocess.run (['sed', '-ie', '/menuentry Opengnsys/,+6d', grubcfg]) - - # Tipo de tabla de particiones - parttabletype = DiskLib.ogGetPartitionTableType (disk) - parttabletype = parttabletype.lower() - - # Localizacion de la cache - cachepart = CacheLib.ogFindCache() - if not cachepart: - SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_NOTCACHE, '') - return None - numdisk, numpart = cachepart.split() - numdisk = int (numdisk) - 1 - # kernel y sus opciones. Pasamos a modo usuario - proc_cmdline = '' - with open ('/proc/cmdline', 'r') as fd: - proc_cmdline = fd.read().strip() - proc_cmdline = re.sub ('^.*linuz', '', proc_cmdline) - proc_cmdline = re.sub ('ogactiveadmin=[a-z]*', '', proc_cmdline) - kernel = f'/boot/{oglivedir}/ogvmlinuz {proc_cmdline}' - - # Configuracion offline si existe parametro - STATUS = '' - if not offline: offline = '' - if 'offline' in offline: STATUS = 'offline' - if 'online' in offline: STATUS = 'online' - if STATUS: - kernel = re.sub ('ogprotocol=[a-z]* ', 'ogprotocol=local ', kernel) - kernel += f' ogstatus={STATUS}' - - # Numero de línea de la primera entrada del grub. - grep_out = subprocess.run (['grep', '--line-number', '--max-count', '1', '^menuentry', grubcfg], capture_output=True, text=True).stdout - numline, _ = grep_out.split (':', maxsplit=1) - # Texto de la entrada de opengnsys - menuentry = f'''menuentry "OpenGnsys" --class opengnsys --class gnu --class os {{ \\ -\tinsmod part_{parttabletype} \\ -\tinsmod ext2 \\ -\tset root='(hd{numdisk},{parttabletype}{numpart})' \\ -\tlinux {kernel} \\ -\tinitrd /boot/{oglivedir}/oginitrd.img \\ -}}''' - - - # Insertamos la entrada de opengnsys antes de la primera entrada existente. - subprocess.run (['sed', '-i', f'{numline}i\\ {menuentry}', grubcfg]) - - # Ponemos que la entrada por defecto sea la primera. - subprocess.run (['sed', '-i', f's/set.*default.*$/set default="0"/g', grubcfg]) - - # Si me dan valor para timeout lo cambio en el grub. - if timeout: - subprocess.run (['sed', '-i', f's/timeout=.*$/timeout={timeout}/g', grubcfg]) - #/** # ogGrubHidePartitions num_disk num_part #@brief ver ogBootLoaderHidePartitions #@see ogBootLoaderHidePartitions #*/ ## -def ogGrubHidePartitions (disk, par, datadisk=None, datapar=None): - return ogBootLoaderHidePartitions (disk, par, datadisk, datapar) + +#/** +# ogBurgHidePartitions num_disk num_part +#@brief ver ogBootLoaderHidePartitions +#@see ogBootLoaderHidePartitions +#*/ ## #/** # ogBootLoaderHidePartitions num_disk num_part @@ -1073,89 +731,23 @@ def ogGrubHidePartitions (disk, par, datadisk=None, datapar=None): #@exception No existe archivo de configuracion del grub/burg. #*/ -def ogBootLoaderHidePartitions (disk, par, datadisk=None, datapar=None): - # Nombre de la función que llama a esta. - func = inspect.stack()[1][3] - - # Si no existe $4 pongo un valor imposible para la partición de datos - if datapar: - partdata = DiskLib.ogDiskToDev (datadisk, datapar) - else: - partdata = '0' - - # Archivo de configuracion del grub - DIRMOUNT = FileSystemLib.ogMount (disk, par) - # La función debe ser llamanda desde ogGrubHidePartitions or ogBurgHidePartitions. - if 'ogGrubHidePartitions' == func: - cfgfile = f'{DIRMOUNT}/boot/grubMBR/boot/grub/grub.cfg' - else: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'Use ogGrubHidePartitions') - return None - - # Error si no existe archivo del grub - if not os.path.exists (cfgfile): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, cfgfile) - return None - - # Si solo hay una particion de Windows me salgo - num_ntfs = 0 - disks = DiskLib.ogDiskToDev() - fdisk_out = subprocess.run (['fdisk', '-l']+disks, capture_output=True, text=True).stdout - for l in fdisk_out.splitlines(): - if 'NTFS' in l: num_ntfs += 1 - if 1 == num_ntfs: return True - - # Elimino llamadas a parttool, se han incluido en otras ejecuciones de esta funcion. - subprocess.run (['sed', '-i', '/parttool/d', cfgfile]) - - parttabletype = DiskLib.ogGetPartitionTableType (disk) - parttabletype = parttabletype.lower() - - # Entradas de Windows: numero de linea y particion. De mayor a menor. - #1:/dev/sda2 - #2:/dev/sda3 - awk_out = subprocess.run (f''' - awk '/menuentry.*Windows/ {{gsub(/\\)"/, ""); gsub(/^.*dev/,""); print NR":/dev"$1}} ' {cfgfile} - ''', shell=True, text=True, capture_output=True).stdout - if awk_out: - winentry = awk_out.splitlines() - winentry.reverse() - else: - winentry = [] - - # Particiones de Windows, pueden no estar en el grub. - winpart = [] - for l in fdisk_out.splitlines(): ## aprovechamos la variable fdisk_out de antes - if 'NTFS' not in l: continue - items = l.split (' ') - winpart.append (items[0]) - winpart.reverse() - - # Modifico todas las entradas de Windows. - for entry in winentry: - line, part = entry.split (':') - # En cada entrada, oculto o muestro cada particion. - text = '' - for parthidden in winpart: - # Muestro la particion de la entrada actual y la de datos. - if parthidden == part or parthidden == partdata: - hidden = '-' - else: - hidden = '+' - numdisk, numpart = DiskLib.ogDevToDisk (parthidden).split() - numdisk = int (numdisk) - numpart = int (numpart) - text = f'\tparttool (hd{numdisk-1},{parttabletype}{numpart}) hidden{hidden} \n{text}' - subprocess.run (['sed', '-i', f'{line}a\\ {text}', cfgfile]) - # Activamos la particion que se inicia en todas las entradas de windows. - subprocess.run (['sed', '-i', '/chainloader/i\\\tparttool ${root} boot+', cfgfile]) #/** # ogGrubDeleteEntry num_disk num_part num_disk_delete num_part_delete #@brief ver ogBootLoaderDeleteEntry #@see ogBootLoaderDeleteEntry #*/ -def ogGrubDeleteEntry (disk, par, diskdel, pardel): - return ogBootLoaderDeleteEntry (disk, par, diskdel, pardel) + +#/** +# ogBurgDeleteEntry num_disk num_part num_disk_delete num_part_delete +#@brief ver ogBootLoaderDeleteEntry +#@see ogBootLoaderDeleteEntry +#*/ + +#/** +# ogRefindDeleteEntry num_disk_delete num_part_delete +#@brief ver ogBootLoaderDeleteEntry +#@see ogBootLoaderDeleteEntry +#*/ #/** # ogBootLoaderDeleteEntry num_disk num_part num_part_delete @@ -1164,73 +756,43 @@ def ogGrubDeleteEntry (disk, par, diskdel, pardel): #@param 2 Numero de particion donde esta el grub #@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 +#@note Tiene que ser llamada desde ogGrubDeleteEntry, ogBurgDeleteEntry o ogRefindDeleteEntry #@return (nada) -#@exception OG_ERR_FORMAT Use ogGrubDeleteEntry +#@exception OG_ERR_FORMAT Use ogGrubDeleteEntry or ogBurgDeleteEntry. #@exception OG_ERR_FORMAT Formato incorrecto. #@exception OG_ERR_NOTFOUND No existe archivo de configuracion del grub. #*/ ## -def ogBootLoaderDeleteEntry (disk, par, diskdel, pardel): - # Nombre de la función que llama a esta. - func = inspect.stack()[1][3] +#/** +# 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 +#*/ ## - # Archivo de configuracion del grub - dirmount = FileSystemLib.ogMount (disk, par) - # La función debe ser llamanda desde ogGrubDeleteEntry, ogBurgDeleteEntry or ogRefindDeleteEntry. - if 'ogGrubDeleteEntry' == func: - cfgfile = f'{dirmount}/boot/grubMBR/boot/grub/grub.cfg' - else: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'Use ogGrubDeleteEntry') - return None - - # Dispositivo - label = DiskLib.ogDiskToDev (diskdel, pardel) - - # Error si no existe archivo de configuración - if not os.path.exists (cfgfile): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, cfgfile) - return None - - # Numero de linea de cada entrada. - menuentry = [] - grep_out = subprocess.run (['grep', '-n', '-e', 'menuentry', cfgfile], capture_output=True, text=True).stdout - if grep_out: - for l in grep_out.splitlines(): - lineno, _ = l.split (':', maxsplit=1) - menuentry.append (lineno) - menuentry.reverse() - - # Entradas que hay que borrar. - deleteentry = [] - grep_out = subprocess.run (['grep', '-n', f'menuentry.*{label}', cfgfile], capture_output=True, text=True).stdout - if grep_out: - for l in grep_out.splitlines(): - lineno, _ = l.split (':', maxsplit=1) - deleteentry.append (lineno) - - # Si no hay entradas para borrar me salgo con aviso - if not deleteentry: - SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_NOTFOUND, f'Menuentry {label}') - return None - - # Recorremos el fichero del final hacia el principio. - with open (cfgfile, 'r') as fd: - endentry = len (fd.read().splitlines()) - for entry in menuentry: - # Comprobamos si hay que borrar la entrada. - if entry in deleteentry: - endentry -= 1 - subprocess.run (['sed', '-i', '-e', f'{entry},{endentry}d', cfgfile]) - # Guardamos el número de línea de la entrada, que sera el final de la siguiente. - endentry = entry #/** # ogGrubDefaultEntry int_disk_GRUGCFG int_partition_GRUBCFG int_disk_default_entry int_npartition_default_entry #@brief ver ogBootLoaderDefaultEntry #@see ogBootLoaderDefaultEntry #*/ ## -def ogGrubDefaultEntry (disk, par, diskdefault, pardefault): - return ogBootLoaderDefaultEntry (disk, par, diskdefault, pardefault) + +#/** +# ogBurgDefaultEntry int_disk_BURGCFG int_partition_BURGCFG int_disk_default_entry int_npartition_default_entry +#@brief ver ogBootLoaderDefaultEntry +#@see ogBootLoaderDefaultEntry +#*/ ## + + +#/** +# ogRefindDefaultEntry int_disk_default_entry int_npartition_default_entry +#@brief ver ogBootLoaderDefaultEntry +#@see ogBootLoaderDefaultEntry +#*/ ## #/** # ogBootLoaderDefaultEntry int_disk_CFG int_partition_CFG int_disk_default_entry int_npartition_default_entry @@ -1245,64 +807,25 @@ def ogGrubDefaultEntry (disk, par, diskdefault, pardefault): #@exception OG_ERR_OUTOFLIMIT Param $3 no es entero. #@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: burg.cfg. #*/ ## -def ogBootLoaderDefaultEntry (disk, par, diskdefault, pardefault): -# Nombre de la función que llama a esta. - func = inspect.stack()[1][3] - -# Error si no puede montar sistema de archivos. - dirmount = FileSystemLib.ogMount (disk, par) - if not dirmount: return None - -# Comprobamos que exista fichero de configuración -# La función debe ser llamanda desde ogGrubDefaultEntry, ogBurgDefaultEntry or ogRefindDefaultEntry. - if 'ogGrubDefaultEntry' == func: - cfgfile = f'{dirmount}/boot/grubMBR/boot/grub/grub.cfg' - else: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'Use ogGrubDefaultEntry') - return None - -# Error si no existe archivo de configuración - if not os.path.exists (cfgfile): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, cfgfile) - return None - -# Dispositivo - label = DiskLib.ogDiskToDev (diskdefault, pardefault) - -# Número de línea de la entrada por defecto en CFGFILE (primera de la partición). - grep_out = subprocess.run (['grep', '--line-number', '--max-count', '1', f'menuentry.*{label}', cfgfile], capture_output=True, text=True).stdout - if not grep_out: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'menuentry {label}') - return None - defaultentry, _ = grep_out.split (':', maxsplit=1) - -# Si no hay entradas para borrar me salgo con aviso - if not defaultentry: - SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_NOTFOUND, f'No menuentry {label}') - return None - -# Número de la de linea por defecto en el menú de usuario - menuentry = subprocess.run (f'grep -n -e menuentry {cfgfile}| cut -d: -f1 | grep -n {defaultentry} |cut -d: -f1', shell=True, text=True, capture_output=True).stdout - if not menuentry: return None - menuentry = int (menuentry) - # En grub y burg las líneas empiezan a contar desde cero - menuentry -= 1 - subprocess.run (['sed', '--regexp-extended', '-i', f's/set default="?[0-9]*"?$/set default="{menuentry}"/g', cfgfile]) - - MSG = f'ogGlobals.lang.MSG_HELP_{func}' - try: MSG = eval (MSG) - except: MSG = '' - if '.' == MSG[-1]: MSG=MSG[0:-1] - print (f'{MSG}: {disk} {par} {diskdefault} {pardefault}') - return True #/** # ogGrubOgliveDefaultEntry num_disk num_part #@brief ver ogBootLoaderOgliveDefaultEntry #@see ogBootLoaderOgliveDefaultEntry #*/ ## -def ogGrubOgliveDefaultEntry (disk, par): - return ogBootLoaderOgliveDefaultEntry (disk, par) + +#/** +# ogBurgOgliveDefaultEntry num_disk num_part +#@brief ver ogBootLoaderOgliveDefaultEntry +#@see ogBootLoaderOgliveDefaultEntry +#*/ ## + + +#/** +# ogRefindOgliveDefaultEntry +#@brief ver ogBootLoaderOgliveDefaultEntry +#@see ogBootLoaderOgliveDefaultEntry +#*/ ## #/** @@ -1316,49 +839,6 @@ def ogGrubOgliveDefaultEntry (disk, par): #@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: burg.cfg. #@exception OG_ERR_NOTFOUND Entrada de OgLive no encontrada en burg.cfg. #*/ ## -def ogBootLoaderOgliveDefaultEntry (disk, par): -# Nombre de la función que llama a esta. - func = inspect.stack()[1][3] - -# Error si no puede montar sistema de archivos. - PART = FileSystemLib.ogMount (disk, par) - if not PART: return None -# La función debe ser llamanda desde ogGrubOgliveDefaultEntry, ogBurgOgliveDefaultEntry or ogRefindOgliveDefaultEntry. - if 'ogGrubOgliveDefaultEntry' == func: - cfgfile = f'{PART}/boot/grubMBR/boot/grub/grub.cfg' - else: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'Use ogGrubOgliveDefaultEntry') - return None - -# Comprobamos que exista fichero de configuración - if not os.path.exists (cfgfile): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, cfgfile) - return None - -# Detectamos cual es la entrada de ogLive - numentry = 0 - with open (cfgfile, 'r') as fd: - while True: - l = fd.readline() - if not l: break - if l.startswith ('menuentry'): - numentry += 1 - if 'OpenGnsys Live' in l: break - -# Si no existe entrada de ogLive nos salimos - if not numentry: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'menuentry OpenGnsys Live in {cfgfile}') - return None - - numentry -= 1 - subprocess.run (['sed', '--regexp-extended', '-i', f's/set default="?[0-9]+"?/set default="{numentry}"/g', cfgfile]) - - MSG = f'ogGlobals.lang.MSG_HELP_{func}' - try: MSG = eval (MSG) - except: MSG = '' - if '.' == MSG[-1]: MSG=MSG[0:-1] - print (f'{MSG}: {disk} {par}') - return True #/** @@ -1373,44 +853,6 @@ def ogBootLoaderOgliveDefaultEntry (disk, par): #@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar (ogMount). #@exception OG_ERR_NOTFOUND No encuentra archivo de configuración del grub. #*/ ## -def ogGrubSecurity (disk, par, user='root', passwd=''): -#localizar disco segunda etapa del grub - secondstage = FileSystemLib.ogMount (disk, par) - if not secondstage: return None - - ## original bash code: - ## $SECONDSTAGE/{,boot/}{{grubMBR,grubPARTITION}/boot/,}{grub{,2},{,efi/}EFI/*}/{menu.lst,grub.cfg,grub.cfg.backup.og} - grubcfg = [] - for _uno in ['', 'boot']: - for _dos in ['grubMBR/boot', 'grubPARTITION/boot', '']: - for _tres in ['grub', 'grub2', 'EFI/*', 'efi/EFI/*']: - for _cuatro in ['menu.lst', 'grub.cfg', 'grub.cfg.backup.og']: - path = '/'.join ([secondstage, _uno, _dos, _tres, _cuatro]) - grubcfg += glob.glob (path) - -# comprobamos que exista el archivo de configuración. - if not grubcfg: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'grub.cfg') - return None - - if passwd: - encryptpasswd = subprocess.run (['grub-mkpasswd-pbkdf2'], input=f'{passwd}\n{passwd}', text=True, capture_output=True).stdout - if encryptpasswd: - lines = encryptpasswd.strip().splitlines() - encryptpasswd = lines[-1] - encryptpasswd = re.sub ('^.*grub', 'grub', encryptpasswd) - - for file in grubcfg: - # Eliminamos configuración anterior - subprocess.run (['sed', '-i', '-e', '/superusers/d', '-e', '/password_pbkdf2/d', file]) - - # Configuramos grub.cfg para que sólo permita editar o entrar en línea de comandos al usuario especificado - if passwd: - subprocess.run (['sed', '-i', f'1i\\password_pbkdf2 {user} {encryptpasswd}', file]) - subprocess.run (['sed', '-i', f'1i\\set superusers="{user}"', file]) - - # Permitimos que se seleccionen las entradas - subprocess.run (['sed', '-i', '/menuentry /s/{/--unrestricted {/', file]) #/** @@ -1419,6 +861,19 @@ def ogGrubSecurity (disk, par, user='root', passwd=''): #@see ogBootLoaderSetTheme #*/ ## +#/** +# ogBurgSetTheme num_disk num_part str_theme +#@brief ver ogBootLoaderSetTheme +#@see ogBootLoaderSetTheme +#*/ ## + + +#/** +# ogRefindSetTheme str_theme +#@brief ver ogBootLoaderSetTheme +#@see ogBootLoaderSetTheme +#*/ ## + #/** # ogBootLoaderSetTheme @@ -1441,6 +896,12 @@ def ogGrubSecurity (disk, par, user='root', passwd=''): #@see ogBootLoaderSetTheme #*/ ## +#/** +# ogBurgSetAdminKeys num_disk num_part str_bolean +#@brief ver ogBootLoaderSetAdminKeys +#@see ogBootLoaderSetAdminKeys +#*/ ## + #/** @@ -1463,8 +924,19 @@ def ogGrubSecurity (disk, par, user='root', passwd=''): #@brief ver ogBootLoaderSetTimeOut #@see ogBootLoaderSetTimeOut #*/ ## -def ogGrubSetTimeOut (disk, par, timeout): - return ogBootLoaderSetTimeOut (disk, par, timeout) + +#/** +# ogBurgSetTimeOut num_disk num_part str_bolean +#@brief ver ogBootLoaderSetTimeOut +#@see ogBootLoaderSetTimeOut +#*/ ## + + +#/** +# ogRefindSetTimeOut int_timeout_second +#@brief ver ogBootLoaderSetTimeOut +#@see ogBootLoaderSetTimeOut +#*/ ## #/** # ogBootLoaderSetTimeOut @@ -1478,29 +950,6 @@ def ogGrubSetTimeOut (disk, par, timeout): #@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. #*/ ## -def ogBootLoaderSetTimeOut (disk, par, timeout): -# Nombre de la función que llama a esta. - func = inspect.stack()[1][3] - -# Error si no puede montar sistema de archivos. - PART = FileSystemLib.ogMount (disk, par) - if not PART: return None -# La función debe ser llamanda desde ogGrubSetTimeOut, ogBurgSetTimeOut or ogRefindSetTimeOut. - if 'ogGrubSetTimeOut' == func: - bootloader = 'grub' - bootloaderdir = 'boot/grubMBR' - cfgfile = f'{PART}/boot/grubMBR/boot/grub/grub.cfg' - else: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'Use ogGrubSetTimeOut') - return None - -# Comprobamos que exista fichero de configuración - if not os.path.exists (cfgfile): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, cfgfile) - return None - -# Asignamos el timeOut. - subprocess.run (['sed', '-i', f's/timeout=.*$/timeout={timeout}/g', cfgfile]) #/** @@ -1509,6 +958,12 @@ def ogBootLoaderSetTimeOut (disk, par, timeout): #@see ogBootLoaderSetResolution #*/ ## +#/** +# ogBurgSetResolution num_disk num_part str_bolean +#@brief ver ogBootLoaderSetResolution +#@see ogBootLoaderSetResolution +#*/ ## + #/** @@ -1537,6 +992,18 @@ def ogBootLoaderSetTimeOut (disk, par, timeout): #@exception OG_ERR_NOTFOUND Fichero de configuración no encontrado: grub.cfg burg.cfg. #*/ ## +# ogRefindInstall bool_autoconfig +#@brief Instala y actualiza el gestor rEFInd en la particion EFI +#@param bolean_Check__auto_config true | false[default] +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_NOTFOUND No se encuentra la partición ESP. +#@exception OG_ERR_NOTFOUND No se encuentra shimx64.efi.signed. +#@exception OG_ERR_NOTFOUND No se encuentra refind-install o refind en OGLIB +#@exception OG_ERR_PARTITION No se puede montar la partición ESP. +#@note Refind debe estar instalado en el ogLive o compartido en OGLIB +#*/ ## + #/** # ogGrub4dosInstallMbr int_ndisk #@brief Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux. @@ -1549,54 +1016,3 @@ def ogBootLoaderSetTimeOut (disk, par, timeout): #@exception OG_ERR_NOMSDOS Disco duro no particioniado en modo msdos #@exception OG_ERR_NOTWRITE Particion no modificable. #*/ ## - -def ogGrub4dosInstallMbr (disk, par): -#Controlar existencia de disco y particion - device = DiskLib.ogDiskToDev (disk) - if not device: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, '') - return None - mountdisk = FileSystemLib.ogMount (disk, par) - if not mountdisk: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, ogGlobals.lang.MSG_ERROR) - return None -#Controlar acceso de escritura a la particion - if FileSystemLib.ogIsReadonly (disk, par): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTWRITE, f': {disk} {par}') - return None -#Controlar disco no uefi - if InventoryLib.ogIsEfiActive(): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTBIOS, ' : grub4dos solo soporta PC con bios legacy') - return None -#Controlar particionado tipo msdos - ptt = DiskLib.ogGetPartitionTableType (disk) - if 'MSDOS' != ptt: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOMSDOS, ': grub2dos requiere particionado tipo MSDOS') - return None -#Controlar la existencia del grub4dos con acceso a ntfs - bindir = f'{ogGlobals.OGLIB}/grub4dos/grub4dos-0.4.6a' - if not os.path.exists (f'{bindir}/bootlace.com'): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f': {bindir}/bootlace.com') - return None - -#instalar el bootloader de grlrd en el MBR - subprocess.run ([f'{bindir}/bootlace64.com', device], capture_output=True) -#copiar grld a la particion - shutil.copy2 (f'{bindir}/grldr', mountdisk) -#Instalar y configurar grub4dos - if os.path.exists (f'{mountdisk}/boot/grub/menu.lst'): - os.unlink (f'{mountdisk}/boot/grub/menu.lst') - os.rmdir (f'/{mountdisk}/boot/grub') - if not os.path.exists (f'{mountdisk}/boot/grub/menu.lst'): - os.makedirs (f'/{mountdisk}/boot/grub', exist_ok=True) - open (f'/{mountdisk}/boot/grub/menu.lst', 'w').close() - grubdisk = int (disk) - 1 - with open (f'/{mountdisk}/boot/grub/menu.lst', 'w') as fd: - fd.write ('##NO-TOCAR-ESTA-LINEA MBR\n') - fd.write ('timeout 0\n') - fd.write ('title MBR\n') - fd.write (f'root (hd{grubdisk},0)\n') - fd.write (f'chainloader (hd{grubdisk},0)+1\n') - fd.write ('boot\n') - fd.write ('EOT\n') - fd.write ('\n') diff --git a/ogclient/lib/python3/CacheLib.py b/ogclient/lib/python3/CacheLib.py index 2918526..1c4357c 100644 --- a/ogclient/lib/python3/CacheLib.py +++ b/ogclient/lib/python3/CacheLib.py @@ -9,6 +9,7 @@ import ogGlobals import SystemLib import DiskLib import FileSystemLib +import CacheLib #/** # ogCreateCache [int_ndisk] int_partsize @@ -60,9 +61,11 @@ def ogCreateCache (ndsk=1, part=4, sizecache=0): prev_part = part - i if prev_part <= 0: break ENDPREVPART = DiskLib.ogGetLastSector (ndsk, prev_part) + print (f'nati got endprevpart ({ENDPREVPART})') if ENDPREVPART: break i += 1 if not ENDPREVPART: + print (f'nati no endprevpart, assuming 0') ENDPREVPART=0 #SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, ndsk) #return None @@ -70,6 +73,7 @@ def ogCreateCache (ndsk=1, part=4, sizecache=0): MINSIZE = 25000 MAXSIZE = END if SIZE < MINSIZE or SIZE > MAXSIZE or START < ENDPREVPART: + print (f'nati size ({SIZE}) < minsize ({MINSIZE}) or size > maxsize ({MAXSIZE}) or start ({START}) < endprevpart ({ENDPREVPART})') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, ndsk) return None @@ -79,20 +83,23 @@ def ogCreateCache (ndsk=1, part=4, sizecache=0): # En el caso de ser disco GPT, de momento se borra la particion y se vuelve a crear, # por lo que se pierden los datos. pttype = DiskLib.ogGetPartitionTableType (ndsk) + print (f'nati pttype ({pttype})') if not pttype: pttype = 'MSDOS' DiskLib.ogCreatePartitionTable (ndsk, pttype) get_ptt = DiskLib.ogGetPartitionTableType (ndsk) + print (f'nati get_ptt ({get_ptt})') if 'GPT' == get_ptt: # Si la tabla de particiones no es valida, volver a generarla. - if subprocess.run (['sgdisk', '-p', DISK], capture_output=True, text=True).returncode: - subprocess.run (['gdisk', DISK], input='2\nw\nY\n', capture_output=True, text=True) + if subprocess.run (['sgdisk', '-p', DISK]).returncode: + subprocess.run (['gdisk', DISK], input='2\nw\nY\n', text=True) # Si existe la cache se borra previamente if ogFindCache(): ogDeleteCache() # Capturamos el codigo de particion GPT para cache # PATCH - Cuando es GPT, la particion con codigo CACHE (CA00) no existe y no puede crearse, se cambia por LINUX (8300) ID = DiskLib.ogTypeToId ('LINUX', 'GPT') + print (f'nati ID ({ID})') subprocess.run (['sgdisk', DISK, f'-n{part}:{START}:{END}', f'-c{part}:CACHE', f'-t{part}:{ID}']) elif 'MSDOS' == get_ptt: # Si la tabla de particiones no es valida, volver a generarla. @@ -100,6 +107,7 @@ def ogCreateCache (ndsk=1, part=4, sizecache=0): subprocess.run (['fdisk', DISK], input='w\n', text=True) # Definir particiones y notificar al kernel. ID = DiskLib.ogTypeToId ('CACHE', 'MSDOS') + print (f'nati ID ({ID})') # Salvamos la configuración de las particiones e incluimos la cache. tmp = subprocess.run (['sfdisk', '--dump', DISK], capture_output=True, text=True).stdout.splitlines() tmp = [ x for x in tmp if f'{DISK}{part}' not in x ] @@ -110,10 +118,10 @@ def ogCreateCache (ndsk=1, part=4, sizecache=0): tmp = [UNIT, ''] + tmp # Guardamos nueva configuración en el disco. i = '\n'.join(tmp) + print (f'nati i ({i})') subprocess.run (['sfdisk', '--no-reread', DISK], input=i, text=True) # Actualiza la tabla de particiones en el kernel. DiskLib.ogUpdatePartitionTable() - return True @@ -232,7 +240,8 @@ def ogFormatCache(): os.makedirs (j, exist_ok=True) # Incluir kernel e Initrd del ogLive - subprocess.run ([f'{ogGlobals.OGSCRIPTS}/updateBootCache.py']) + ## como lo llamo sin especificar el path entero? + #subprocess.run (['scripts/updateBootCache.py']) ## TODO #/** @@ -356,5 +365,5 @@ def ogUnmountCache(): #@return lo mismo que devuelve initCache #*/ ## def initCache (*args): - p = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/initCache.py'] + list(args)) + p = subprocess.run (['/opt/opengnsys/images/nati/client/shared/scripts/initCache.py'] + list(args)) return p.returncode diff --git a/ogclient/lib/python3/DiskLib.py b/ogclient/lib/python3/DiskLib.py index 1213358..5b95b05 100644 --- a/ogclient/lib/python3/DiskLib.py +++ b/ogclient/lib/python3/DiskLib.py @@ -76,7 +76,7 @@ def ogCreatePartitions (disk, parts): CACHEPART = CacheLib.ogFindCache() if CACHEPART: cache_disk, cache_part = CACHEPART.split() - if ND == int (cache_disk): + if ND == cache_disk: CACHESIZE = int (CacheLib.ogGetCacheSize()) * 2 # Sector de inicio (la partición 1 empieza en el sector 63). IODISCO = ogDiskToDev (disk) @@ -100,6 +100,7 @@ def ogCreatePartitions (disk, parts): SECTORS -= CACHESIZE PART = 1 + print (f'START ({START}) SECTORS ({SECTORS}) PART ({PART})') sfdisk_input = 'unit: sectors\n\n' NVME_PREFIX = 'p' if 'nvme' in DISK else '' @@ -108,7 +109,6 @@ def ogCreatePartitions (disk, parts): if f'{ND} {PART}' == CACHEPART and CACHESIZE: sfdisk_input += f'{DISK}{NVME_PREFIX}{PART} : start={SECTORS+1}, size={CACHESIZE}, Id=ca\n' PART += 1 - continue # Leer formato de cada parámetro - Tipo:Tamaño TYPE, SIZE = p.split (':') @@ -176,10 +176,12 @@ def ogCreatePartitions (disk, parts): ogCreatePartitionTable (ND) # Definir particiones y notificar al kernel. + #print (f'nati: about to run sfdisk: ({sfdisk_input})') p = subprocess.run (['sfdisk', DISK], input=sfdisk_input, capture_output=True, text=True) + #print (f'nati: rc ({p.returncode}) stdout ({p.stdout}) stderr ({p.stderr})') subprocess.run (['partprobe', DISK]) if CACHESIZE: CacheLib.ogMountCache() - return not p.returncode + return True #/** @@ -282,10 +284,12 @@ def ogCreateGptPartitions (disk, parts): ogCreatePartitionTable (ND, 'GPT') # Definir particiones y notificar al kernel. - p = subprocess.run (['sgdisk'] + DELOPTIONS + OPTIONS + [DISK], capture_output=True, text=True) + #print (f'nati: about to run sgdisk ({DELOPTIONS}) ({OPTIONS}) ({DISK})') + p = subprocess.run (['sgdisk'] + DELOPTIONS + OPTIONS + [DISK]) + #print (f'nati: rc ({p.returncode}) stdout ({p.stdout}) stderr ({p.stderr})') subprocess.run (['partprobe', DISK]) if CACHESIZE: CacheLib.ogMountCache() - return not p.returncode + return True #/** @@ -814,7 +818,7 @@ def ogGetPartitionId (disk, par): if fsid == '8300' and f'{disk} {par}' == CacheLib.ogFindCache(): fsid = 'CA00' elif 'MSDOS' == pttype: - fsid = subprocess.run (['sfdisk', '--part-type', DISK, str(par)], capture_output=True, text=True).stdout.strip() + fsid = subprocess.run (['sfdisk', '--part-type', DISK, par], capture_output=True, text=True).stdout.strip() elif 'LVM' == pttype: fsid = '10000' elif 'ZPOOL' == pttype: diff --git a/ogclient/lib/python3/FileLib.py b/ogclient/lib/python3/FileLib.py index 6bc0e05..2a4adf4 100644 --- a/ogclient/lib/python3/FileLib.py +++ b/ogclient/lib/python3/FileLib.py @@ -213,8 +213,10 @@ def ogCopyFile (src, dst): if not TARGET: SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'device or file {dst_dev_err} not found') return + print (f'nati: ogCopyFile: SOURCE ({SOURCE}) TARGET ({TARGET})') # Copiar fichero (para evitar problemas de comunicaciones las copias se hacen con rsync en vez de cp). + print (f'nati: ogCopyFile: rsync --progress --inplace -avh ({SOURCE}) ({TARGET})') result = subprocess.run(["rsync", "--progress", "--inplace", "-avh", SOURCE, TARGET], capture_output=True, text=True) return result.returncode @@ -504,10 +506,12 @@ def ogMakeDir (container=None, disk=None, par=None, file=None): else: raise TypeError ('if one of "disk" and "par" are specified, then both must be') + print (f'nati: ogMakeDir: parent ({parent})') if not parent: SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'device or file {dev_err} not found') return None dst = os.path.basename (file) + print (f'nati: ogMakeDir: dst ({dst})') os.makedirs (os.path.join (parent, dst), exist_ok=True) return True diff --git a/ogclient/lib/python3/FileSystemLib.py b/ogclient/lib/python3/FileSystemLib.py index 1067ddc..15139f3 100644 --- a/ogclient/lib/python3/FileSystemLib.py +++ b/ogclient/lib/python3/FileSystemLib.py @@ -14,6 +14,7 @@ import ogGlobals import SystemLib import DiskLib import CacheLib +import FileSystemLib #/** @@ -286,11 +287,15 @@ def ogGetFsSize (disk, par, unit='KB'): elif unit.upper() == "TB": factor = 1024 * 1024 * 1024 elif unit.upper() != "KB": - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f"{unit} != {{ KB, MB, GB, TB }}") + SystemLib.ogRaiseError ( + [], + ogGlobals.OG_ERR_FORMAT, + f"{unit} != {{ KB, MB, GB, TB }}" + ) return # Obtener el tamaño del sistema de archivo (si no está formateado; tamaño = 0). - mnt = ogMount (disk, par) + mnt = FileSystemLib.ogMount (disk, par) if mnt: result = subprocess.run(["df", "-BK", mnt], capture_output=True, text=True) val = result.stdout.split("\n")[1].split()[1] @@ -327,7 +332,11 @@ def ogGetFsType(disk, part): try: subprocess.run(["zfs", "mount", PART]) except FileNotFoundError: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTEXEC, 'zfs') + SystemLib.ogRaiseError ( + [], + ogGlobals.OG_ERR_NOTEXEC, + 'zfs' + ) return out = subprocess.run(["mount"], capture_output=True, text=True).stdout.splitlines() for line in out: @@ -336,7 +345,11 @@ def ogGetFsType(disk, part): break if not TYPE: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'{disk} {part}') + SystemLib.ogRaiseError ( + [], + ogGlobals.OG_ERR_NOTFOUND, + f'{disk} {part}' + ) return # Componer valores correctos. @@ -580,7 +593,11 @@ def ogMountFs (disk, par): try: rc = subprocess.run(['mount', dev, mntdir, '-o', 'force,remove_hiberfile'], check=True).returncode except subprocess.CalledProcessError: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, f"{disk}, {par}") + SystemLib.ogRaiseError ( + [], + ogGlobals.OG_ERR_PARTITION, + f"{disk}, {par}" + ) return if 0 == rc: @@ -589,18 +606,26 @@ def ogMountFs (disk, par): try: subprocess.run (['ntfsfix', '-d', par], check=True) except subprocess.CalledProcessError: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, f"{disk, par}") + SystemLib.ogRaiseError ( + [], + ogGlobals.OG_ERR_PARTITION, + f"{disk, par}" + ) #return else: try: subprocess.run (['mount', par, mntdir, '-o', 'ro'], check=True) except subprocess.CalledProcessError: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, f"{disk, par}") + SystemLib.ogRaiseError ( + [], + ogGlobals.OG_ERR_PARTITION, + f"{disk, par}" + ) #return # Aviso de montaje de solo lectura. if ogIsReadonly(disk, par): - SystemLib.ogEcho ([], "warning", f'ogMountFs: {ogGlobals.lang.MSG_MOUNTREADONLY}: "{disk}, {par}"') + SystemLib.ogEcho("warning", f'ogMountFs: {ogGlobals.lang.MSG_MOUNTREADONLY}: "{disk}, {par}"') else: # Montar sistema de archivos ZFS (un ZPOOL no comienza por "/"). subprocess.run(['zfs', 'mount', dev]) @@ -692,8 +717,7 @@ def ogReduceFs (disk, par): break elif type == 'NTFS': ogUnmount (disk, par) - ntfsresize_out = subprocess.run (['ntfsresize', '-fi', PART], capture_output=True, text=True).stdout - nr_lines = ntfsresize_out.splitlines() + nr_lines = subprocess.run (['ntfsresize', '-fi', PART], capture_output=True, text=True).stdout.splitlines() maxsize = None size = None for l in nr_lines: @@ -703,10 +727,12 @@ def ogReduceFs (disk, par): size = l.split()[4] size = int ((int (size) * 1.1 / 1024 + 1) * 1024) - if not maxsize or not size: - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, f'{disk},{par} ({ntfsresize_out})') + if not maxsize and not size: + SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_PARTITION, f'{disk},{par}') return None + import time + extrasize = 0 retval = 1 while retval != 0 and size+extrasize < maxsize: @@ -784,14 +810,18 @@ def ogUnmountFs(disk, par): if MNTDIR: # Error si la particion está bloqueada. if ogIsLocked (disk, par): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_LOCKED, f"{ogGlobals.lang.MSG_PARTITION}, {disk} {par}") + SystemLib.ogRaiseError ( + [], + ogGlobals.OG_ERR_LOCKED, + f"{ogGlobals.lang.MSG_PARTITION}, {disk} {par}" + ) return # Desmontar y borrar punto de montaje. try: subprocess.run(["umount", PART], check=True) except subprocess.CalledProcessError: - SystemLib.ogEcho ([], "warning", f'ogUnmountFs: {ogGlobals.lang.MSG_DONTUNMOUNT}: "{disk}, {par}"') + SystemLib.ogEcho("warning", f'ogUnmountFs: {ogGlobals.lang.MSG_DONTUNMOUNT}: "{disk}, {par}"') try: os.rmdir(MNTDIR) except: @@ -865,7 +895,7 @@ def ogGetFreeSize(disk, part, unit='KB'): kk factor = unit2factor[unit.lower()] - particion = ogMount (disk, part) + particion = FileSystemLib.ogMount (disk, part) if not particion: kk df = subprocess.run (['df'], capture_output=True, text=True).stdout diff --git a/ogclient/lib/python3/ImageLib.py b/ogclient/lib/python3/ImageLib.py index 621924e..2b5fc8c 100644 --- a/ogclient/lib/python3/ImageLib.py +++ b/ogclient/lib/python3/ImageLib.py @@ -233,7 +233,7 @@ def ogCreateImage (disk, par, container, imgfile, tool='partclone', level='gzip' bn = os.path.basename (imgfile) IMGFILE = f'{imgdir}/{bn}.{imgtype}' - if ogIsImageLocked (container=None, imgfile=IMGFILE): + if ogIsImageLocked (IMGFILE): SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_LOCKED, f'{ogGlobals.lang.MSG_IMAGE} {container}, {imgfile}') return None @@ -248,6 +248,7 @@ def ogCreateImage (disk, par, container, imgfile, tool='partclone', level='gzip' # Crear Imagen. #trap + print (f'nati program ({program})') p = subprocess.run (program, shell=True, check=True) errcode = p.returncode if 0 == errcode: @@ -511,10 +512,10 @@ def ogRestoreImage (repo, imgpath, disk, par): rc = None try: + #print (f'nati: ogRestoreImage: running ({program})') p = subprocess.run (program, shell=True, capture_output=True, text=True) - print (p.stdout) - print (p.stderr) rc = p.returncode + #print (f'nati: ogRestoreImage: rc ({rc}) stdout ({p.stdout}) stderr ({p.stderr})') if not rc: SystemLib.ogRaiseError ([], ogGlobalsOG_ERR_IMAGE, f'{imgfile}, {disk}, {par}') except: diff --git a/ogclient/lib/python3/InventoryLib.py b/ogclient/lib/python3/InventoryLib.py index 0d0ac6f..2269af3 100644 --- a/ogclient/lib/python3/InventoryLib.py +++ b/ogclient/lib/python3/InventoryLib.py @@ -115,6 +115,7 @@ def ogIsEfiActive(): def ogListHardwareInfo(): ret = '' + SystemLib.ogEcho ([], 'info', ogGlobals.lang.MSG_HARDWAREINVENTORY) # Ejecutar dmidecode y obtener tipo de chasis dmi_out = subprocess.run (['dmidecode', '-s', 'chassis-type'], capture_output=True, text=True).stdout dmi_out = '\n'.join ([ x for x in dmi_out.splitlines() if 'Other' not in x ]) diff --git a/ogclient/lib/python3/NetLib.py b/ogclient/lib/python3/NetLib.py index 438d72d..e36f863 100644 --- a/ogclient/lib/python3/NetLib.py +++ b/ogclient/lib/python3/NetLib.py @@ -39,32 +39,48 @@ def _ogConnect (server, protocol, src, dst, options, readonly): #@param 2 Abreviatura Unidad Organizativa #@return Cambio recurso remoto en OGIMG. #*/ -def ogChangeRepo (ip_repo): - ogprotocol = os.environ.get ('ogprotocol', 'smb') +def ogChangeRepo(ip_repo, og_unit=None): + ogprotocol = os.environ['ogprotocol'] or 'smb' + + if og_unit: + SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'the og_unit parameter became unsupported') + return None try: mount = subprocess.run (['mount'], capture_output=True, text=True).stdout ro = bool (list (filter (lambda line: re.search (r'ogimages.*\bro,', line), mount.splitlines()))) current_repo = ogGetRepoIp() - new_repo = current_repo if ip_repo.upper() == 'REPO' else ip_repo + new_repo = current_repo if ip_repo.upper() == "REPO" else ip_repo if new_repo == current_repo: return True - subprocess.run (['umount', ogGlobals.OGIMG], check=True) + subprocess.run(["umount", ogGlobals.OGIMG], check=True) SystemLib.ogEcho (['session', 'log'], None, f'{ogGlobals.lang.MSG_HELP_ogChangeRepo} {new_repo}') options = _ogConnect_options() if not _ogConnect (new_repo, ogprotocol, 'ogimages', ogGlobals.OGIMG, options, ro): _ogConnect (current_repo, ogprotocol, 'ogimages', ogGlobals.OGIMG, options, ro) - SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_REPO, f'Error connecting to the new repository: {new_repo}') + SystemLib.ogRaiseError( + "session", + ogGlobals.OG_ERR_REPO, + f"Error connecting to the new repository: {new_repo}", + ) return False - SystemLib.ogEcho (['session', 'log'], None, f'Repository successfully changed to {new_repo}'.strip()) + SystemLib.ogEcho( + ["session", "log"], + None, + f"Repository successfully changed to {new_repo}".strip(), + ) return True except Exception as e: - SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_GENERIC, f'Error executing ogChangeRepo: {e}') + SystemLib.ogRaiseError( + "session", + ogGlobals.OG_ERR_GENERIC, + f"Error executing ogChangeRepo: {e}", + ) return None #/** @@ -199,6 +215,7 @@ def ogGetMacAddress(): mac_addresses.append(parts[i + 1].upper()) if mac_addresses: + print (f'nati: ogGetMacAddress: {mac_addresses[0]}') return mac_addresses[0] else: print("No active mac address found") diff --git a/ogclient/lib/python3/ProtocolLib.py b/ogclient/lib/python3/ProtocolLib.py index b4a17b2..18c8bb8 100644 --- a/ogclient/lib/python3/ProtocolLib.py +++ b/ogclient/lib/python3/ProtocolLib.py @@ -82,6 +82,7 @@ def ogUcastSyntax (op, sess, file=None, device=None, tool=None, level=None): address += f' -O {session[i]}:{portbase}' else: address = f'{session[1]}:{portbase}' + #print (f'nati mode ({mode}) address ({address})') if 'SENDPARTITION' == op: syn = ImageLib.ogCreateImageSyntax (device, ' ', tool, level) @@ -89,6 +90,7 @@ def ogUcastSyntax (op, sess, file=None, device=None, tool=None, level=None): ## otherwise, param2 in ImageLib.ogCreateImageSyntax() is not '| mbuffer' but empty ## and then parts[2] is out of range parts = syn.split ('|') + #print (f'nati syn ({syn}) parts ({parts})') prog1 = f'{parts[0]}|{parts[2]}'.strip() prog1 = prog1.replace ('>', '').strip() return f'{prog1} | mbuffer {address}' @@ -129,6 +131,7 @@ def ogUcastSendPartition (disk, par, sess, tool, level): cmd = ogUcastSyntax ('SENDPARTITION', sess, device=PART, tool=tool, level=level) if not cmd: return None + print (f'nati cmd ({cmd})') try: subprocess.run (cmd, shell=True, check=True) except subprocess.CalledProcessError: @@ -160,6 +163,7 @@ def ogUcastReceiverPartition (disk, par, sess, tool, level): cmd = ogUcastSyntax ('RECEIVERPARTITION', sess, device=PART, tool=tool, level=level) if not cmd: return None + print (f'nati cmd ({cmd})') try: subprocess.run (cmd, shell=True, check=True) except subprocess.CalledProcessError: @@ -204,6 +208,7 @@ def ogUcastSendFile (disk=None, par=None, container=None, file=None, sess=None): ## we were given container= source = FileLib.ogGetPath (src=container, file=file) dev_err = f'{container} {file}' + print (f'nati ogGetPath (src=({container}), file=({file})) = source ({source})') else: raise TypeError ('argument "container" can be specified along neither "disk" nor "par"') @@ -212,10 +217,12 @@ def ogUcastSendFile (disk=None, par=None, container=None, file=None, sess=None): ## we were given disk= par= source = FileLib.ogGetPath (src=f'{disk} {par}', file=file) dev_err = f'{disk} {par} {file}' + print (f'nati ogGetPath (src=({disk} {par}), file=({file})) = source ({source})') elif disk is None and par is None: ## we were given nothing source = FileLib.ogGetPath (file=file) dev_err = file + print (f'nati ogGetPath (file=({file})) = source ({source})') else: raise TypeError ('if one of "disk" and "par" are specified, then both must be') @@ -224,12 +231,14 @@ def ogUcastSendFile (disk=None, par=None, container=None, file=None, sess=None): return path2 = FileLib.ogGetPath (file=source) + print (f'nati path2 ({path2})') if not path2: SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'device or file {dev_err} not found') return cmd = ogUcastSyntax ('SENDFILE', sess, file=source) if not cmd: return None + print (f'nati cmd ({cmd})') try: subprocess.run (cmd, shell=True, check=True) except subprocess.CalledProcessError: @@ -300,6 +309,7 @@ def ogMcastSyntax (op, sess, file=None, device=None, tool=None, level=None): if 'SEND' in op: mode = 'server' else: mode = 'client' + print (f'nati mode ({mode})') try: isudpcast = subprocess.run (['udp-receiver', '--help'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True).stdout @@ -308,6 +318,7 @@ def ogMcastSyntax (op, sess, file=None, device=None, tool=None, level=None): return session = sess.split (':') + print (f'nati sess ({sess}) session ({session})') PERROR = 0 if 'server' == mode: @@ -321,6 +332,7 @@ def ogMcastSyntax (op, sess, file=None, device=None, tool=None, level=None): mbuffer = " --pipe 'mbuffer -q -m 20M' " portbase = int (session[0]) + print (f'nati portbase ({portbase})') if portbase not in range (9000, 9100, 2): SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'McastSession portbase {portbase}') PERROR = 3 @@ -360,6 +372,7 @@ def ogMcastSyntax (op, sess, file=None, device=None, tool=None, level=None): if 'client' == mode: other = session[1:] + print (f'nati session ({session}) other ({other})') serveraddress = other[0] if len (other) > 0 else '' starttimeout = other[1] if len (other) > 1 else '' receivertimeout = other[2] if len (other) > 2 else '' @@ -370,16 +383,23 @@ def ogMcastSyntax (op, sess, file=None, device=None, tool=None, level=None): else: repoip = NetLib.ogGetRepoIp() clientip = _clientip() + #print (f'nati repoip ({repoip}) clientip ({clientip})') if 1 != len (clientip): raise Exception ('more than one local IP address found') c = clientip[0] + #print (f'nati c ({c})') clientip = c['local'] mascara = c['prefixlen'] + #print (f'nati clientip ({clientip}) mascara ({mascara})') ripbt = _binary_ip (repoip) ipbt = _binary_ip (clientip) reposubred = ripbt[0:mascara] clientsubred = ipbt[0:mascara] + #print (f'nati ripbt ({ripbt})') + #print (f'nati ipbt ({ipbt})') + #print (f'nati reposubred ({reposubred})') + #print (f'nati clientsubred ({clientsubred})') if reposubred == clientsubred: serveraddress = ' ' else: serveraddress = f' --mcast-rdv-address {repoip}' @@ -407,6 +427,7 @@ def ogMcastSyntax (op, sess, file=None, device=None, tool=None, level=None): ## otherwise, param2 in ImageLib.ogCreateImageSyntax() is not '| mbuffer' but empty ## and then parts[2] is out of range parts = syn.split ('|') + #print (f'nati syn ({syn}) parts ({parts})') prog1 = f'{parts[0]}|{parts[2]}'.strip() prog1 = prog1.replace ('>', '').strip() return f'{prog1} | {syntaxserver}' @@ -462,6 +483,7 @@ def ogMcastSendFile (disk=None, par=None, container=None, file=None, sess=None): ## we were given container= source = FileLib.ogGetPath (src=container, file=file) dev_err = f'{container} {file}' + print (f'nati ogGetPath (src=({container}), file=({file})) = source ({source})') else: raise TypeError ('argument "container" can be specified along neither "disk" nor "par"') @@ -470,10 +492,12 @@ def ogMcastSendFile (disk=None, par=None, container=None, file=None, sess=None): ## we were given disk= par= source = FileLib.ogGetPath (src=f'{disk} {par}', file=file) dev_err = f'{disk} {par} {file}' + print (f'nati ogGetPath (src=({disk} {par}), file=({file})) = source ({source})') elif disk is None and par is None: ## we were given nothing source = FileLib.ogGetPath (file=file) dev_err = file + print (f'nati ogGetPath (file=({file})) = source ({source})') else: raise TypeError ('if one of "disk" and "par" are specified, then both must be') @@ -482,12 +506,14 @@ def ogMcastSendFile (disk=None, par=None, container=None, file=None, sess=None): return path2 = FileLib.ogGetPath (file=source) + print (f'nati path2 ({path2})') if not path2: SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'device or file {dev_err} not found') return cmd = ogMcastSyntax ('SENDFILE', sess, file=source) if not cmd: return None + print (f'nati cmd ({cmd})') try: subprocess.run (cmd, shell=True, check=True) except subprocess.CalledProcessError: @@ -526,6 +552,7 @@ def ogMcastReceiverFile (disk=None, par=None, container=None, file=None, sess=No ## we were given container= targetdir = FileLib.ogGetParentPath (src=container, file=file) dev_err = f'{container} {file}' + print (f'nati ogGetParentPath (src=({container}), file=({file})) = targetdir ({targetdir})') else: raise TypeError ('argument "container" can be specified along neither "disk" nor "par"') @@ -534,10 +561,12 @@ def ogMcastReceiverFile (disk=None, par=None, container=None, file=None, sess=No ## we were given disk= par= targetdir = FileLib.ogGetParentPath (src=f'{disk} {par}', file=file) dev_err = f'{disk} {par} {file}' + print (f'nati ogGetParentPath (src=({disk} {par}), file=({file})) = targetdir ({targetdir})') elif disk is None and par is None: ## we were given nothing targetdir = FileLib.ogGetParentPath (file=file) dev_err = file + print (f'nati ogGetParentPath (file=({file})) = targetdir ({targetdir})') else: raise TypeError ('if one of "disk" and "par" are specified, then both must be') @@ -546,9 +575,12 @@ def ogMcastReceiverFile (disk=None, par=None, container=None, file=None, sess=No return targetfile = os.path.basename (file) + print (f'nati targetfile ({targetfile})') + print (f'nati calling ogMcastSyntax with sess ({sess})') cmd = ogMcastSyntax ('RECEIVERFILE', sess, file=os.path.join (targetdir, targetfile)) if not cmd: return None + print (f'nati cmd ({cmd})') try: subprocess.run (cmd, shell=True, check=True) except subprocess.CalledProcessError: @@ -581,6 +613,7 @@ def ogMcastSendPartition (disk, par, sess, tool, compressor): FileSystemLib.ogUnmount (disk, par) cmd = ogMcastSyntax ('SENDPARTITION', sess, device=PART, tool=tool, level=compressor) if not cmd: return None + print (f'nati cmd ({cmd})') try: subprocess.run (cmd, shell=True, check=True) except subprocess.CalledProcessError: @@ -606,6 +639,7 @@ def ogMcastReceiverPartition (disk, par, sess, tool, compressor): FileSystemLib.ogUnmount (disk, par) cmd = ogMcastSyntax ('RECEIVERPARTITION', sess, device=PART, tool=tool, level=compressor) if not cmd: return None + print (f'nati cmd ({cmd})') try: subprocess.run (cmd, shell=True, check=True) except subprocess.CalledProcessError: @@ -659,6 +693,7 @@ def ogTorrentStart (disk=None, par=None, container=None, torrentfile=None, torre return None source = FileLib.ogGetPath (src=container, file=torrentfile) dev_err = f'{container} {torrentfile}' + print (f'nati ogGetPath (src=({container}), file=({torrentfile})) = source ({source})') else: raise TypeError ('argument "container" can be specified along neither "disk" nor "par"') @@ -667,6 +702,7 @@ def ogTorrentStart (disk=None, par=None, container=None, torrentfile=None, torre ## we were given disk= par= source = FileLib.ogGetPath (src=f'{disk} {par}', file=torrentfile) dev_err = f'{disk} {par} {torrentfile}' + print (f'nati ogGetPath (src=({disk} {par}), file=({torrentfile})) = source ({source})') elif disk is None and par is None: ## we were given nothing if torrentfile.startswith ('/opt/opengnsys/images'): @@ -674,6 +710,7 @@ def ogTorrentStart (disk=None, par=None, container=None, torrentfile=None, torre return None source = FileLib.ogGetPath (file=torrentfile) dev_err = torrentfile + print (f'nati ogGetPath (file=({torrentfile})) = source ({source})') else: raise TypeError ('if one of "disk" and "par" are specified, then both must be') @@ -788,6 +825,7 @@ def ogCreateTorrent (disk=None, par=None, container=None, file=None, ip_bttrack= return f = f'{file}.{ext}' source = FileLib.ogGetPath (src=container, file=f) + print (f'nati ogGetPath (src=({container}), file=({f})) = source ({source})') else: raise TypeError ('argument "container" can be specified along neither "disk" nor "par"') @@ -796,10 +834,12 @@ def ogCreateTorrent (disk=None, par=None, container=None, file=None, ip_bttrack= ## we were given disk= par= f = f'{file}.img' source = FileLib.ogGetPath (src=f'{disk} {par}', file=f) + print (f'nati ogGetPath (src=({disk} {par}), file=({f})) = source ({source})') elif disk is None and par is None: ## we were given nothing f = f'{file}.img' source = FileLib.ogGetPath (file=f) + print (f'nati ogGetPath (file=({f})) = source ({source})') else: raise TypeError ('if one of "disk" and "par" are specified, then both must be') @@ -850,12 +890,14 @@ def ogUpdateCacheIsNecesary (repo, file, proto): return None filesource = FileLib.ogGetPath (src=repo, file=file) + #print (f'nati filesource ({filesource})') if not filesource: SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f' {repo} {file}') return None # paso 1. si no existe la imagen, confirmar que es necesario actualizar la cache. filetarget = FileLib.ogGetPath (src='CACHE', file=file) + #print (f'nati filetarget ({filetarget})') if not filetarget: # borramos el fichero bf del torrent, en el caso de que se hubiese quedado de algun proceso fallido if FileLib.ogGetPath (src='CACHE', file=f'/{file}.torrent.bf'): ogDeleteFile (container='CACHE', file=f'{file}.torrent.bf') diff --git a/ogclient/lib/python3/RegistryLib.py b/ogclient/lib/python3/RegistryLib.py index 11a2c08..2657bd8 100644 --- a/ogclient/lib/python3/RegistryLib.py +++ b/ogclient/lib/python3/RegistryLib.py @@ -19,8 +19,10 @@ import FileLib # Función ficticia para lanzar chntpw con timeout de 5 s., evitando cuelgues del programa. chntpw_exe = shutil.which ('drbl-chntpw') or shutil.which ('chntpw') def chntpw (hivefile, input_file): + #print (f'nati: hivefile ({hivefile}) input_file ({input_file}) type ({type(input_file)})') with open (input_file, 'r') as fd: input_contents = fd.read() + #print (f'nati: input_contents ({input_contents})') return subprocess.run ([chntpw_exe, '-e', hivefile], timeout=5, input=input_contents, capture_output=True, text=True).stdout ## en el codigo bash aparecen "${3%\\*}" y "${3##*\\}" varias veces diff --git a/ogclient/lib/python3/SystemLib.py b/ogclient/lib/python3/SystemLib.py index d86b635..fffd2cb 100644 --- a/ogclient/lib/python3/SystemLib.py +++ b/ogclient/lib/python3/SystemLib.py @@ -3,7 +3,6 @@ import datetime from zoneinfo import ZoneInfo import sys import os -import json import shutil import inspect import glob @@ -14,6 +13,7 @@ from contextlib import redirect_stdout, redirect_stderr import ogGlobals import StringLib +import SystemLib #NODEBUGFUNCTIONS, OGIMG, OG_ERR_CACHESIZE, OG_ERR_NOTCACHE, OG_ERR_NOTWRITE, OG_ERR_FILESYS #OG_ERR_REPO, OG_ERR_NOTOS, OG_ERR_NOGPT, OG_ERR_OUTOFLIMIT, OG_ERR_IMAGE, OG_ERR_CACHE @@ -21,7 +21,6 @@ import StringLib def _logtype2logfile (t): if 'log' == t.lower(): return ogGlobals.OGLOGFILE - if 'jsonlog' == t.lower(): return ogGlobals.OGJSONLOGFILE elif 'command' == t.lower(): return ogGlobals.OGLOGCOMMAND elif 'session' == t.lower(): return ogGlobals.OGLOGSESSION else: raise Exception (f'unknown log type ({t})') @@ -37,40 +36,24 @@ def ogEcho (logtypes, loglevel, msg): logfiles = ['/dev/stdout'] if type (logtypes) is list: for l in logtypes: - if 'log' == l: - logfiles.append (_logtype2logfile ('log')) - logfiles.append (_logtype2logfile ('jsonlog')) - else: - logfiles.append (_logtype2logfile (l)) + logfiles.append (_logtype2logfile (l)) else: ## string - if 'log' == logtypes: - logfiles.append (_logtype2logfile ('log')) - logfiles.append (_logtype2logfile ('jsonlog')) - else: - logfiles.append (_logtype2logfile (logtypes)) + logfiles.append (_logtype2logfile (logtypes)) if loglevel is None or 'help' == loglevel: if ogGlobals.DEBUG.lower() != "no": logfiles.append (ogGlobals.OGLOGFILE) - logfiles.append (ogGlobals.OGJSONLOGFILE) for f in logfiles: with open (f, 'a') as fd: - if ogGlobals.OGJSONLOGFILE == f: - fd.write (json.dumps ({'message':msg}) + '\n') - else: - fd.write (msg + '\n') + fd.write (msg + '\n') return if 'info' == loglevel or 'warning' == loglevel or 'error' == loglevel: - DATETIME = datetime.datetime.now (ZoneInfo (ogGlobals.TZ)).strftime ('%F %T %Z') - DATETIME_json = datetime.datetime.now (ZoneInfo (ogGlobals.TZ)).strftime ('%Y-%m-%d %H:%M:%S') + DATETIME = datetime.datetime.now(ZoneInfo(ogGlobals.TZ)).strftime("%F %T %Z") for f in logfiles: with open (f, 'a') as fd: - if ogGlobals.OGJSONLOGFILE == f: - fd.write (json.dumps ({'timestamp':DATETIME_json, 'severity':loglevel, 'message':msg}) + '\n') - else: - fd.write (f"OpenGnsys {loglevel} {DATETIME} {msg}\n") + fd.write (f"OpenGnsys {loglevel} {DATETIME} {msg}\n") else: raise Exception (f'unknown loglevel ({loglevel})') @@ -83,28 +66,20 @@ def ogEcho (logtypes, loglevel, msg): #@return Salida de ejecución del comando. #@note str_logfile = { LOG, SESSION, COMMAND } #*/ -#ogExecAndLog (str_logfile ... str_command ...", -#ogExecAndLog ([], ogMyLib.ogSomeMethod, *args, **kwargs) -#ogExecAndLog ('command', ogMyLib.ogSomeMethod, *args, **kwargs) -#ogExecAndLog (['command'], ogMyLib.ogSomeMethod, *args, **kwargs) -#ogExecAndLog (['log', 'command'], ogMyLib.ogSomeMethod, *args, **kwargs) +#ogHelp (str_logfile ... str_command ...", +#ogHelp ([], ogMyLib.ogSomeMethod, *args, **kwargs) +#ogHelp ('command', ogMyLib.ogSomeMethod, *args, **kwargs) +#ogHelp (['command'], ogMyLib.ogSomeMethod, *args, **kwargs) +#ogHelp (['log', 'command'], ogMyLib.ogSomeMethod, *args, **kwargs) def ogExecAndLog (logtypes, fun, *args, **kwargs): logfiles = ['/dev/stdout'] if type (logtypes) is list: for l in logtypes: logtypes = list (map (lambda x: x.lower(), logtypes)) - if 'log' == l: - logfiles.append (_logtype2logfile ('log')) - logfiles.append (_logtype2logfile ('jsonlog')) - else: - logfiles.append (_logtype2logfile (l)) + logfiles.append (_logtype2logfile (l)) else: ## string logtypes = logtypes.lower() - if 'log' == logtypes: - logfiles.append (_logtype2logfile ('log')) - logfiles.append (_logtype2logfile ('jsonlog')) - else: - logfiles.append (_logtype2logfile (logtypes)) + logfiles.append (_logtype2logfile (logtypes)) if not fun: ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, 'no function provided') @@ -129,37 +104,45 @@ def ogExecAndLog (logtypes, fun, *args, **kwargs): # ## redirect stdout only # eval $COMMAND | tee -a $FILES + import time sout = serr = '' if 'command' in logtypes: os.unlink (ogGlobals.OGLOGCOMMAND) open (ogGlobals.OGLOGCOMMAND, 'w').close() + #print ('nati: ogExecAndLog: about to redirect stdout and stderr') + #time.sleep (1) ## nati with redirect_stdout (StringIO()) as r_stdout, redirect_stderr (StringIO()) as r_stderr: rc = fun (*args, **kwargs) sout = r_stdout.getvalue() serr = r_stderr.getvalue() + #print (f'nati: ogExecAndLog: end of redirections, rc ({rc}) sout ({sout}) serr ({serr})') + #time.sleep (1) ## nati else: + #print ('nati: ogExecAndLog: about to redirect stdout only') + #time.sleep (1) ## nati with redirect_stdout (StringIO()) as r_stdout: rc = fun (*args, **kwargs) sout = r_stdout.getvalue() + #print (f'nati: ogExecAndLog: end of redirections, rc ({rc}) sout ({sout})') + #time.sleep (1) ## nati rc_str = str (rc) if sout or serr or ('True' != rc_str and 'False' != rc_str and 'None' != rc_str): + #print ('nati: ogExecAndLog: sout or serr are true') + #time.sleep (1) ## nati for f in logfiles: + #print (f'nati: ogExecAndLog: logging to logfile ({f})') with open (f, 'a') as fd: - if ogGlobals.OGJSONLOGFILE == f: - if sout: fd.write (json.dumps ({'message':sout}) + '\n') - if serr: fd.write (json.dumps ({'message':serr}) + '\n') - if rc_str: fd.write (json.dumps ({'message':rc_str}) + '\n') - else: - if sout: fd.write (f'{sout}\n') - if serr: fd.write (f'{serr}\n') - if rc_str: fd.write (f'{rc_str}\n') - #fd.write (f"ogExecAndLog: {fun.__name__} rc:\n{rc_str}\n") - #if sout: fd.write (f"ogExecAndLog: {fun.__name__} stdout:\n{sout}\n") - #else: fd.write (f"ogExecAndLog: {fun.__name__} stdout: (none)\n") - #if serr: fd.write (f"ogExecAndLog: {fun.__name__} stderr:\n{serr}\n") - #else: fd.write (f"ogExecAndLog: {fun.__name__} stderr: (none)\n") + if sout: fd.write (f'{sout}\n') + if serr: fd.write (f'{serr}\n') + if rc_str: fd.write (f'{rc_str}\n') + #fd.write (f"ogExecAndLog: {fun.__name__} rc:\n{rc_str}\n") + #if sout: fd.write (f"ogExecAndLog: {fun.__name__} stdout:\n{sout}\n") + #else: fd.write (f"ogExecAndLog: {fun.__name__} stdout: (none)\n") + #if serr: fd.write (f"ogExecAndLog: {fun.__name__} stderr:\n{serr}\n") + #else: fd.write (f"ogExecAndLog: {fun.__name__} stderr: (none)\n") + #print (f'nati: ogExecAndLog: returning rc ({rc})') return rc #/** @@ -283,6 +266,7 @@ def ogRaiseError (logtypes, code, msg): if code == ogGlobals.OG_ERR_FORMAT or \ (str_call_stack in ogGlobals.NODEBUGFUNCTIONS) or \ not (len(call_stack)>0 and (call_stack[0] in ogGlobals.NODEBUGFUNCTIONS)): + #print ('nati: ogRaiseError: actually calling ogEcho') ogEcho (logtypes, "error", f"{str_call_stack.replace(' ', '<-')}: {MSG}") return code @@ -312,11 +296,11 @@ def ogIsRepoLocked(): # FUNCNAME = ogCheckProgram.__name__ # # if not program or not isinstance(program, str): -# ogRaiseError ("session", ogGlobals.OG_ERR_FORMAT, f"Error: {ogGlobals.lang.MSG_ERR_FORMAT} {FUNCNAME} \"program\"") +# SystemLib.ogRaiseError ("session", ogGlobals.OG_ERR_FORMAT, f"Error: {ogGlobals.lang.MSG_ERR_FORMAT} {FUNCNAME} \"program\"") # return # # if not shutil.which(program): -# ogRaiseError ( "session", ogGlobals.OG_ERR_NOTEXEC, f"Error: The program '{program}' is not available on the system.") +# SystemLib.ogRaiseError ( "session", ogGlobals.OG_ERR_NOTEXEC, f"Error: The program '{program}' is not available on the system.") # return # # return 0 diff --git a/ogclient/lib/python3/UEFILib.py b/ogclient/lib/python3/UEFILib.py index 3e61486..a70b5a7 100644 --- a/ogclient/lib/python3/UEFILib.py +++ b/ogclient/lib/python3/UEFILib.py @@ -42,8 +42,8 @@ def ogNvramActiveEntry (entry): numentries.append (words[0][4:8]) except ValueError: for l in efibootmgr_out.splitlines(): - words = l.split (maxsplit=2) - if len(words) < 3: continue + words = l.split (maxsplit=1) + if len(words) < 2: continue if words[1] == entry: numentries.append (words[0][4:8]) @@ -135,6 +135,8 @@ def ogCopyEfiBootLoader (disk, par): bootlabel = f'Part-{int(disk):02d}-{int(par):02d}' osversion = InventoryLib.ogGetOsVersion (disk, par) + print (f'bootlabel ({bootlabel})') + print (f'osversion ({osversion})') if 'Windows 1' in osversion: loader = None for i in f'{efidir}/EFI/Microsoft/Boot/bootmgfw.efi', f'{efidir}/EFI/{bootlabel}/Boot/bootmgfw.efi': @@ -178,8 +180,8 @@ def ogNvramDeleteEntry (entry): numentries.append (words[0][4:8]) except ValueError: for l in efibootmgr_out.splitlines(): - words = l.split (maxsplit=2) - if len(words) < 3: continue + words = l.split (maxsplit=1) + if len(words) < 2: continue if words[1] == entry: numentries.append (words[0][4:8]) @@ -323,8 +325,8 @@ def ogNvramInactiveEntry (entry): numentries.append (words[0][4:8]) except ValueError: for l in efibootmgr_out.splitlines(): - words = l.split (maxsplit=2) - if len(words) < 3: continue + words = l.split (maxsplit=1) + if len(words) < 2: continue if words[1] == entry: numentries.append (words[0][4:8]) @@ -426,7 +428,7 @@ def ogRestoreEfiBootLoader (disk, par): return osversion = InventoryLib.ogGetOsVersion (disk, par) - if osversion and 'Windows 1' in osversion: + if 'Windows 1' in osversion: bootlabel = f'Part-{int(disk):02d}-{int(par):02d}' loader = FileLib.ogGetPath (file=f'{mntdir}/ogBoot/bootmgfw.efi') if not loader: @@ -485,8 +487,8 @@ def ogNvramSetNext (entry): numentries.append (words[0][4:8]) except ValueError: for l in efibootmgr_out.splitlines(): - words = l.split (maxsplit=2) - if len(words) < 3: continue + words = l.split (maxsplit=1) + if len(words) < 2: continue if words[1] == entry: numentries.append (words[0][4:8]) @@ -494,7 +496,7 @@ def ogNvramSetNext (entry): SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, f'NVRAM entry "{entry}"') return - if 1 != len (numentries): + if 1 != len(numentries): SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, f'more than one entry found') return diff --git a/ogclient/lib/python3/ogGlobals.py b/ogclient/lib/python3/ogGlobals.py index f1901fd..29eea03 100644 --- a/ogclient/lib/python3/ogGlobals.py +++ b/ogclient/lib/python3/ogGlobals.py @@ -57,12 +57,11 @@ OGBIN = os.path.join (OPENGNSYS, 'bin') OGETC = os.path.join (OPENGNSYS, 'etc') OGLIB = os.path.join (OPENGNSYS, 'lib') OGAPI = os.path.join (OGLIB, 'engine', 'bin') -OGPYFUNCS = os.path.join (OPENGNSYS, 'functions') OGSCRIPTS = os.path.join (OPENGNSYS, 'scripts') OGIMG = os.path.join (OPENGNSYS, 'images') OGCAC = os.path.join (OPENGNSYS, 'cache') -OGLOGFILE = '/var/log/clone-engine.log' -OGJSONLOGFILE = '/var/log/clone-engine.json.log' +OGLOG = os.path.join (OPENGNSYS, 'log') +OGLOGFILE = f'{OGLOG}/192.168.42.42' ## TODO import NetLib; OGLOGFILE = f'$OGLOG/{NetLib.ogGetIpAddress()}.log' DEBUG = 'yes' _path = os.environ['PATH'] + ':/sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin:/opt/oglive/rootfs/opt/drbl/sbin' os.environ['PATH'] = ':'.join ([OGSCRIPTS, _path, OGAPI, OGBIN]) diff --git a/ogclient/scripts/bootOs.py b/ogclient/scripts/bootOs.py deleted file mode 100755 index 28357ed..0000000 --- a/ogclient/scripts/bootOs.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python3 -# Script de ejemplo para arancar un sistema operativo instalado. -# Nota: se usa como base para el programa de arranque de OpenGnsys Admin. - -import sys -import re -import subprocess -import shutil - -import ogGlobals -from SystemLib import ogRaiseError, ogEcho -from DiskLib import ogDiskToDev -from FileSystemLib import ogMount, ogUnmount, ogCheckFs, ogUnmountAll -from CacheLib import ogUnmountCache -from BootLib import ogBoot - -prog = sys.argv[0] -if len (sys.argv) < 3 or len (sys.argv) > 4: - ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'Formato: {prog} ndisco nfilesys [str_kernel str_initrd str_kernelparams]') - sys.exit (1) -disk, par, *other = sys.argv[1:] -params = other[0] if len (other) > 0 else '' - -# Comprobar errores. -part = ogDiskToDev (disk, par) -if not part: sys.exit (1) -mntdir = ogMount (disk, par) -if not mntdir: sys.exit (1) - -print ('[0] Inicio del proceso de arranque.') - -# Si el equipo está hibernado chequeamos el f.s. y borramos el hiberfile (error cod.6) -mount_out = subprocess.run (['mount'], capture_output=True, text=True).stdout -if not mount_out or not re.search (rf'{mntdir}.*\(rw', mount_out): - ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_WARNING}: {ogGlobals.lang.MSG_MOUNTREADONLY}') - ogUnmount (disk, par) - ogCheckFs (disk, par) - - part = ogDiskToDev (disk, par) - os.makedirs (mntdir, exist_ok=True) - subprocess.run (['ntfs-3g', '-o', 'remove_hiberfile', part, mntdir]) - ogEcho (['log', 'session'], None, 'Particion desbloqueada') - - ogUnmount (disk, par) - ogMount (disk, par) - -if shutil.which ('bootOsCustom.py'): - print ('[10] Configuración personalizada del inicio.') - subprocess.run ([f'{ogGlobals.OGSCRIPTS}/bootOsCustom.py']) - -print ('[70] Desmontar todos los sistemas de archivos.') -subprocess.run (['sync']) -for i in range (1, 1+len(ogDiskToDev())): - ogUnmountAll (i) -print ('[80] Desmontar cache local.') -ogUnmountCache() -print (f'[90] Arrancar sistema operativo.') -ogBoot (disk, par, params=params) diff --git a/ogclient/scripts/deployImage.py b/ogclient/scripts/deployImage.py index 4070fb4..e5a2ec2 100755 --- a/ogclient/scripts/deployImage.py +++ b/ogclient/scripts/deployImage.py @@ -145,10 +145,6 @@ def main (repo, imgname, disk, par, proto='UNICAST', protoopt=''): SystemLib.ogEcho (['log', 'session'], None, f'[55] {ogGlobals.lang.MSG_HELP_ogRestoreImage}: restoreImage {params}') retval = subprocess.run (['restoreImage.py'] + params).returncode - ## turn shell's success into python success (without ending up with True or False) - if retval: retval = 0 - else: retval = 1 - # Mostrar resultados. resumerestoreimage = subprocess.run (['grep', '--max-count', '1', 'Total Time:', ogGlobals.OGLOGCOMMAND], capture_output=True, text=True).stdout SystemLib.ogEcho (['log', 'session'], None, f' [ ] {resumerestoreimage} ') diff --git a/ogclient/scripts/getIpAddress.py b/ogclient/scripts/getIpAddress.py new file mode 100755 index 0000000..65f62aa --- /dev/null +++ b/ogclient/scripts/getIpAddress.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +import sys +import NetLib + +def get_ip_address(*args): + try: + # Llama a ogGetIpAddress desde NetLib y captura el resultado + result = NetLib.ogGetIpAddress(*args) + print(result.strip()) + except Exception as e: + print(f"Error ejecutando ogGetIpAddress: {e}", file=sys.stderr) + sys.exit(1) + +if __name__ == "__main__": + get_ip_address(*sys.argv[1:]) + diff --git a/ogclient/scripts/initCache.py b/ogclient/scripts/initCache.py index a0e038a..8a45ca8 100755 --- a/ogclient/scripts/initCache.py +++ b/ogclient/scripts/initCache.py @@ -47,9 +47,8 @@ def main (NDISK, NPART, SIZE, MOUNT): if SIZE != CACHESIZE: print("[10] Crear partición de caché local.") CacheLib.ogUnmountCache() - if not CacheLib.ogCreateCache (NDISK, NPART, SIZE): - SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_CACHE, 'failed to create cache') - return False + print (f'nati: calling ogCreateCache ({NDISK}, {NPART}, {SIZE})') + CacheLib.ogCreateCache (NDISK, NPART, SIZE) DiskLib.ogUpdatePartitionTable() # Si caché no montada y no formateada o cambia el tamaño: formatear. @@ -105,19 +104,23 @@ if __name__ == "__main__": NPART = int (args[1]) SIZE = int (args[2]) else: + print (f'nati: params no es ni 1 ni 2 ni 3 sino ({PARAMS})') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) except ValueError: + print (f'nati: ValueError') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) # Si disco o partición no son mayores o iguales que 1, error. if NDISK < 1 or NPART < 1: + print (f'nati: ndisk<1 or npart<1, ({NDISK}) ({NPART})') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) # Si tamaño no es numérico o tamaño<-1, error. if SIZE < -1: + print (f'nati: SIZE<-1 ({SIZE})') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) diff --git a/ogclient/scripts/listHardwareInfo.py b/ogclient/scripts/listHardwareInfo.py index 5993f07..9f633b1 100755 --- a/ogclient/scripts/listHardwareInfo.py +++ b/ogclient/scripts/listHardwareInfo.py @@ -1,28 +1,43 @@ -#!/usr/bin/python3 -# Scirpt de ejemplo para almacenear en fichero temporal el listado de hardware. -# Nota: se usa como base para el programa de recogida de listado de hardware de OpenGnsys Admin. -# Formato: listHardwareInfo - +import subprocess import os import sys -import subprocess - -import ogGlobals -from SystemLib import ogRaiseError +sys.path.append('/opt/opengnsys/lib/engine/bin') from NetLib import ogGetIpAddress +sys.path.append('/opt/opengnsys/lib/engine/bin') from InventoryLib import ogListHardwareInfo -prog = sys.argv[0] -if len (sys.argv) > 1: - ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_FORMAT} {prog}') - sys.exit (1) +def get_server_log_dir(): + # Obtener el directorio de logs del servidor + oglog = os.getenv("OGLOG") + if not oglog: + return "" + result = subprocess.run(["mount"], capture_output=True, text=True) + for line in result.stdout.splitlines(): + parts = line.split() + if len(parts) >= 4 and parts[3] == oglog: + return parts[1] + return "" -# Directorio del servidor donde se exportan los ficheros de registro. -#SERVERLOGDIR = unused +def list_hardware_info(): + oglog = os.getenv("OGLOG", "/tmp") # Usar /tmp como valor por defecto para OGLOG + ip_address = ogGetIpAddress() + # Fichero de listado de hardware basado en la IP obtenida + hardfile = f"hard-{ogGetIpAddress()}" + print(f"hardfile:{hardfile}") + # Ejecutar ogListHardwareInfo y redirigir al archivo de listado + hardware_info_path = os.path.join(oglog, hardfile) + with open(hardware_info_path, 'w') as output_file: + output_file.write(ogListHardwareInfo()) + + return hardware_info_path + +if __name__ == "__main__": + # Obtener el directorio del servidor donde se exportan los ficheros de registro + server_log_dir = get_server_log_dir() + + # Generar el archivo de listado de hardware y obtener su ruta + hardware_info_path = list_hardware_info() + + # Imprimir la ruta del archivo generado + print(hardware_info_path) -# Fichero de listado: hard-IP -HARDFILE = f'/tmp/hard-{ogGetIpAddress()}' -out = ogListHardwareInfo() -with open (HARDFILE, 'w') as fd: - fd.write (out) -print (HARDFILE) diff --git a/ogclient/scripts/listSoftwareInfo.py b/ogclient/scripts/listSoftwareInfo.py index f92cdbd..1c2756e 100755 --- a/ogclient/scripts/listSoftwareInfo.py +++ b/ogclient/scripts/listSoftwareInfo.py @@ -18,7 +18,7 @@ prog = os.path.basename (sys.argv[0]) def main (disk, par, reduced): ip = NetLib.ogGetIpAddress() - softfile = f'/tmp/soft-{ip}-{disk}-{par}' + softfile = f'{ogGlobals.OGLOG}/soft-{ip}-{disk}-{par}' software_list = InventoryLib.ogListSoftware (disk, par) if reduced: diff --git a/ogclient/scripts/restoreImage.py b/ogclient/scripts/restoreImage.py index 961b971..a5f0ff6 100644 --- a/ogclient/scripts/restoreImage.py +++ b/ogclient/scripts/restoreImage.py @@ -114,5 +114,5 @@ t = time.time() - t0 SystemLib.ogEcho (['log', 'session'], None, f'[100] Duracion de la operacion {int (t/60)}m {int (t%60)}s') # Código de salida del comando prinicpal de restauración. -sys.exit (not retval) ## negated for the shell +sys.exit (retval) diff --git a/ogclient/scripts/updateBootCache.py b/ogclient/scripts/updateBootCache.py index e698b90..854b9c9 100755 --- a/ogclient/scripts/updateBootCache.py +++ b/ogclient/scripts/updateBootCache.py @@ -1,7 +1,6 @@ #!/usr/bin/python3 import os -import sys import shutil import ogGlobals @@ -35,34 +34,29 @@ if not CacheLib.ogMountCache(): os.makedirs (ogbcache, exist_ok=True) -servervmlinuz = serverinitrd = cachevmlinuz = cacheinitrd = '' # comparamos los del server -if os.path.exists (f'{ogbtftp}/ogvmlinuz.sum'): - with open (f'{ogbtftp}/ogvmlinuz.sum', 'r') as fd: servervmlinuz = fd.read().strip() -if os.path.exists (f'{ogbtftp}/oginitrd.img.sum'): - with open (f'{ogbtftp}/oginitrd.img.sum', 'r') as fd: serverinitrd = fd.read().strip() +with open (f'{ogbtftp}/ogvmlinuz.sum', 'rb') as fd: servervmlinuz = fd.read() +with open (f'{ogbtftp}/oginitrd.img.sum', 'rb') as fd: serverinitrd = fd.read() #comparamos los de la cache -if os.path.exists (f'{ogbcache}/ogvmlinuz.sum'): - with open (f'{ogbcache}/ogvmlinuz.sum', 'r') as fd: cachevmlinuz = fd.read().strip() -if os.path.exists (f'{ogbcache}/oginitrd.img.sum'): - with open (f'{ogbcache}/oginitrd.img.sum', 'r') as fd: cacheinitrd = fd.read().strip() +with open (f'{ogbcache}/ogvmlinuz.sum', 'rb') as fd: cachevmlinuz = fd.read() +with open (f'{ogbcache}/oginitrd.img.sum', 'rb') as fd: cacheinitrd = fd.read() print (f'MD5 on SERVER: {servervmlinuz} {serverinitrd}') print (f'MD5 on CACHE: {cachevmlinuz} {cacheinitrd}') -do_reboot = '' +do_reboot = '0' if cachevmlinuz != servervmlinuz: print ('ogvmlinuz updating') shutil.copy2 (f'{ogbtftp}/ogvmlinuz', f'{ogbcache}/ogvmlinuz') shutil.copy2 (f'{ogbtftp}/ogvmlinuz.sum', f'{ogbcache}/ogvmlinuz.sum') - do_reboot = 'true' + do_reboot = '1' if cacheinitrd != serverinitrd: print ('oginitrd updating') shutil.copy2 (f'{ogbtftp}/oginitrd.img', f'{ogbcache}/oginitrd.img') shutil.copy2 (f'{ogbtftp}/oginitrd.img.sum', f'{ogbcache}/oginitrd.img.sum') - do_reboot = 'true' + do_reboot = '1' print (do_reboot) -sys.exit (0) +os.exit (0) diff --git a/ogclient/scripts/updateCache.py b/ogclient/scripts/updateCache.py index b063a44..179781c 100644 --- a/ogclient/scripts/updateCache.py +++ b/ogclient/scripts/updateCache.py @@ -144,6 +144,7 @@ if sizerequired >= cachesizefree: sys.exit (1) # Comprobamos que imagen cache igual a la del repo. Si sincronizada no podemos comprobar. +## nati: esto ya lo hicimos mas arriba... rc = ProtocolLib.ogUpdateCacheIsNecesary (repositorio, path, protocolo) # si rc=True: actualizamos; si rc=False: no actualizamos (exit 0); si rc=None: exit error if rc == True: pass ## es necesario actualizar