Compare commits

..

1 Commits

Author SHA1 Message Date
Nicolas Arenas f8390cc9be Modify jenkinsfile to upload packages
ogclone-engine/pipeline/head This commit looks good Details
2025-03-19 14:58:11 +01:00
209 changed files with 4658 additions and 7845 deletions

View File

@ -1,508 +1,12 @@
# Changelog # Changelog
All notable changes to this project will be documented in this file. ## [0.1.1] - 2025-02-28
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Changed - 2025-03-19
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.26.1] - 2025-07-14
### Changed
- Change sort order in `_getAllDisks()`
## [0.26.0] - 2025-07-14
### Fixed
- Overhaul partitioning
## [0.25.2] - 2025-07-14
### Fixed
- Run initCache.py rather than just initCache
## [0.25.1] - 2025-07-11
### Changed
- Derive a strong password from the default opengnsys weak one
## [0.25.0] - 2025-07-11
## Added
- Add ogGit functionality
## [0.24.0] - 2025-07-11
### Added
- Configure and run filebeat
## [0.23.2] - 2025-07-07
### Changed
- Improved error reporting in ogCreateCache
## [0.23.1] - 2025-07-04
### Fixed
- Don't fail if grub.cfg is not found
## [0.23.0] - 2025-07-03
### Removed
- Remove several bash scripts under "scripts" and "interfaceAdm"
## [0.22.8] - 2025-07-03
### Removed
- Remove unused "cacheopts"
## [0.22.7] - 2025-07-03
### Fixed
- Fix dstat--show bandwith in the local cgi
## [0.22.6] - 2025-07-03
### Changed
- Include own IP address in the local CGI's title
## [0.22.5] - 2025-07-02
### Fixed
- Fixed booting windows using winboot/kexec
## [0.22.4] - 2025-07-01
### Changed
- Do copy grub.cfg :) and clean it up on boot
- Remove warning about /dev/loop0
- Comment unused code out
## [0.22.3] - 2025-06-27
### Changed
- Don't copy grub.cfg
## [0.22.2] - 2025-06-27
### Fixed
- Don't check rc of updateBootCache.py because we may have no cache partition
## [0.22.1] - 2025-06-27
### Fixed
- Included some changes that should be in the previous version
## [0.22.0] - 2025-06-26
### Changed
- Changed torrent client from ctorrent to aria2c
- Updated ogCreateTorrent function replaced ctorrent with mktorrent
## [0.21.1] - 2025-06-26
### Fixed
- Fixed syntax and other errors
## [0.21.0] - 2025-06-25
### Changed
- Prevent Configurar.py from messing with the browser
## [0.20.3] - 2025-06-25
### Fixed
- Fixed bugs when partitioning disks
## [0.20.2] - 2025-06-24
### Changed
- Do a couple of ogExecAndLog()s also when creating images
## [0.20.1] - 2025-06-24
### Changed
- Fix mark for ogboot on linux
## [0.20.0] - 2025-06-24
### Changed
- In order to have /tmp/command.log updated in realtime, ogExecAndLog now spawns a subprocess rather than calling functions directly
## [0.19.2] - 2025-06-24
### Changed
- Write a mark for ogboot on linux only
## [0.19.1] - 2025-06-23
### Fixed
- Fixed path of EFI boot entry
## [0.19.0] - 2025-06-23
### Changed
- Write a mark for ogboot
## [0.18.2] - 2025-06-19
### Fixed
- Accept None as partition type
## [0.18.1] - 2025-06-18
### Fixed
- Look for grub.cfg in two places rather than one
## [0.18.0] - 2025-06-16
### Added
- Added scripts and libs for oggit
## [0.17.0] - 2025-06-16
### Changed
- Removed useless warning about /dev/loop0
- Fix windows EFI booting, and a typo
## [0.16.0] - 2025-06-12
### Changed
- Gave some care to the "Custom" scripts
## [0.15.3] - 2025-06-12
### Fixed
- Create missing dir
## [0.15.2] - 2025-06-11
### Fixed
- Fixed a condition check
## [0.15.1] - 2025-06-11
### Fixed
- Add a missing "import"
- Fix retrieving windows version from the registry
- Fix bug while building the "Part-01-01" string
- Removed obsolete unused "bootOS" scripts (with a capital "S")
## [0.15.0] - 2025-06-10
### Changed
- Remove opengnsys bash functions from the agent's environment
## [0.14.2] - 2025-06-09
### Fixed
- Get rc of bash pipelines in ProtocolLib
## [0.14.1] - 2025-06-07
### Fixed
- Fixed rc management in deployImage.py
## [0.14.0] - 2025-06-07
### Changed
- Read $ogusetls and $ogverifytls from the environment and configure stunnel accordingly
## [0.13.9] - 2025-06-04
### Fixed
- Copy grub.cfg so that grub finds the config upon boot
## [0.13.8] - 2025-06-03
### Fixed
- Paid attention to return codes between python (True for success) and shell (0 for success)
## [0.13.7] - 2025-06-02
### Fixed
- Fixed management of the "multicast session" parameter
## [0.13.6] - 2025-06-02
### Fixed
- Fixed variable name in restoreImage.py
## [0.13.5] - 2025-05-30
### Fixed
- Return a true value from the unicast/multicast methods
- Fully qualify a method call
## [0.13.4] - 2025-05-28
### Changed
- Show sgdisk output
## [0.13.3] - 2025-05-28
### Fixed
- unlink() only existing files
## [0.13.2] - 2025-05-28
### Changed
- Point urlMenu back to the localhost stunnel
## [0.13.1] - 2025-05-21
### Changed
- Make dbus envvar available to the agent
## [0.13.0] - 2025-05-19
### Added
- Run dbus
## [0.12.0] - 2025-05-18
### Changed
- no tls for the urlmenu either
## [0.11.0] - 2025-05-18
### Added
- Run stunnel and point the browser to it
## [0.10.0] - 2025-05-14
### Changed
- Run the new browser
## [0.9.0] - 2025-05-09
### Added
- Use zstd when creating and restoring images
## [0.8.4] - 2025-05-09
### Added
- When restoring an image, include the image name in the ogagent configuration file
## [0.8.3] - 2025-05-08
### Fixed
- Have ogNvramAddEntry() handle EFI entries with spaces in them
## [0.8.2] - 2025-05-07
### Changed
- Have Configurar.py ignore the tch parameter, take cache size from the definition of the cache partition
## [0.8.1] - 2025-05-07
### Fixed
- Gracefully handle error in ogBoot() when not finding /boot partition in target's fstab
## [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
## [0.1.0] - 2025-02-28 ## [0.1.0] - 2025-02-28
### Added ### Addded
- Merge pull request 'Include all client files, build debian package' (#2) from deb-package into main - Merge pull request 'Include all client files, build debian package' (#2) from deb-package into main

View File

@ -19,7 +19,7 @@ pipeline {
stage('Prepare Workspace') { stage('Prepare Workspace') {
steps { steps {
script { script {
env.BUILD_DIR = "${WORKSPACE}/ogclient" env.BUILD_DIR = "${WORKSPACE}/oggui"
sh "mkdir -p ${env.BUILD_DIR}" sh "mkdir -p ${env.BUILD_DIR}"
} }
} }
@ -48,22 +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') { stage('Build') {
steps { steps {
script { dir("${env.BUILD_DIR}") {
construirPaquete(env.BUILD_DIR, "../artifacts", "172.17.8.68", "/var/tmp/opengnsys/debian-repo/ogclient") 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/ogclient && mkdir -p /var/tmp/opengnsys/debian-repo/ogclient"
scp -r ../artifacts/* aptly@172.17.8.68:/var/tmp/opengnsys/debian-repo/ogclient
'''
} }
} }
} }
@ -75,24 +69,7 @@ pipeline {
} }
agent { label 'debian-repo' } agent { label 'debian-repo' }
steps { steps {
script { sh "aptly repo add opengnsys-devel /var/tmp/opengnsys/debian-repo/ogclient/*.deb"
// 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)
}
} }
} }
} }

View File

@ -23,7 +23,13 @@ case "$1" in
cp -a "$OLD_FILE" "$NEW_FILE" cp -a "$OLD_FILE" "$NEW_FILE"
# Append our configuration # 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 # Reload Samba
if command -v systemctl >/dev/null 2>&1; then if command -v systemctl >/dev/null 2>&1; then
@ -42,8 +48,6 @@ case "$1" in
;; ;;
esac esac
chown -R opengnsys:opengnsys /opt/opengnsys/ogclient
chown -R opengnsys:opengnsys /opt/opengnsys/ogclient_log
#DEBHELPER# #DEBHELPER#
exit 0 exit 0

View File

@ -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

View File

@ -1,7 +1,7 @@
[ogclient] [ogclient]
comment = OpenGnsys Client comment = OpenGnsys Client
browseable = no browseable = no
writeable = yes writeable = no
locking = no locking = no
path = /opt/opengnsys/ogclient path = /opt/opengnsys/ogclient
guest ok = no guest ok = no

Binary file not shown.

View File

@ -23,21 +23,15 @@ if [ -f "/usr/share/OGAgent/opengnsys/linux/OGAgentService.py" -a "$ogstatus" !=
cd /usr/share/OGAgent cd /usr/share/OGAgent
export OGAGENTCFG_OGCORE_IP=$ogcore export OGAGENTCFG_OGCORE_IP=$ogcore
export OGAGENTCFG_OGLOG_IP=$oglog export OGAGENTCFG_OGLOG_IP=$oglog
export OGAGENTCFG_URLMENU_SCHEME=http export OGAGENTCFG_URLMENU_IP=$ogcore
export OGAGENTCFG_URLMENU_IP=127.0.0.1
export OGAGENTCFG_URLMENU_PORT=81
(
## remove bash functions and some OG vars from the agent's environment
unset -f $(declare -F |awk '/og[A-Z]|NT[A-Z]/ { print $3 }')
unset $(declare |awk -F= '/^MSG_|^OG_ERR_/ { print $1 }')
python3 -m opengnsys.linux.OGAgentService fg python3 -m opengnsys.linux.OGAgentService fg
)
else else
for FILE in index $OGGROUP $(ogGetIpAddress) for FILE in index $OGGROUP $(ogGetIpAddress)
do do
[ -f $OGCAC/menus/$FILE.html ] && OGMENU="$OGCAC/menus/$FILE.html" [ -f $OGCAC/menus/$FILE.html ] && OGMENU="$OGCAC/menus/$FILE.html"
done done
$OPENGNSYS/bin/launch_browser $OGMENU echo "exec /usr/bin/OGBrowser $OGMENU" > /home/root/
/usr/bin/OGBrowser -qws $OGMENU
fi fi
# Si fallo en cliente y modo "admin", cargar shell; si no, salir. # Si fallo en cliente y modo "admin", cargar shell; si no, salir.

View File

@ -1,12 +0,0 @@
#!/bin/bash
F=/opt/opengnsys/functions
## BootLib.bootOs() makes a copy of grub.cfg in /boot/grub within the ESP
## clean it up
if $F/ogIsEfiActive; then
ESP=$($F/ogGetEsp)
MNTPT=$($F/ogMount $ESP)
rm -f $MNTPT/boot/grub/grub.cfg
$F/ogUnmount $ESP
fi

View File

@ -5,8 +5,8 @@ set -a
source /opt/opengnsys/etc/preinit/loadenviron.sh source /opt/opengnsys/etc/preinit/loadenviron.sh
# Scripts de inicio. # Scripts de inicio.
for f in cleanesp fileslinks loadmodules metadevs mountrepo poweroff filebeat otherservices; do for f in fileslinks loadmodules metadevs mountrepo poweroff otherservices; do
source $OGETC/preinit/$f.sh $OGETC/preinit/$f.sh
done done
unset f unset f

View File

@ -1,19 +0,0 @@
#!/bin/bash
F=/etc/filebeat/filebeat.yml
OPENSEARCH_PORT=9200
if [ -f $F ]; then
PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 |sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') ## taken from a sibling script
PASS=${PASS:-"og"}
PASS=OG+$(echo -n $PASS |sha256sum |cut -c1-12) ## og KDF
chmod 0600 $F
sed -i -e "s/__OGLOG_IP__/$oglog/g" \
-e "s/__OGLOG_PORT__/$OPENSEARCH_PORT/g" \
-e "s/__OPENSEARCH_PASSWORD__/$PASS/g" \
$F
unset PASS
mkdir -p /var/log/filebeat
/usr/bin/filebeat -c $F --path.home /usr/share/filebeat --path.config /etc/filebeat --path.data /var/lib/filebeat --path.logs /var/log/filebeat &
fi

View File

@ -7,71 +7,32 @@
#@date 2012-01-12 #@date 2012-01-12
#*/ #*/
# Montar efivar filesystem
ogIsEfiActive && mount -t efivarfs none /sys/firmware/efi/efivars ogIsEfiActive && mount -t efivarfs none /sys/firmware/efi/efivars
# Lanzar servicios complementarios del cliente.
echo "${MSG_OTHERSERVICES:-.}" echo "${MSG_OTHERSERVICES:-.}"
# stunnel start # Iniciar rsyslog, si es necesario.
cat >/etc/stunnel/menu.conf <<__EOF__
setuid = stunnel4
setgid = stunnel4
pid = /var/run/stunnel4/menu.pid
foreground = yes
debug = info
[menu]
client = yes
accept = 127.0.0.1:81
connect = $ogcore:8443
__EOF__
if [[ true == "$ogusetls" ]]; then
if [[ true == "$ogverifytls" ]]; then
## use tls and verify
cat >>/etc/stunnel/menu.conf <<__EOF__
cert = /opt/opengnsys/etc/ogagent.crt
key = /opt/opengnsys/etc/ogagent.key
CAfile = /opt/opengnsys/etc/ca.crt
requireCert = yes
verifyChain = yes
__EOF__
else
## use tls but not verify
cat >>/etc/stunnel/menu.conf <<__EOF__
cert = /opt/opengnsys/etc/ogagent.crt
key = /opt/opengnsys/etc/ogagent.key
CAfile = /opt/opengnsys/etc/ca.crt
requireCert = no
verifyChain = no
__EOF__
fi
else
## don't use tls
cat >>/etc/stunnel/menu.conf <<__EOF__
requireCert = no
verifyChain = no
__EOF__
fi
mkdir -p /var/run/stunnel4; chown stunnel4:stunnel4 /var/run/stunnel4
stunnel /etc/stunnel/menu.conf &>/var/log/stunnel4/menu.log &
# stunnel end
# dbus
if [ -e /etc/dbus-1/system.d/ogbrowser.conf ]; then
mkdir -p /run/dbus
DBUS_SESSION_BUS_ADDRESS=$(dbus-daemon --print-address --system --nosyslog)
export DBUS_SESSION_BUS_ADDRESS
dbus-monitor --system &>/var/log/dbus-monitor.log &
fi
[ -S /dev/log ] || service rsyslog start [ -S /dev/log ] || service rsyslog start
# root password # Adpatar la clave de "root" para acceso SSH.
PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \
sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
PASS=${PASS:-"og"} PASS=${PASS:-"og"}
echo -ne "$PASS\n$PASS\n" | passwd root 2>/dev/null echo -ne "$PASS\n$PASS\n" | passwd root 2>/dev/null
# Cargar el entorno OpenGnsys en conexión SSH.
cp -a $OPENGNSYS/etc/preinit/loadenviron.sh /etc/profile.d/ cp -a $OPENGNSYS/etc/preinit/loadenviron.sh /etc/profile.d/
# Arrancar SSH.
/etc/init.d/ssh start &>/dev/null /etc/init.d/ssh start &>/dev/null
#setterm -blank 0 -powersave off -powerdown 0 < /dev/console > /dev/console 2>&1 ## apagado de monitor # Desactivado apagado de monitor.
ethtool -s $DEVICE wol g 2>/dev/null ## Activado WOL en la interfaz usada en arranque PXE. #setterm -blank 0 -powersave off -powerdown 0 < /dev/console > /dev/console 2>&1
# Activado WOL en la interfaz usada en arranque PXE.
ethtool -s $DEVICE wol g 2>/dev/null
# TODO Localizar correctamente el script de arranque.
[ -f /opt/opengnsys/scripts/runhttplog.sh ] && /opt/opengnsys/scripts/runhttplog.sh 2>/dev/null [ -f /opt/opengnsys/scripts/runhttplog.sh ] && /opt/opengnsys/scripts/runhttplog.sh 2>/dev/null

View File

@ -19,7 +19,6 @@ if 5 == len (sys.argv):
args = parser.parse_args() args = parser.parse_args()
src = { 'container': args.src_container, 'file': args.src_file } src = { 'container': args.src_container, 'file': args.src_file }
dst = { 'container': args.dst_container, 'file': args.dst_file } dst = { 'container': args.dst_container, 'file': args.dst_file }
elif 7 == len (sys.argv): elif 7 == len (sys.argv):
parser.add_argument ('src_disk') parser.add_argument ('src_disk')
parser.add_argument ('src_par') parser.add_argument ('src_par')
@ -30,31 +29,6 @@ elif 7 == len (sys.argv):
args = parser.parse_args() args = parser.parse_args()
src = { 'disk': args.src_disk, 'par': args.src_par, 'file': args.src_file } src = { 'disk': args.src_disk, 'par': args.src_par, 'file': args.src_file }
dst = { 'disk': args.dst_disk, 'par': args.dst_par, 'file': args.dst_file } dst = { 'disk': args.dst_disk, 'par': args.dst_par, 'file': args.dst_file }
elif 4 == len (sys.argv):
## can be either:
## - src_container src_file dst_file
## - src_file dst_container dst_file
if 'REPO' == sys.argv[1] or 'CACHE' == sys.argv[1]:
## we are in "src_container src_file dst_file"
parser.add_argument ('src_container')
parser.add_argument ('src_file')
parser.add_argument ('dst_file')
args = parser.parse_args()
src = { 'container': args.src_container, 'file': args.src_file }
dst = { 'file': args.dst_file }
elif 'REPO' == sys.argv[2] or 'CACHE' == sys.argv[2]:
## we are in "src_file dst_container dst_file"
parser.add_argument ('src_file')
parser.add_argument ('dst_container')
parser.add_argument ('dst_file')
args = parser.parse_args()
src = { 'file': args.src_file }
dst = { 'container': args.dst_container, '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)
elif 6 == len (sys.argv): elif 6 == len (sys.argv):
## can be either: ## can be either:
## - src_disk src_par src_file dst_container dst_file ## - src_disk src_par src_file dst_container dst_file
@ -62,7 +36,7 @@ elif 6 == len (sys.argv):
try: try:
num = int (sys.argv[1]) ## raises ValueError if sys.argv[1] doesn't look like a number num = int (sys.argv[1]) ## raises ValueError if sys.argv[1] doesn't look like a number
## we are in "src_disk src_par src_file dst_container dst_file" ## "src_disk src_par src_file dst_container dst_file"
parser.add_argument ('src_disk') parser.add_argument ('src_disk')
parser.add_argument ('src_par') parser.add_argument ('src_par')
parser.add_argument ('src_file') parser.add_argument ('src_file')
@ -72,7 +46,7 @@ elif 6 == len (sys.argv):
src = { 'disk': args.src_disk, 'par': args.src_par, 'file': args.src_file } src = { 'disk': args.src_disk, 'par': args.src_par, 'file': args.src_file }
dst = { 'container': args.dst_container, 'file': args.dst_file } dst = { 'container': args.dst_container, 'file': args.dst_file }
except: except:
## we are in "src_container src_file dst_disk dst_par dst_file" ## "src_container src_file dst_disk dst_par dst_file"
parser.add_argument ('src_container') parser.add_argument ('src_container')
parser.add_argument ('src_file') parser.add_argument ('src_file')
parser.add_argument ('dst_disk') parser.add_argument ('dst_disk')
@ -81,9 +55,6 @@ elif 6 == len (sys.argv):
args = parser.parse_args() args = parser.parse_args()
src = { 'container': args.src_container, 'file': args.src_file } src = { 'container': args.src_container, 'file': args.src_file }
dst = { 'disk': args.dst_disk, 'par': args.dst_par, 'file': args.dst_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) ret = ogCopyFile (src, dst)
if ret is not None: if ret is not None:

View File

@ -0,0 +1,3 @@
#!/bin/bash
poweroff
exit 0

View File

@ -2,9 +2,6 @@
import os import os
import sys import sys
import time
os.system ('pkill -f OGAgent')
time.sleep (3)
os.system ('poweroff') os.system ('poweroff')
sys.exit (0) sys.exit (0)

View File

@ -0,0 +1,54 @@
#!/bin/bash
#______________________________________
#
# PARAMETROS RECIBIDOS DESDE EL CLIENTE
# $1 modo (admin, user)
#______________________________________
# Error si llamada no se realliza desde OpenGnsys Client.
PROG=$(basename $0)
#CALLER=$(ogGetCaller)
#if ! $(ogCheckStringInGroup "$CALLER" "CrearImagen ConsolaRemota CrearImagenBasica CrearSoftIncremental"); then
# ogRaiseError $OG_ERR_NOTEXEC "$CALLER -> $PROG"
# exit $?
#fi
# Salir si el repositorio está bloquedo (tiene ficheros abiertos).
REPOIP=$(ogGetRepoIp)
if [ -z "$REPOIP" ]; then
ogRaiseError $OG_ERR_NOTFOUND "repo no montado"
exit $?
fi
if ogIsRepoLocked; then
ogRaiseError $OG_ERR_LOCKED "repo $REPOIP"
exit $?
fi
# Comprobar protocolo y modo de acceso.
PROTO=${ogprotocol:-"smb"}
case "$PROTO" in
nfs|smb) ;;
*) ogRaiseError $OG_ERR_FORMAT "protocolo desconocido $PROTO"
exit $? ;;
esac
case "$1" in
admin) MODE="rw" ;;
user) MODE="ro" ;;
*) ogRaiseError $OG_ERR_FORMAT "modo desconocido $1"
exit $? ;;
esac
# Desmontar repositorio y volver a montarlo con el modo adecuado.
umount $OGIMG
# Unidad organizativa
[ "$ogunit" != "" ] && OGUNIT="/$ogunit"
ogEcho info "$PROG: Montar repositorio $REPO por $PROTO en modo $1"
case "$PROTO" in
nfs) mount -t nfs $REPOIP:$OGIMG$OGUNIT $OGIMG -o $MODE ;;
smb) PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \
sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
PASS=${PASS:-"og"}
mount.cifs //$REPOIP/ogimages$OGUNIT $OGIMG -o $MODE,serverino,acl,username=opengnsys,password=$PASS
esac

View File

@ -0,0 +1,159 @@
#!/bin/bash
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimieincludento para httpdlog
echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp
# Registro de inicio de ejecución
ogEcho log session "$MSG_INTERFACE_START $0 $*"
# Solo ejecutable por OpenGnsys Client.
PATH=$PATH:$(dirname $0)
PROG=$(basename $0)
#____________________________________________________________________
#
# El parámetro $2 es el que aporta toda la información y el $1 se queda obsoleto
# Formato de entrada:
# dis=Número de disco
# *=caracter de separación
# che=Vale 0 o 1
# *=caracter de separación
# $tch=tamaño cache
# != caracter de separación
#
# Y un numero indeterminado de cadenas del tipo siguuenteseparadas por el caracter '$':
# par=Número de particion*cod=Código de partición*sfi=Sistema de ficheros*tam=Tamaño de la partición*ope=Operación
# @= caracter de separación
#____________________________________________________________________
# Captura de parámetros (se ignora el 1er parámetro y se eliminan espacios y tabuladores).
#param='dis=1*che=0*tch=70000000!par=1*cpt=NTFS*sfi=NTFS*tam=11000000*ope=0%'
shift
param="$(echo $* | sed 's/[ ]//g')"
# Activa navegador para ver progreso
coproc /opt/opengnsys/bin/browser -qws http://localhost/cgi-bin/httpd-log.sh
# Leer los dos bloques de parámetros, separados por '!'.
declare -a TBPRM
IFS='!' read -a TBPRM <<<"$param"
pparam="${TBPRM[0]}" # Parámetros generales del disco.
sparam="${TBPRM[1]}" # Parámetros de particionado y formateo.
# 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.
unset TBPRM
IFS='*' read -a TBPRM <<<"$pparam"
[[ ${TBPRM} =~ = ]] && eval ${TBPRM[@]} # Comprobar asignación antes de exportar valores.
# Error si no se define el parámetro de disco (dis).
[ -z "$dis" ] && exit $OG_ERR_FORMAT
# Toma valores de distribución de particiones, separados por "%".
declare -a CFG # Valores de configuración.
declare -a TBP # Tabla de particionado.
declare -a TBF # Tabla de formateo.
unset TBPRM
IFS='%' read -a TBPRM <<<"$sparam"
maxp=0
for ((i=0; i<${#TBPRM[@]}; i++)); do
# Leer datos de la partición, separados por "*".
unset par
IFS='*' read -a CFG <<<"${TBPRM[i]}" 2>/dev/null
[[ ${CFG} =~ = ]] && eval ${CFG[@]} # Comprobar asignación antes de exportar valores.
# Componer datos de particionado.
if [ "$cpt" != "CACHE" ]; then
TBP[par]="$cpt:$tam"
fi
# Si se activa operación de formatear, componer datos de formateo.
if [ "$ope" == 1 ]; then
# Comprobamos que la particion y el s.f sean validos.
ogCheckStringInGroup $cpt "EMPTY EXTENDED LINUX-LVM LVM ZPOOL"
[ $? -ne 0 ] && TBF[par]="$sfi"
fi
# Obtener la partición mayor.
[ $par -gt $maxp ] && maxp=$par
done
#____________________________________________________
#
# Proceso
#____________________________________________________
# Tamaño actual de la cache
CACHESIZE=$(ogGetCacheSize)
# Desmonta todas las particiones y la caché
ogEcho session log "[10] $MSG_HELP_ogUnmountAll"
ogUnmountAll $dis &>/dev/null
ogUnmountCache
# Elimina la tabla de particiones
if [ `ogGetPartitionTableType 1` != 'MSDOS' ]; then
ogDeletePartitionTable $dis
ogExecAndLog COMMAND ogUpdatePartitionTable $dis
# Crea tabla de particiones MSDOS (NOTA: adaptar para tablas GPT).
ogCreatePartitionTable $dis MSDOS
fi
# Inicia la cache.
if echo "$sparam" |grep "CACHE" >/dev/null; then
ogEcho session log "[30] $MSG_HELP_ogCreateCache"
ogEcho session log " initCache $tch"
ogExecAndLog COMMAND initCache $tch
fi
# Definir particionado.
ogEcho session log "[50] $MSG_HELP_ogCreatePartitions"
ogEcho session log " ogCreatePartitions $dis ${TBP[@]}"
ogExecAndLog COMMAND ogCreatePartitions $dis ${TBP[@]}
if [ $? -ne 0 ]; then
kill $COPROC_PID
exit $(ogRaiseError session log $OG_ERR_GENERIC "ogCreatePartitions $dis ${TBP[@]}")
fi
ogExecAndLog COMMAND ogUpdatePartitionTable $dis
# Formatear particiones
ogEcho session log "[70] $MSG_HELP_ogFormat"
for ((par=1; par<=$maxp; par++)); do
case "${TBF[par]}" in
CACHE) # Si el tamaño es distinto ya se ha formateado.
if [ "$CACHESIZE" == $tch ]; then
ogEcho session log " ogFormatCache"
ogExecAndLog COMMAND ogFormatCache
fi
;;
"") ;;
*) ogEcho session log " ogFormatFs $dis $par ${TBF[par]}"
ogExecAndLog COMMAND ogFormatFs $dis $par ${TBF[par]}
if [ $? -ne 0 ]; then
kill $COPROC_PID
exit $(ogRaiseError session log $OG_ERR_GENERIC "ogFormatFs $dis $par ${TBF[par]}");
fi
;;
esac
done
RETVAL=$?
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
#___________________________________________________________________
#
# Retorno
#___________________________________________________________________
kill $COPROC_PID
exit 0

View File

@ -2,13 +2,13 @@
import os import os
import sys import sys
import subprocess
import ogGlobals import ogGlobals
import SystemLib import SystemLib
import CacheLib import CacheLib
import FileSystemLib import FileSystemLib
import DiskLib import DiskLib
import InventoryLib
#Load engine configurator from engine.cfg file. #Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg #Carga el configurador del engine desde el fichero engine.cfg
@ -34,6 +34,10 @@ prog = os.path.basename(__name__)
# El parámetro $2 es el que aporta toda la información y el $1 se queda obsoleto # El parámetro $2 es el que aporta toda la información y el $1 se queda obsoleto
# Formato de entrada: # Formato de entrada:
# dis=Número de disco # dis=Número de disco
# *=caracter de separación
# che=Vale 0 o 1
# *=caracter de separación
# $tch=tamaño cache
# != caracter de separación # != caracter de separación
# #
# Y un numero indeterminado de cadenas del tipo siguuenteseparadas por el caracter '$': # Y un numero indeterminado de cadenas del tipo siguuenteseparadas por el caracter '$':
@ -42,45 +46,47 @@ prog = os.path.basename(__name__)
#____________________________________________________________________ #____________________________________________________________________
# Captura de parámetros (se ignora el 1er parámetro y se eliminan espacios y tabuladores). # Captura de parámetros (se ignora el 1er parámetro y se eliminan espacios y tabuladores).
#param='dis=1!par=1*cpt=NTFS*sfi=NTFS*tam=11000000*ope=0%' #param='dis=1*che=0*tch=70000000!par=1*cpt=NTFS*sfi=NTFS*tam=11000000*ope=0%'
#param = ''.join(sys.argv[2:]).replace(' ', '').replace('\t', '') #param = ''.join(sys.argv[2:]).replace(' ', '').replace('\t', '')
param = sys.argv[2] param = sys.argv[2]
# Activa navegador para ver progreso
coproc = subprocess.Popen (['/opt/opengnsys/bin/browser', '-qws', 'http://localhost/cgi-bin/httpd-log.sh'])
# Leer los dos bloques de parámetros, separados por '!'. # Leer los dos bloques de parámetros, separados por '!'.
tbprm = param.split ('!') tbprm = param.split ('!')
pparam = tbprm[0] # General disk parameters pparam = tbprm[0] # General disk parameters
sparam = tbprm[1] # Partitioning and formatting parameters sparam = tbprm[1] # Partitioning and formatting parameters
is_there_cache = 'CACHE' in sparam
# Toma valores de disco y caché, separados por "*". # 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. # Los valores están en las variables $dis: disco, $che: existe cache (1, 0), $tch: Tamaño de la cache.
pparams = pparam.split ('*') tbprm = pparam.split ('*')
dis = tch = None dis = ptt = tch = None
for item in pparams: for item in tbprm:
if '=' not in item: continue if '=' not in item: continue
k, v = item.split ('=', 1) k, v = item.split ('=', 1)
if k not in ['dis']: if k not in ['dis', 'tch', 'ptt']: ## 'ptt' added, unused 'che' removed
print (f'ignoring unknown disk parameter ({k})') print (f'ignoring unknown disk parameter ({k})')
continue continue
if 'dis' == k: dis = int (v) 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). # Error si no se define el parámetro de disco (dis).
if dis is None: if dis is None: sys.exit (ogGlobals.OG_ERR_FORMAT)
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 "%". # Toma valores de distribución de particiones, separados por "%".
tbp = [] # Valores de configuración (parámetros para ogCreatePartitions) tbp = [] # Valores de configuración (parámetros para ogCreatePartitions)
tbf = {} # Tabla de formateo tbf = {} # Tabla de formateo
sparams = sparam.split('%') tbprm = sparam.split('%')
maxp=0 maxp=0
sum_tam = 0 for item in tbprm:
do_sum_tam = True
cache_seen = extended_seen = efi_seen = False
for item in sparams:
if not item: continue ## por si nos pasan un '%' al final de todo if not item: continue ## por si nos pasan un '%' al final de todo
# Leer datos de la partición, separados por "*". # Leer datos de la partición, separados por "*".
par = cpt = sfi = tam = None par = cpt = sfi = tam = None
@ -96,42 +102,20 @@ for item in sparams:
if 'par' == k: par = int (v) if 'par' == k: par = int (v)
elif 'cpt' == k: cpt = v elif 'cpt' == k: cpt = v
elif 'sfi' == k: sfi = v elif 'sfi' == k: sfi = v
elif 'tam' == k: tam = int (v) elif 'tam' == k: tam = v
elif 'ope' == k: ope = int (v) elif 'ope' == k: ope = int (v)
missing_params = [] missing_params = []
if par is None or 'None' == par: missing_params.append ('par') if par is None: missing_params.append ('par')
if cpt is None or 'None' == cpt: missing_params.append ('cpt') if cpt is None: missing_params.append ('cpt')
if sfi is None or 'None' == sfi: missing_params.append ('sfi') if sfi is None: missing_params.append ('sfi')
if tam is None or 'None' == tam: missing_params.append ('tam') if tam is None: missing_params.append ('tam')
if missing_params: if missing_params:
print (f'partition data ({item}) missing required parameters ({' '.join (missing_params)})') print (f'partition data ({item}) missing required parameters ({' '.join (missing_params)})')
sys.exit (1) sys.exit (1)
# Componer datos de particionado. # Componer datos de particionado.
if 'EFI' == cpt: if 'CACHE' != cpt: tbp.append (f'{cpt}:{tam}')
if efi_seen:
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_FORMAT, f'se ha solicitado más de una partición de ESP')
sys.exit (1)
efi_seen = True
if 'CACHE' == cpt:
if cache_seen:
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_FORMAT, f'se ha solicitado más de una partición de cache')
sys.exit (1)
cache_seen = True
tch = tam
else:
tbp.append (f'{cpt}:{tam}')
if do_sum_tam:
sum_tam += tam
if 'EXTENDED' == cpt:
if extended_seen:
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_FORMAT, f'se ha solicitado más de una partición extendida')
sys.exit (1)
extended_seen = True
extended_is_at = par
do_sum_tam = False ## don't sum sizes anymore
if ope: if ope:
# Si se activa operación de formatear, componer datos de formateo. # Si se activa operación de formatear, componer datos de formateo.
if cpt not in ['EMPTY', 'EXTENDED', 'LINUX-LVM', 'LVM', 'ZPOOL']: if cpt not in ['EMPTY', 'EXTENDED', 'LINUX-LVM', 'LVM', 'ZPOOL']:
@ -139,90 +123,6 @@ for item in sparams:
# Obtener la partición mayor. # Obtener la partición mayor.
if par > maxp: maxp = par if par > maxp: maxp = par
if tch is None:
tch = 0
cur_ptt = DiskLib.ogGetPartitionTableType (dis)
ptt = 'GPT' if InventoryLib.ogIsEfiActive() else 'MSDOS'
if not cache_seen and not tbp:
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_FORMAT, f'No se ha solicitado ninguna partición')
sys.exit (1)
if 'GPT' == ptt and extended_seen:
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_FORMAT, f'En GPT no se pueden usar particiones extendidas')
sys.exit (1)
## error si nos piden más de 4 y ninguna es extendida
if 'MSDOS' == ptt and not extended_seen:
requested_partitions = len (tbp)
if cache_seen: requested_partitions += 1
if requested_partitions > 4:
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_FORMAT, f'Se han solicitado más de 4 particiones y ninguna es extendida')
sys.exit (1)
if efi_seen:
if 'EFI' != tbp[0].split (':')[0]:
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_FORMAT, f'la partición ESP debe estar declarada en primera posición')
sys.exit (1)
else:
if 'GPT' == ptt and 1 == dis:
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_FORMAT, f'En GPT debe haber una partición ESP')
sys.exit (1)
## si no nos definen partición de cache y el disco tiene una, hay que borrarla
if not cache_seen:
c = CacheLib.ogFindCache()
if c:
cache_disk, cache_part = c.split()
if int (cache_disk) == int (dis):
CacheLib.ogUnmountCache()
CacheLib.ogDeleteCache()
## la extendida solo puede estar en la (si hay cache) o en la 4 (si no lo hay)
if extended_seen:
extended_should_be_at = 3 if cache_seen else 4
if extended_is_at != extended_should_be_at:
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_FORMAT, f'La partición extendida no puede ser la "{extended_is_at}" sino que debe ser la "{extended_should_be_at}"')
sys.exit (1)
recreate_partition_table = False
if not cur_ptt:
SystemLib.ogEcho (['session', 'log'], None, f'No partition table--will create a "{ptt}" one')
recreate_partition_table = True
if cur_ptt and ptt != cur_ptt:
SystemLib.ogEcho (['session', 'log'], None, f'Current partition table type "{cur_ptt}" is wrong for this system--will replace it for a "{ptt}" one')
recreate_partition_table = True
## size check: check that cache fits in the space left by the previously existing partitions
if not recreate_partition_table and not CacheLib.ogCheckNewCacheSize (dis, tch):
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_CACHE, f'nueva partición de caché no cabe en el hueco actual')
## BUG el "hueco actual" me podría dar igual, si luego resulta que también estoy definiendo otras particiones y ya sí hay sitio para todo
sys.exit (1)
## size check: check that the newly defined partitions fit in the disk
disk_sectors = DiskLib.ogGetLastSector (dis)
IOSIZE = DiskLib.ogGetIoSize (dis)
if not IOSIZE:
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_FORMAT, f'Failed to get disk sector size')
sys.exit (1)
if 512 == IOSIZE:
sum_tam_sectors = sum_tam*2
cache_sectors = tch*2
else:
sum_tam_sectors = (sum_tam+3)//4 ## sumamos 3 para que la división entera "redondee al alza"
cache_sectors = (tch+3)//4
## esta comprobacion puede dejar pasar situaciones que más tarde dan error
## la ventana es bastante estrecha, y sumando aquí simplemente un 1 por 1000, ya la cerramos del todo
sum_tam_sectors = int (sum_tam_sectors * 1.001)
space_left_by_cache = disk_sectors - cache_sectors
if sum_tam_sectors > space_left_by_cache:
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_CACHE, f'las particiones no caben en el disco')
sys.exit (1)
#____________________________________________________ #____________________________________________________
# #
# Proceso # Proceso
@ -236,46 +136,54 @@ SystemLib.ogEcho (['session', 'log'], None, f'[10] {ogGlobals.lang.MSG_HELP_ogUn
FileSystemLib.ogUnmountAll (dis) FileSystemLib.ogUnmountAll (dis)
CacheLib.ogUnmountCache() CacheLib.ogUnmountCache()
if recreate_partition_table: # Elimina la tabla de particiones
cur_ptt = DiskLib.ogGetPartitionTableType (dis)
if not cur_ptt or ptt != cur_ptt:
DiskLib.ogDeletePartitionTable (dis) DiskLib.ogDeletePartitionTable (dis)
SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGPYFUNCS}/ogUpdatePartitionTable']) SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable)
# Crea tabla de particiones MSDOS (NOTA: adaptar para tablas GPT).
DiskLib.ogCreatePartitionTable (dis, ptt) DiskLib.ogCreatePartitionTable (dis, ptt)
# Inicia la cache. # Inicia la cache.
if is_there_cache: if 'CACHE' in sparam:
SystemLib.ogEcho (['session', 'log'], None, f'[30] {ogGlobals.lang.MSG_HELP_ogCreateCache}') SystemLib.ogEcho (['session', 'log'], None, f'[30] {ogGlobals.lang.MSG_HELP_ogCreateCache}')
SystemLib.ogEcho (['session', 'log'], None, f' initCache.py {dis} {tch}') SystemLib.ogEcho (['session', 'log'], None, f' initCache {tch}')
rc = SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGSCRIPTS}/initCache.py', str (dis), str (tch)]) SystemLib.ogExecAndLog ('command', CacheLib.initCache, tch)
if not rc:
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_CACHE, f'initCache.py failed')
sys.exit (1)
# Definir particionado. # Definir particionado.
if tbp:
SystemLib.ogEcho (['session', 'log'], None, f'[50] {ogGlobals.lang.MSG_HELP_ogCreatePartitions}') SystemLib.ogEcho (['session', 'log'], None, f'[50] {ogGlobals.lang.MSG_HELP_ogCreatePartitions}')
SystemLib.ogEcho (['session', 'log'], None, f' ogCreatePartitions {dis} {' '.join (tbp)}') SystemLib.ogEcho (['session', 'log'], None, f' ogCreatePartitions {dis} {' '.join (tbp)}')
res = SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGPYFUNCS}/ogCreatePartitions', str(dis)] + tbp) res = SystemLib.ogExecAndLog ('command', DiskLib.ogCreatePartitions, dis, tbp)
if not res: if not res:
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_FORMAT, f'ogCreatePartitions {dis} {' '.join (tbp)}') coproc.kill()
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_GENERIC, f'ogCreatePartitions {dis} {' '.join (tbp)}')
sys.exit (1) sys.exit (1)
SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGPYFUNCS}/ogUpdatePartitionTable']) SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable)
retval = 0
if tbf:
# Formatear particiones # Formatear particiones
SystemLib.ogEcho (['session', 'log'], None, f'[70] {ogGlobals.lang.MSG_HELP_ogFormat}') SystemLib.ogEcho (['session', 'log'], None, f'[70] {ogGlobals.lang.MSG_HELP_ogFormat}')
retval = 0
for p in range (1, maxp+1): for p in range (1, maxp+1):
if p not in tbf: continue if p not in tbf: continue
if 'CACHE' == tbf[p]: if 'CACHE' == tbf[p]:
if CACHESIZE == tch: # Si el tamaño es distinto ya se ha formateado. if CACHESIZE == tch: # Si el tamaño es distinto ya se ha formateado.
SystemLib.ogEcho (['session', 'log'], None, ' ogFormatCache') SystemLib.ogEcho (['session', 'log'], None, ' ogFormatCache')
retval = SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGPYFUNCS}/ogFormatCache']) retval = SystemLib.ogExecAndLog ('command', CacheLib.ogFormatCache)
else: else:
SystemLib.ogEcho (['session', 'log'], None, f' ogFormatFs {dis} {p} {tbf[p]}') SystemLib.ogEcho (['session', 'log'], None, f' ogFormatFs {dis} {p} {tbf[p]}')
retval = SystemLib.ogExecAndLog ('command', [f'{ogGlobals.OGPYFUNCS}/ogFormatFs', str(dis), str(p), tbf[p]]) retval = SystemLib.ogExecAndLog ('command', FileSystemLib.ogFormatFs, dis, str(p), tbf[p])
if not retval: if retval:
coproc.kill()
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_GENERIC, f'ogFormatFs {dis} {p} {tbf[p]}') SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_GENERIC, f'ogFormatFs {dis} {p} {tbf[p]}')
sys.exit (1) sys.exit (1)
# Registro de fin de ejecución
SystemLib.ogEcho (['session', 'log'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}') SystemLib.ogEcho (['session', 'log'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}')
#___________________________________________________________________
#
# Retorno
#___________________________________________________________________
coproc.kill()
sys.exit (0) sys.exit (0)

View File

@ -0,0 +1,3 @@
#!/bin/bash
chmod +x $1
$1>$2 || exit $?

View File

@ -0,0 +1,91 @@
#!/bin/bash
#___________________________________________________
#
# 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
TIME1=$SECONDS
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp
# Registro de inicio de ejecución
ogEcho log session "$MSG_INTERFACE_START $0 $*"
# Solo ejecutable por OpenGnsys Client.
PATH=$PATH:$(dirname $0)
PROG=$(basename $0)
#CALLER=$(ogGetCaller)
#if [ "$CALLER" != "ogAdmClient" ]; then
# ogRaiseError $OG_ERR_NOTEXEC "$CALLER -> $PROG"
# exit $?
#fi
# Valor por defecto para el repositorio.
REPO=${4:-"REPO"}
[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE"
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
ogCheckIpAddress $REPO
if [ $? == 0 -o $REPO == "REPO" ] ; then
# Unidad organizativa
[ "$ogunit" != "" ] && OGUNIT="$ogunit"
# Si falla el cambio -> salimos con error repositorio no valido
ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?)
REPO="REPO"
fi
# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura,
if [ "$REPO" == "REPO" -a "$boot" != "admin" ]
then
CambiarAcceso admin &>> $OGLOGFILE
RETVAL=$?
[ $RETVAL -gt 0 ] && exit $RETVAL
fi
ogEcho createImage "$1" "$2" "$4" /"$3"
# Si existe, ejecuta script personalizado "createImageCustom"; si no, llama al genérico "createImage".
if which createImageCustom &>/dev/null; then
createImageCustom "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND
else
createImage "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND
fi
RETVAL=$?
# Cambiar acceso a modo usuario, si es necesario.
[ "$REPO" == "REPO" -a "$boot" != "admin" ] && CambiarAcceso user
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
exit $RETVAL

View File

@ -66,7 +66,7 @@ repo = arg_repo
if not repo: repo = 'REPO' if not repo: repo = 'REPO'
if repo == ogGetIpAddress(): repo = 'CACHE' if repo == ogGetIpAddress(): repo = 'CACHE'
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. # Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
if 'REPO' == repo or ogCheckIpAddress (repo): if 'REPO' == repo or StringLib.ogCheckIpAddress (repo):
# Si falla el cambio -> salimos con error repositorio no valido # Si falla el cambio -> salimos con error repositorio no valido
if not ogChangeRepo (repo): if not ogChangeRepo (repo):
ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repo) ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repo)

View File

@ -1,80 +0,0 @@
#!/usr/bin/env python3
import sys
import resource
import logging
import NetLib
import ogGlobals
import SystemLib
import DiskLib
import NetLib
from GitLib import OpengnsysGitLibrary, NTFSImplementation, OgProgressPrinterWeb
def create_image(disk_num, partition_num, repo, image_name, tagName):
ntfs_impl = NTFSImplementation.NTFS3G
og_git = OpengnsysGitLibrary(ntfs_implementation = ntfs_impl)
og_git.progress_callback = OgProgressPrinterWeb()
device = DiskLib.ogDiskToDev(disk_num, partition_num)
if og_git.initRepo(device, image_name):
return 0
#if tagName:
# og_git.tag(device = device, tagName = tagName, commit = "HEAD", message = "Image created")
else:
return 1
def main():
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
# Usamos el mínimo entre 65536 y el límite hard disponible
new_limit = min(65536, hard)
resource.setrlimit(resource.RLIMIT_NOFILE, (new_limit, hard))
print(f"RLIMIT_NOFILE establecido a: {resource.getrlimit(resource.RLIMIT_NOFILE)}")
except ValueError as e:
print(f"No se pudo aumentar el límite de archivos abiertos: {e}")
if len(sys.argv) != 6:
sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, "Incorrect number of arguments. Usage: CrearImagenGit.py disk_num partition_num image_name repo tag"))
# repo - repositorio, ip address. Opcional porque oglive lo recibe como parametro de kernel
# tag - tag a crear automaticamente. Opcional, no necesitamos crear un tag siempre.
disk_num, partition_num, image_name, repo, tag = sys.argv[1:6]
opengnsys_log_dir = "/opt/opengnsys/log"
ip_address = NetLib.ogGetIpAddress()
logFilePath = f"{opengnsys_log_dir}/{ip_address}.log"
fileLog = logging.FileHandler(logFilePath)
fileLog.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)24s - [%(levelname)5s] - %(message)s')
fileLog.setFormatter(formatter)
logger = logging.getLogger(__package__)
logger.setLevel(logging.DEBUG)
logger.addHandler(fileLog)
logger.info("Starting CrearImagenGit")
retval = create_image(disk_num, partition_num, repo, image_name, tag)
sys.exit(retval)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,44 @@
#!/bin/bash
TIME1=$SECONDS
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
echo -n "" > $OGLOGSESSION; echo -n "" > $OGLOGCOMMAND
# Registro de inicio de ejecución
ogEcho log session "$MSG_INTERFACE_START $0 $*"
echo -e "\n Instrucciones a ejecutar: *****************************" >> $OGLOGFILE
cat $1 >> $OGLOGFILE
echo -e "\n Salida de las instrucciones: *****************************" >> $OGLOGFILE
chmod +x $1
# Si mandamos la salida a OGLOGCOMMAND reescribimos lo que manda el comando.
#$1 &>> $OGLOGCOMMAND
$1
RETVAL=$?
TIME=$[SECONDS-TIME1]
if [ $RETVAL == 0 ]
then
ogEcho log session "[100] Duracion de la operacion $[TIME/60]m $[TIME%60]s"
else
ogRaiseError log session $RETVAL
ogEcho log session error "Operacion no realizada"
fi
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
exit $RETVAL

View File

@ -34,7 +34,7 @@ with open (ogGlobals.OGLOGFILE, 'a') as logfd:
os.chmod (script_path, 0o755) os.chmod (script_path, 0o755)
# Si mandamos la salida a OGLOGCOMMAND reescribimos lo que manda el comando. # Si mandamos la salida a OGLOGCOMMAND reescribimos lo que manda el comando.
RETVAL = subprocess.run (['bash', script_path]).returncode RETVAL = subprocess.run (script_path, capture_output=True, text=True).returncode
TIME = time.time() - TIME1 TIME = time.time() - TIME1

View File

@ -0,0 +1,13 @@
#!/bin/bash
# UHU - Comprobamos el disco, si solo hay un parametro, disco es 1, por compatibilidad con clientes antiguos
if [ $# == 1 ]
then
disk=1
part=$1
else
disk=$1
part=$2
fi
bootOs $disk $part

View File

@ -0,0 +1,6 @@
#!/bin/bash
# Script de interfaz para guardar en un fichero el inventario de hardware de un cliente.
file=$(listHardwareInfo)
tail -n+2 $file >$1

View File

@ -0,0 +1,19 @@
#!/bin/bash
TIME1=$SECONDS
#Carga el configurador del engine desde el fichero engine.cfg
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
echo -n " " | tee $OGLOGSESSION $OGLOGCOMMAND ${OGLOGCOMMAND}.tmp
# Registro de inicio de ejecución
ogEcho log session "$MSG_INTERFACE_START $0 $*"
file=$(listSoftwareInfo $1 $2)
cp $file $3
TIME=$[SECONDS-TIME1]
ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL : $[TIME/60]m $[TIME%60]s"

View File

@ -1,96 +0,0 @@
#!/usr/bin/env python3
import os
import subprocess
import sys
import time
import resource
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
# Usamos el mínimo entre 65536 y el límite hard disponible
new_limit = min(65536, hard)
resource.setrlimit(resource.RLIMIT_NOFILE, (new_limit, hard))
print(f"RLIMIT_NOFILE establecido a: {resource.getrlimit(resource.RLIMIT_NOFILE)}")
except ValueError as e:
print(f"No se pudo aumentar el límite de archivos abiertos: {e}")
# Añadir rutas personalizadas de forma segura
extra_paths = [
"/opt/opengnsys/interfaceAdm/git/",
"/opt/opengnsys/ogrepository/oggit/lib/"
]
# Si estás completamente seguro de que esta ruta no interfiere con la stdlib
# y contiene todos los módulos necesarios, puedes añadirla AL FINAL del path.
path_maybe_problematic = "/opt/oglive/rootfs/opt/opengnsys/lib/python3/"
if os.path.isdir(path_maybe_problematic):
sys.path.append(path_maybe_problematic)
for path in extra_paths:
if os.path.isdir(path):
sys.path.append(path)
import NetLib
import ogGlobals
import SystemLib
import logging
import DiskLib
import NetLib
from GitLib import OpengnsysGitLibrary, NTFSImplementation, OgProgressPrinterWeb
def commit_image(disk_num, partition_num, repo, image_name, msg):
ntfs_impl = NTFSImplementation.NTFS3G
og_git = OpengnsysGitLibrary(ntfs_implementation = ntfs_impl)
og_git.progress_callback = OgProgressPrinterWeb()
device = DiskLib.ogDiskToDev(disk_num, partition_num)
og_git.initRepo(device, image_name)
og_git.commit(device, msg)
og_git.push()
def main():
if len(sys.argv) != 6:
sys.exit(SystemLib.ogRaiseError([], ogGlobals.OG_ERR_FORMAT, "Incorrect number of arguments. Usage: ModificarImagenGit.py disk_num partition_num image_name repo msg"))
# repo - repositorio, ip address. Opcional porque oglive lo recibe como parametro de kernel
# tag - tag a crear automaticamente. Opcional, no necesitamos crear un tag siempre.
disk_num, partition_num, image_name, repo, msg = sys.argv[1:6]
opengnsys_log_dir = "/opt/opengnsys/log"
ip_address = NetLib.ogGetIpAddress()
logFilePath = f"{opengnsys_log_dir}/{ip_address}.log"
fileLog = logging.FileHandler(logFilePath)
fileLog.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)24s - [%(levelname)5s] - %(message)s')
fileLog.setFormatter(formatter)
logger = logging.getLogger(__package__)
logger.setLevel(logging.DEBUG)
logger.addHandler(fileLog)
logger.info("Starting ModificarImagenGit")
retval = commit_image(disk_num, partition_num, repo, image_name, msg)
sys.exit(retval)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,3 @@
#!/bin/bash
reboot
exit 0

View File

@ -2,9 +2,6 @@
import os import os
import sys import sys
import time
os.system ('pkill -f OGAgent')
time.sleep (3)
os.system ('reboot') os.system ('reboot')
sys.exit (0) sys.exit (0)

View File

@ -0,0 +1,15 @@
#!/bin/bash
#_______________________________________________________________________________________________________________________________
#
# 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".
deployImage "$4" "$3" "$1" "$2" "$5" "$6" "$7" "$8" || exit $?

View File

@ -19,11 +19,11 @@ import ogGlobals
if __name__ == '__main__': if __name__ == '__main__':
prog = sys.argv[0] prog = sys.argv[0]
if len (sys.argv) < 6: if len (sys.argv) < 7:
print (f'Usage: {prog} <disk> <partition> <image_name> <repo_ip> <protocol> [protocol_options] [additional_args...]') print (f'Usage: {prog} <disk> <partition> <image_name> <repo_ip> <protocol> <protocol_options> [additional_args...]')
sys.exit (1) sys.exit (1)
disk, par, imgname, repo, proto, *extra = sys.argv[1:] disk, par, imgname, repo, proto, protoopt, *extra = sys.argv[1:]
rc = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/deployImage.py', repo, imgname, disk, par, proto] + extra).returncode rc = subprocess.run ([f'{ogGlobals.OGSCRIPTS}/deployImage.py', repo, imgname, disk, par, proto, protoopt] + extra).returncode
sys.exit (rc) sys.exit (rc)

View File

@ -1,65 +0,0 @@
#!/usr/bin/env python3
import sys
import resource
import logging
import NetLib
import ogGlobals
import SystemLib
import DiskLib
from GitLib import OpengnsysGitLibrary, NTFSImplementation, OgProgressPrinterWeb
if __name__ == "__main__":
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
# Usamos el mínimo entre 65536 y el límite hard disponible
new_limit = min(65536, hard)
resource.setrlimit(resource.RLIMIT_NOFILE, (new_limit, hard))
print(f"RLIMIT_NOFILE establecido a: {resource.getrlimit(resource.RLIMIT_NOFILE)}")
except ValueError as e:
print(f"No se pudo aumentar el límite de archivos abiertos: {e}")
if len(sys.argv) < 6:
print("Usage: python RestaurarImagenGit.py <disk> <partition> <repo> <ip> <ref> <protocol>")
sys.exit(1)
disk = sys.argv[1]
partition = sys.argv[2]
repo = sys.argv[3]
ipaddr = sys.argv[4]
gitref = sys.argv[5]
proto = sys.argv[6]
opengnsys_log_dir = "/opt/opengnsys/log"
ip_address = NetLib.ogGetIpAddress()
logFilePath = f"{opengnsys_log_dir}/{ip_address}.log"
fileLog = logging.FileHandler(logFilePath)
fileLog.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)24s - [%(levelname)5s] - %(message)s')
fileLog.setFormatter(formatter)
logger = logging.getLogger(__package__)
logger.setLevel(logging.DEBUG)
logger.addHandler(fileLog)
logger.info("Starting RestaurarImagenGit")
ntfs_impl = NTFSImplementation.NTFS3G
og_git = OpengnsysGitLibrary(ntfs_implementation = ntfs_impl)
og_git.progress_callback = OgProgressPrinterWeb()
device = DiskLib.ogDiskToDev(disk, partition)
og_git.cloneRepo(repo, device, device)
logger.info("RestaurarImagenGit Finished.")

View File

@ -0,0 +1,88 @@
#!/bin/bash
#_______________________________________________________________________________________________________________________________
#
# Formato de salida:
# disk=Número de disco\tpar=Número de particion\tcod=Código de partición\tsfi=Sistema de ficheros\tsoi=Sistema instalado\ttam=Tamaño de la partición\n
#_______________________________________________________________________________________________________________________________
# No registrar los errores.
export DEBUG="no"
ser=$(ogGetSerialNumber)
cfg=""
disks=$(ogDiskToDev | wc -w)
for ((dsk=1; dsk<=$disks; dsk++)); do
particiones=$(ogGetPartitionsNumber $dsk)
particiones=${particiones:-0}
# Tipo de tabla de particiones: 1=MSDOS, 2=GPT
ptt=$(ogGetPartitionTableType $dsk)
case "$ptt" in
MSDOS) ptt=1 ;;
GPT) ptt=2 ;;
LVM) ptt=3 ;;
ZPOOL) ptt=4 ;;
*) ptt=0 ;;
esac
# Información de disco (partición 0)
cfg="$cfg$dsk:0:$ptt:::$(ogGetDiskSize $dsk):0;"
for ((par=1;par<=$particiones;par++)); do
# Código del identificador de tipo de partición
cod=$(ogGetPartitionId $dsk $par 2>/dev/null)
# Tipo del sistema de ficheros
fsi=$(getFsType $dsk $par 2>/dev/null)
fsi=${fsi:-"EMPTY"}
# Tamaño de la particón
tam=$(ogGetPartitionSize $dsk $par 2>/dev/null)
tam=${tam:-"0"}
# Sistema operativo instalado
case "$fsi" in
""|EMPTY|LINUX-SWAP|LINUX-LVM|ZVOL)
soi=""; uso=0 ;;
*) if [ -n "$(ogMount $dsk $par 2>/dev/null)" ]; then
soi=$(getOsVersion $dsk $par 2>/dev/null | cut -f2 -d:)
# Hacer un 2º intento para algunos casos especiales.
[ -z "$soi" ] && soi=$(getOsVersion $dsk $par 2>/dev/null | cut -f2 -d:)
# Sistema de archivos para datos (sistema operativo "DATA")
[ -z "$soi" -a "$fsi" != "EMPTY" -a "$fsi" != "CACHE" ] && soi="DATA"
# Obtener porcentaje de uso.
uso=$(df $(ogGetMountPoint $dsk $par) | awk '{getline; printf "%d",$5}')
uso=${uso:0}
else
soi=""; uso=0
fi
;;
esac
cfg="$cfg$dsk:$par:$cod:$fsi:$soi:$tam:$uso;"
done
done
# Crear configuración por defecto para cliente sin disco.
[ -z "$cfg" ] && cfg="1:0:0:::0;"
# Guardar salida en fichero temporal.
cfgfile=/tmp/getconfig
echo "${ser:+$ser;}$cfg" > $cfgfile
# Crear el menú por defecto a partir del fichero generado (no dar ninguna salida).
generateMenuDefault &>/dev/null
# Componer salida formateada.
awk '{ n=split($0,sep,";");
for (i=1; i<n; i++){
c=split (sep[i],dua,":");
if (i==1 && c==1)
printf ("ser=%s\n", dua[1]);
else
printf ("disk=%s\tpar=%s\tcpt=%s\tfsi=%s\tsoi=%s\ttam=%s\tuso=%s\n",
dua[1],dua[2],dua[3],dua[4],dua[5],dua[6],dua[7]);
}
}' $cfgfile
# Borramos marcas de arranque de Windows
rm -f /mnt/*/ogboot.* /mnt/*/*/ogboot.*
# Volver a registrar los errores.
unset DEBUG

View File

@ -1,78 +1,80 @@
#!/usr/bin/python3 #!/usr/bin/env python3
import os import os
import glob
import subprocess import subprocess
from InventoryLib import ogGetSerialNumber, ogGetOsVersion, ogIsEfiActive def run_command(command):
from DiskLib import ogDiskToDev, ogGetPartitionsNumber, ogGetPartitionTableType, ogGetDiskSize, ogGetPartitionId, ogGetPartitionSize result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
from FileSystemLib import ogMount, ogGetMountPoint, ogGetFsType return result.stdout.decode().strip()
ser = ogGetSerialNumber() def main():
fwt = 'UEFI' if ogIsEfiActive() else 'BIOS' # No registrar los errores.
print (f'ser={ser}\nfwt={fwt}') os.environ["DEBUG"] = "no"
ser = run_command("ogGetSerialNumber")
cfg = ""
disks = int(run_command("ogDiskToDev | wc -w"))
disks = len (ogDiskToDev())
if disks:
for dsk in range(1, disks + 1): for dsk in range(1, disks + 1):
# Tipo de tabla de particiones: 1=MSDOS, 2=GPT particiones = run_command(f"ogGetPartitionsNumber {dsk}")
ptt = ogGetPartitionTableType (dsk) particiones = int(particiones) if particiones else 0
ptt = run_command(f"ogGetPartitionTableType {dsk}")
ptt_map = { ptt_map = {
'MSDOS': 1, "MSDOS": 1,
'GPT': 2, "GPT": 2,
'LVM': 3, "LVM": 3,
'ZPOOL': 4, "ZPOOL": 4
} }
ptt = ptt_map.get(ptt, 0) ptt = ptt_map.get(ptt, 0)
# Información de disco (partición 0) cfg += f"{dsk}:0:{ptt}:::{run_command(f'ogGetDiskSize {dsk}')}:0;"
s = ogGetDiskSize (dsk)
print (f'disk={dsk}\tpar=0\tcpt={ptt}\tfsi=\tsoi=\ttam={s}\tuso=0')
particiones = ogGetPartitionsNumber (dsk)
particiones = int (particiones) if particiones else 0
for par in range(1, particiones + 1): for par in range(1, particiones + 1):
# Código del identificador de tipo de partición cod = run_command(f"ogGetPartitionId {dsk} {par} 2>/dev/null")
cod = ogGetPartitionId (dsk, par) 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 if fsi not in ["", "EMPTY", "LINUX-SWAP", "LINUX-LVM", "ZVOL"]:
fsi = ogGetFsType (dsk, par) if run_command(f"ogMount {dsk} {par} 2>/dev/null"):
if not fsi: fsi = 'EMPTY' soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1]
# 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 not soi: if not soi:
soi = ogGetOsVersion (dsk, par) soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1]
if not soi: soi = '' if not soi and fsi not in ["EMPTY", "CACHE"]:
if soi: soi = soi.split (':')[1] soi = "DATA"
# Sistema de archivos para datos (sistema operativo "DATA") uso = int(run_command(f"df $(ogGetMountPoint {dsk} {par}) | awk '{{getline; printf \"%d\",$5}}'") or 0)
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'
else: else:
soi = '' soi = ""
uso = '0' uso = 0
print (f'disk={dsk}\tpar={par}\tcpt={cod}\tfsi={fsi}\tsoi={soi}\ttam={tam}\tuso={uso}') cfg += f"{dsk}:{par}:{cod}:{fsi}:{soi}:{tam}:{uso};"
if not cfg:
cfg = "1:0:0:::0;"
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: else:
print ('disk=1\tpar=0\tcpt=0\tfsi=\tsoi=\ttam=0\tuso=0') print(f"disk={parts[0]}\tpar={parts[1]}\tcpt={parts[2]}\tfsi={parts[3]}\tsoi={parts[4]}\ttam={parts[5]}\tuso={parts[6]}")
# Crear el menú por defecto a partir del fichero generado (no dar ninguna salida). run_command("rm -f /mnt/*/ogboot.* /mnt/*/*/ogboot.*")
# requiere /tmp/getconfig pero este script ya no lo crea
#subprocess.run ([f'{ogGlobals.OGSCRIPTS}/generateMenuDefault'])
# Borramos marcas de arranque de Windows # Volver a registrar los errores.
for f in glob.glob ('/mnt/*/ogboot.*') + glob.glob ('/mnt/*/*/ogboot.*'): os.environ.pop("DEBUG", None)
try: os.unlink (f)
except: pass if __name__ == "__main__":
main()

View File

@ -0,0 +1,2 @@
#!/bin/bash
getIpAddress

View File

@ -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())

View File

@ -0,0 +1,2 @@
#!/bin/bash
initCache $1

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

View File

@ -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" }
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -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" }
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 525 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 671 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 725 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 562 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 B

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