Compare commits
No commits in common. "main" and "misc-fixes" have entirely different histories.
main
...
misc-fixes
60
CHANGELOG.md
60
CHANGELOG.md
|
@ -5,66 +5,6 @@ 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.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
|
||||
|
|
|
@ -5,7 +5,7 @@ set -a
|
|||
source /opt/opengnsys/etc/preinit/loadenviron.sh
|
||||
|
||||
# Scripts de inicio.
|
||||
for f in cleanesp fileslinks loadmodules metadevs mountrepo poweroff filebeat otherservices; do
|
||||
for f in cleanesp fileslinks loadmodules metadevs mountrepo poweroff otherservices; do
|
||||
source $OGETC/preinit/$f.sh
|
||||
done
|
||||
unset f
|
||||
|
|
|
@ -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
|
|
@ -7,7 +7,10 @@
|
|||
#@date 2012-01-12
|
||||
#*/
|
||||
|
||||
# Montar efivar filesystem
|
||||
ogIsEfiActive && mount -t efivarfs none /sys/firmware/efi/efivars
|
||||
|
||||
# Lanzar servicios complementarios del cliente.
|
||||
echo "${MSG_OTHERSERVICES:-.}"
|
||||
|
||||
# stunnel start
|
||||
|
@ -54,7 +57,7 @@ mkdir -p /var/run/stunnel4; chown stunnel4:stunnel4 /var/run/stunnel4
|
|||
stunnel /etc/stunnel/menu.conf &>/var/log/stunnel4/menu.log &
|
||||
# stunnel end
|
||||
|
||||
# dbus
|
||||
# Iniciar 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)
|
||||
|
@ -62,16 +65,26 @@ if [ -e /etc/dbus-1/system.d/ogbrowser.conf ]; then
|
|||
dbus-monitor --system &>/var/log/dbus-monitor.log &
|
||||
fi
|
||||
|
||||
# Iniciar rsyslog, si es necesario.
|
||||
[ -S /dev/log ] || service rsyslog start
|
||||
|
||||
# root password
|
||||
PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
|
||||
# Adpatar la clave de "root" para acceso SSH.
|
||||
PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \
|
||||
sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
|
||||
PASS=${PASS:-"og"}
|
||||
echo -ne "$PASS\n$PASS\n" | passwd root 2>/dev/null
|
||||
|
||||
# Cargar el entorno OpenGnsys en conexión SSH.
|
||||
cp -a $OPENGNSYS/etc/preinit/loadenviron.sh /etc/profile.d/
|
||||
# Arrancar SSH.
|
||||
/etc/init.d/ssh start &>/dev/null
|
||||
|
||||
#setterm -blank 0 -powersave off -powerdown 0 < /dev/console > /dev/console 2>&1 ## apagado de monitor
|
||||
ethtool -s $DEVICE wol g 2>/dev/null ## Activado WOL en la interfaz usada en arranque PXE.
|
||||
# Desactivado apagado de monitor.
|
||||
#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
|
||||
|
||||
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
poweroff
|
||||
exit 0
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
chmod +x $1
|
||||
$1>$2 || exit $?
|
|
@ -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
|
||||
|
|
@ -1,78 +1,36 @@
|
|||
#!/usr/bin/env python3
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import resource
|
||||
import logging
|
||||
import time
|
||||
|
||||
|
||||
sys.path.insert(0, "/opt/oglive/rootfs/opt/opengnsys/lib/python3/")
|
||||
sys.path.insert(0, "/opt/opengnsys/interfaceAdm/git/")
|
||||
sys.path.insert(0, "/opt/opengnsys/ogrepository/oggit/lib/")
|
||||
|
||||
import NetLib
|
||||
import ogGlobals
|
||||
import SystemLib
|
||||
import DiskLib
|
||||
import NetLib
|
||||
|
||||
|
||||
from GitLib import OpengnsysGitLibrary, NTFSImplementation, OgProgressPrinterWeb
|
||||
from gitlib import OpengnsysGitLibrary, NTFSImplementation
|
||||
|
||||
|
||||
def create_image(disk_num, partition_num, repo, image_name, tagName):
|
||||
def create_image(disk_num, partition_num, repo, image_name):
|
||||
|
||||
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
|
||||
|
||||
device = og_git._runBashFunction("ogDiskToDev", [str(disk_num), str(partition_num)])
|
||||
og_git.initRepo(device, image_name)
|
||||
|
||||
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.
|
||||
|
||||
sys.exit(SystemLib.ogRaiseError(OG_ERR_FORMAT, "Incorrect number of arguments"))
|
||||
|
||||
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)
|
||||
|
||||
|
||||
retval = create_image(disk_num, partition_num, repo, image_name)
|
||||
|
||||
sys.exit(retval)
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
@ -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
|
|
@ -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
|
||||
|
|
@ -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"
|
||||
|
|
@ -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()
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
reboot
|
||||
exit 0
|
|
@ -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 $?
|
||||
|
|
@ -1,65 +1,32 @@
|
|||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import resource
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
|
||||
sys.path.insert(0, "/opt/oglive/rootfs/opt/opengnsys/lib/python3/")
|
||||
sys.path.insert(0, "/opt/opengnsys/interfaceAdm/git/")
|
||||
sys.path.insert(0, "/opt/opengnsys/ogrepository/oggit/lib/")
|
||||
|
||||
import NetLib
|
||||
import ogGlobals
|
||||
import SystemLib
|
||||
import DiskLib
|
||||
|
||||
from GitLib import OpengnsysGitLibrary, NTFSImplementation, OgProgressPrinterWeb
|
||||
from gitlib import OpengnsysGitLibrary, NTFSImplementation
|
||||
|
||||
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>")
|
||||
if len(sys.argv) < 4:
|
||||
print("Usage: python RestaurarImagenGit.py <disk> <partition> <repo> <boot_device>")
|
||||
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")
|
||||
|
||||
|
||||
|
||||
boot_device = sys.argv[4]
|
||||
|
||||
ntfs_impl = NTFSImplementation.NTFS3G
|
||||
og_git = OpengnsysGitLibrary(ntfs_implementation = ntfs_impl)
|
||||
og_git.progress_callback = OgProgressPrinterWeb()
|
||||
|
||||
device = DiskLib.ogDiskToDev(disk, partition)
|
||||
device = og_git._runBashFunction("ogDiskToDev", [str(disk), str(partition)])
|
||||
|
||||
og_git.cloneRepo(repo, device, device)
|
||||
|
||||
logger.info("RestaurarImagenGit Finished.")
|
||||
og_git.cloneRepo(repo, device, boot_device)
|
||||
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
#!/bin/bash
|
||||
getIpAddress
|
|
@ -0,0 +1,2 @@
|
|||
#!/bin/bash
|
||||
initCache $1
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
echo "Content-type: text/html"
|
||||
echo ""
|
||||
echo "<html><head><title>OpenGnsys Client $(/opt/opengnsys/functions/ogGetIpAddress)</title>"
|
||||
echo "<html><head><title>OpenGnsys Client</title>"
|
||||
echo " <meta charset='utf-8'>"
|
||||
echo "</head><body>"
|
||||
|
||||
|
|
|
@ -132,10 +132,7 @@ def ogBoot (disk, par, nvramperm=False, params=''):
|
|||
grub_cfg_src = f'{esp_mntdir}/EFI/{bootlabel}/Boot/grub.cfg'
|
||||
if not os.path.exists (grub_cfg_src):
|
||||
grub_cfg_src = f'{esp_mntdir}/boot/grubMBR/boot/grub/grub.cfg'
|
||||
if os.path.exists (grub_cfg_src):
|
||||
shutil.copy2 (grub_cfg_src, f'{esp_mntdir}/boot/grub/grub.cfg')
|
||||
else:
|
||||
print ('grub.cfg not found')
|
||||
shutil.copy2 (grub_cfg_src, f'{esp_mntdir}/boot/grub/grub.cfg')
|
||||
|
||||
# Crear orden de arranque (con unos valores por defecto).
|
||||
UEFILib.ogNvramAddEntry (bootlabel, f'/EFI/{bootlabel}/Boot/{bootloader}', nvramperm)
|
||||
|
@ -173,10 +170,7 @@ def ogBoot (disk, par, nvramperm=False, params=''):
|
|||
grub_cfg_src = f'{esp_mntdir}/EFI/{bootlabel}/Boot/grub.cfg'
|
||||
if not os.path.exists (grub_cfg_src):
|
||||
grub_cfg_src = f'{esp_mntdir}/boot/grubMBR/boot/grub/grub.cfg'
|
||||
if os.path.exists (grub_cfg_src):
|
||||
shutil.copy2 (grub_cfg_src, f'{esp_mntdir}/boot/grub/grub.cfg')
|
||||
else:
|
||||
print ('grub.cfg not found')
|
||||
shutil.copy2 (grub_cfg_src, f'{esp_mntdir}/boot/grub/grub.cfg')
|
||||
|
||||
# Crear orden de arranque (con unos valores por defecto).
|
||||
l = re.sub ('^.*EFI(.*)$', r'\1', loader)
|
||||
|
@ -195,12 +189,12 @@ def ogBoot (disk, par, nvramperm=False, params=''):
|
|||
winboot = os.environ.get ('winboot', '')
|
||||
if 'kexec' == winboot:
|
||||
# Modo de arranque en caliente (con kexec).
|
||||
cp_cmd = f'cp {ogGlobals.OGLIB}/grub4dos/* {mntdir}'
|
||||
subprocess.run (cp_cmd, shell=True)
|
||||
for f in glob.glob (f'{ogGlobals.OGLIB}/grub4dos/*'):
|
||||
shutil.copy2 (f, mntdir)
|
||||
disk0 = int(disk)-1
|
||||
par0 = int(par)-1
|
||||
subprocess.run (['kexec', '--load', f'{mntdir}/grub.exe', '--append=--config-file=root (hd{disk0},{par0}); chainloader (hd{disk0},{par0})/{loader}; tpm --init'])
|
||||
subprocess.Popen (['kexec', '--exec'])
|
||||
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'])
|
||||
|
|
|
@ -70,7 +70,7 @@ def ogCreateCache (ndsk=1, part=4, sizecache=0):
|
|||
MINSIZE = 25000
|
||||
MAXSIZE = END
|
||||
if SIZE < MINSIZE or SIZE > MAXSIZE or START < ENDPREVPART:
|
||||
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, f'size ({SIZE}) < minsize ({MINSIZE}) or size > maxsize ({MAXSIZE}) or start ({START}) < endprevpart ({ENDPREVPART})')
|
||||
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, ndsk)
|
||||
return None
|
||||
|
||||
# Desmontar todos los sistemas de archivos del disco.
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,345 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
import hivex
|
||||
import argparse
|
||||
import struct
|
||||
|
||||
from hivex import Hivex
|
||||
from hivex.hive_types import *
|
||||
|
||||
|
||||
# Docs:
|
||||
#
|
||||
# https://www.geoffchappell.com/notes/windows/boot/bcd/objects.htm
|
||||
# https://learn.microsoft.com/en-us/previous-versions/windows/desktop/bcd/bcdbootmgrelementtypes
|
||||
|
||||
#print(f"Root: {root}")
|
||||
|
||||
|
||||
BCD_Enumerations = {
|
||||
"BcdLibraryDevice_ApplicationDevice" : 0x11000001,
|
||||
"BcdLibraryString_ApplicationPath" : 0x12000002,
|
||||
"BcdLibraryString_Description" : 0x12000004,
|
||||
"BcdLibraryString_PreferredLocale" : 0x12000005,
|
||||
"BcdLibraryObjectList_InheritedObjects" : 0x14000006,
|
||||
"BcdLibraryInteger_TruncatePhysicalMemory" : 0x15000007,
|
||||
"BcdLibraryObjectList_RecoverySequence" : 0x14000008,
|
||||
"BcdLibraryBoolean_AutoRecoveryEnabled" : 0x16000009,
|
||||
"BcdLibraryIntegerList_BadMemoryList" : 0x1700000a,
|
||||
"BcdLibraryBoolean_AllowBadMemoryAccess" : 0x1600000b,
|
||||
"BcdLibraryInteger_FirstMegabytePolicy" : 0x1500000c,
|
||||
"BcdLibraryInteger_RelocatePhysicalMemory" : 0x1500000D,
|
||||
"BcdLibraryInteger_AvoidLowPhysicalMemory" : 0x1500000E,
|
||||
"BcdLibraryBoolean_DebuggerEnabled" : 0x16000010,
|
||||
"BcdLibraryInteger_DebuggerType" : 0x15000011,
|
||||
"BcdLibraryInteger_SerialDebuggerPortAddress" : 0x15000012,
|
||||
"BcdLibraryInteger_SerialDebuggerPort" : 0x15000013,
|
||||
"BcdLibraryInteger_SerialDebuggerBaudRate" : 0x15000014,
|
||||
"BcdLibraryInteger_1394DebuggerChannel" : 0x15000015,
|
||||
"BcdLibraryString_UsbDebuggerTargetName" : 0x12000016,
|
||||
"BcdLibraryBoolean_DebuggerIgnoreUsermodeExceptions" : 0x16000017,
|
||||
"BcdLibraryInteger_DebuggerStartPolicy" : 0x15000018,
|
||||
"BcdLibraryString_DebuggerBusParameters" : 0x12000019,
|
||||
"BcdLibraryInteger_DebuggerNetHostIP" : 0x1500001A,
|
||||
"BcdLibraryInteger_DebuggerNetPort" : 0x1500001B,
|
||||
"BcdLibraryBoolean_DebuggerNetDhcp" : 0x1600001C,
|
||||
"BcdLibraryString_DebuggerNetKey" : 0x1200001D,
|
||||
"BcdLibraryBoolean_EmsEnabled" : 0x16000020,
|
||||
"BcdLibraryInteger_EmsPort" : 0x15000022,
|
||||
"BcdLibraryInteger_EmsBaudRate" : 0x15000023,
|
||||
"BcdLibraryString_LoadOptionsString" : 0x12000030,
|
||||
"BcdLibraryBoolean_DisplayAdvancedOptions" : 0x16000040,
|
||||
"BcdLibraryBoolean_DisplayOptionsEdit" : 0x16000041,
|
||||
"BcdLibraryDevice_BsdLogDevice" : 0x11000043,
|
||||
"BcdLibraryString_BsdLogPath" : 0x12000044,
|
||||
"BcdLibraryBoolean_GraphicsModeDisabled" : 0x16000046,
|
||||
"BcdLibraryInteger_ConfigAccessPolicy" : 0x15000047,
|
||||
"BcdLibraryBoolean_DisableIntegrityChecks" : 0x16000048,
|
||||
"BcdLibraryBoolean_AllowPrereleaseSignatures" : 0x16000049,
|
||||
"BcdLibraryString_FontPath" : 0x1200004A,
|
||||
"BcdLibraryInteger_SiPolicy" : 0x1500004B,
|
||||
"BcdLibraryInteger_FveBandId" : 0x1500004C,
|
||||
"BcdLibraryBoolean_ConsoleExtendedInput" : 0x16000050,
|
||||
"BcdLibraryInteger_GraphicsResolution" : 0x15000052,
|
||||
"BcdLibraryBoolean_RestartOnFailure" : 0x16000053,
|
||||
"BcdLibraryBoolean_GraphicsForceHighestMode" : 0x16000054,
|
||||
"BcdLibraryBoolean_IsolatedExecutionContext" : 0x16000060,
|
||||
"BcdLibraryBoolean_BootUxDisable" : 0x1600006C,
|
||||
"BcdLibraryBoolean_BootShutdownDisabled" : 0x16000074,
|
||||
"BcdLibraryIntegerList_AllowedInMemorySettings" : 0x17000077,
|
||||
"BcdLibraryBoolean_ForceFipsCrypto" : 0x16000079,
|
||||
|
||||
|
||||
"BcdBootMgrObjectList_DisplayOrder" : 0x24000001,
|
||||
"BcdBootMgrObjectList_BootSequence" : 0x24000002,
|
||||
"BcdBootMgrObject_DefaultObject" : 0x23000003,
|
||||
"BcdBootMgrInteger_Timeout" : 0x25000004,
|
||||
"BcdBootMgrBoolean_AttemptResume" : 0x26000005,
|
||||
"BcdBootMgrObject_ResumeObject" : 0x23000006,
|
||||
"BcdBootMgrObjectList_ToolsDisplayOrder" : 0x24000010,
|
||||
"BcdBootMgrBoolean_DisplayBootMenu" : 0x26000020,
|
||||
"BcdBootMgrBoolean_NoErrorDisplay" : 0x26000021,
|
||||
"BcdBootMgrDevice_BcdDevice" : 0x21000022,
|
||||
"BcdBootMgrString_BcdFilePath" : 0x22000023,
|
||||
"BcdBootMgrBoolean_ProcessCustomActionsFirst" : 0x26000028,
|
||||
"BcdBootMgrIntegerList_CustomActionsList" : 0x27000030,
|
||||
"BcdBootMgrBoolean_PersistBootSequence" : 0x26000031,
|
||||
|
||||
"BcdDeviceInteger_RamdiskImageOffset" : 0x35000001,
|
||||
"BcdDeviceInteger_TftpClientPort" : 0x35000002,
|
||||
"BcdDeviceInteger_SdiDevice" : 0x31000003,
|
||||
"BcdDeviceInteger_SdiPath" : 0x32000004,
|
||||
"BcdDeviceInteger_RamdiskImageLength" : 0x35000005,
|
||||
"BcdDeviceBoolean_RamdiskExportAsCd" : 0x36000006,
|
||||
"BcdDeviceInteger_RamdiskTftpBlockSize" : 0x36000007,
|
||||
"BcdDeviceInteger_RamdiskTftpWindowSize" : 0x36000008,
|
||||
"BcdDeviceBoolean_RamdiskMulticastEnabled" : 0x36000009,
|
||||
"BcdDeviceBoolean_RamdiskMulticastTftpFallback" : 0x3600000A,
|
||||
"BcdDeviceBoolean_RamdiskTftpVarWindow" : 0x3600000B,
|
||||
|
||||
"BcdMemDiagInteger_PassCount" : 0x25000001,
|
||||
"BcdMemDiagInteger_FailureCount" : 0x25000003,
|
||||
|
||||
"Reserved1" : 0x21000001,
|
||||
"Reserved2" : 0x22000002,
|
||||
"BcdResumeBoolean_UseCustomSettings" : 0x26000003,
|
||||
"BcdResumeDevice_AssociatedOsDevice" : 0x21000005,
|
||||
"BcdResumeBoolean_DebugOptionEnabled" : 0x26000006,
|
||||
"BcdResumeInteger_BootMenuPolicy" : 0x25000008,
|
||||
|
||||
"BcdOSLoaderDevice_OSDevice" : 0x21000001,
|
||||
"BcdOSLoaderString_SystemRoot" : 0x22000002,
|
||||
"BcdOSLoaderObject_AssociatedResumeObject" : 0x23000003,
|
||||
"BcdOSLoaderBoolean_DetectKernelAndHal" : 0x26000010,
|
||||
"BcdOSLoaderString_KernelPath" : 0x22000011,
|
||||
"BcdOSLoaderString_HalPath" : 0x22000012,
|
||||
"BcdOSLoaderString_DbgTransportPath" : 0x22000013,
|
||||
"BcdOSLoaderInteger_NxPolicy" : 0x25000020,
|
||||
"BcdOSLoaderInteger_PAEPolicy" : 0x25000021,
|
||||
"BcdOSLoaderBoolean_WinPEMode" : 0x26000022,
|
||||
"BcdOSLoaderBoolean_DisableCrashAutoReboot" : 0x26000024,
|
||||
"BcdOSLoaderBoolean_UseLastGoodSettings" : 0x26000025,
|
||||
"BcdOSLoaderBoolean_AllowPrereleaseSignatures" : 0x26000027,
|
||||
"BcdOSLoaderBoolean_NoLowMemory" : 0x26000030,
|
||||
"BcdOSLoaderInteger_RemoveMemory" : 0x25000031,
|
||||
"BcdOSLoaderInteger_IncreaseUserVa" : 0x25000032,
|
||||
"BcdOSLoaderBoolean_UseVgaDriver" : 0x26000040,
|
||||
"BcdOSLoaderBoolean_DisableBootDisplay" : 0x26000041,
|
||||
"BcdOSLoaderBoolean_DisableVesaBios" : 0x26000042,
|
||||
"BcdOSLoaderBoolean_DisableVgaMode" : 0x26000043,
|
||||
"BcdOSLoaderInteger_ClusterModeAddressing" : 0x25000050,
|
||||
"BcdOSLoaderBoolean_UsePhysicalDestination" : 0x26000051,
|
||||
"BcdOSLoaderInteger_RestrictApicCluster" : 0x25000052,
|
||||
"BcdOSLoaderBoolean_UseLegacyApicMode" : 0x26000054,
|
||||
"BcdOSLoaderInteger_X2ApicPolicy" : 0x25000055,
|
||||
"BcdOSLoaderBoolean_UseBootProcessorOnly" : 0x26000060,
|
||||
"BcdOSLoaderInteger_NumberOfProcessors" : 0x25000061,
|
||||
"BcdOSLoaderBoolean_ForceMaximumProcessors" : 0x26000062,
|
||||
"BcdOSLoaderBoolean_ProcessorConfigurationFlags" : 0x25000063,
|
||||
"BcdOSLoaderBoolean_MaximizeGroupsCreated" : 0x26000064,
|
||||
"BcdOSLoaderBoolean_ForceGroupAwareness" : 0x26000065,
|
||||
"BcdOSLoaderInteger_GroupSize" : 0x25000066,
|
||||
"BcdOSLoaderInteger_UseFirmwarePciSettings" : 0x26000070,
|
||||
"BcdOSLoaderInteger_MsiPolicy" : 0x25000071,
|
||||
"BcdOSLoaderInteger_SafeBoot" : 0x25000080,
|
||||
"BcdOSLoaderBoolean_SafeBootAlternateShell" : 0x26000081,
|
||||
"BcdOSLoaderBoolean_BootLogInitialization" : 0x26000090,
|
||||
"BcdOSLoaderBoolean_VerboseObjectLoadMode" : 0x26000091,
|
||||
"BcdOSLoaderBoolean_KernelDebuggerEnabled" : 0x260000a0,
|
||||
"BcdOSLoaderBoolean_DebuggerHalBreakpoint" : 0x260000a1,
|
||||
"BcdOSLoaderBoolean_UsePlatformClock" : 0x260000A2,
|
||||
"BcdOSLoaderBoolean_ForceLegacyPlatform" : 0x260000A3,
|
||||
"BcdOSLoaderInteger_TscSyncPolicy" : 0x250000A6,
|
||||
"BcdOSLoaderBoolean_EmsEnabled" : 0x260000b0,
|
||||
"BcdOSLoaderInteger_DriverLoadFailurePolicy" : 0x250000c1,
|
||||
"BcdOSLoaderInteger_BootMenuPolicy" : 0x250000C2,
|
||||
"BcdOSLoaderBoolean_AdvancedOptionsOneTime" : 0x260000C3,
|
||||
"BcdOSLoaderInteger_BootStatusPolicy" : 0x250000E0,
|
||||
"BcdOSLoaderBoolean_DisableElamDrivers" : 0x260000E1,
|
||||
"BcdOSLoaderInteger_HypervisorLaunchType" : 0x250000F0,
|
||||
"BcdOSLoaderBoolean_HypervisorDebuggerEnabled" : 0x260000F2,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerType" : 0x250000F3,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerPortNumber" : 0x250000F4,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerBaudrate" : 0x250000F5,
|
||||
"BcdOSLoaderInteger_HypervisorDebugger1394Channel" : 0x250000F6,
|
||||
"BcdOSLoaderInteger_BootUxPolicy" : 0x250000F7,
|
||||
"BcdOSLoaderString_HypervisorDebuggerBusParams" : 0x220000F9,
|
||||
"BcdOSLoaderInteger_HypervisorNumProc" : 0x250000FA,
|
||||
"BcdOSLoaderInteger_HypervisorRootProcPerNode" : 0x250000FB,
|
||||
"BcdOSLoaderBoolean_HypervisorUseLargeVTlb" : 0x260000FC,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerNetHostIp" : 0x250000FD,
|
||||
"BcdOSLoaderInteger_HypervisorDebuggerNetHostPort" : 0x250000FE,
|
||||
"BcdOSLoaderInteger_TpmBootEntropyPolicy" : 0x25000100,
|
||||
"BcdOSLoaderString_HypervisorDebuggerNetKey" : 0x22000110,
|
||||
"BcdOSLoaderBoolean_HypervisorDebuggerNetDhcp" : 0x26000114,
|
||||
"BcdOSLoaderInteger_HypervisorIommuPolicy" : 0x25000115,
|
||||
"BcdOSLoaderInteger_XSaveDisable" : 0x2500012b
|
||||
}
|
||||
|
||||
|
||||
def format_value(bcd, bcd_value):
|
||||
|
||||
name = bcd.value_key(bcd_value)
|
||||
(type, length) = bcd.value_type(bcd_value)
|
||||
|
||||
typename = ""
|
||||
str_value = ""
|
||||
if type == REG_SZ:
|
||||
typename = "SZ"
|
||||
str_value = bcd.value_string(bcd_value)
|
||||
elif type == REG_DWORD:
|
||||
typename = "DWORD"
|
||||
dval = bcd.value_dword(bcd_value)
|
||||
|
||||
str_value = hex(dval) + " (" + str(bcd.value_dword(bcd_value)) + ")"
|
||||
elif type == REG_BINARY:
|
||||
typename = "BIN"
|
||||
(length, value) = bcd.value_value(bcd_value)
|
||||
str_value = value.hex()
|
||||
elif type == REG_DWORD_BIG_ENDIAN:
|
||||
typename = "DWORD_BE"
|
||||
elif type == REG_EXPAND_SZ:
|
||||
typename = "EXPAND SZ"
|
||||
elif type == REG_FULL_RESOURCE_DESCRIPTOR:
|
||||
typename = "RES DESC"
|
||||
elif type == REG_LINK:
|
||||
typename = "LINK"
|
||||
elif type == REG_MULTI_SZ:
|
||||
typename = "MULTISZ"
|
||||
(length, str_value) = bcd.value_value(bcd_value)
|
||||
str_value = str_value.decode('utf-16le')
|
||||
str_value = str_value.replace("\0", ";")
|
||||
#value = ";".join("\0".split(value))
|
||||
elif type == REG_NONE:
|
||||
typename = "NONE"
|
||||
elif type == REG_QWORD:
|
||||
typename = "QWORD"
|
||||
elif type == REG_RESOURCE_LIST:
|
||||
typename = "RES LIST"
|
||||
elif type == REG_RESOURCE_REQUIREMENTS_LIST:
|
||||
typename = "REQ LIST"
|
||||
else:
|
||||
typename = str(type)
|
||||
str_value = "???"
|
||||
|
||||
|
||||
return (typename, length, str_value)
|
||||
|
||||
def dump_all(root, depth = 0):
|
||||
|
||||
padding = "\t" * depth
|
||||
|
||||
children = bcd.node_children(root)
|
||||
|
||||
if len(children) > 0:
|
||||
|
||||
for child in children:
|
||||
name = bcd.node_name(child)
|
||||
print(f"{padding}{name}")
|
||||
|
||||
dump_all(child, depth + 1)
|
||||
# print(f"Child: {child}")
|
||||
|
||||
#print(f"Values: {num_vals}")
|
||||
return
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
values = bcd.node_values(root)
|
||||
#print(f"Value list: {values}")
|
||||
|
||||
for v in values:
|
||||
(type_name, length, str_value) = format_value(bcd, v)
|
||||
name = bcd.value_key(v)
|
||||
|
||||
print(f"{padding}{name: <16}: [{type_name: <10}]; ({length: < 4}) {str_value}")
|
||||
|
||||
|
||||
class WindowsBCD:
|
||||
def __init__(self, filename):
|
||||
self.filename = filename
|
||||
self.bcd = Hivex(filename)
|
||||
|
||||
def dump(self, root=None, depth = 0):
|
||||
padding = "\t" * depth
|
||||
|
||||
if root is None:
|
||||
root = self.bcd.root()
|
||||
|
||||
children = self.bcd.node_children(root)
|
||||
|
||||
if len(children) > 0:
|
||||
for child in children:
|
||||
name = self.bcd.node_name(child)
|
||||
print(f"{padding}{name}")
|
||||
|
||||
self.dump(child, depth + 1)
|
||||
return
|
||||
|
||||
values = self.bcd.node_values(root)
|
||||
|
||||
for v in values:
|
||||
(type_name, length, str_value) = format_value(self.bcd, v)
|
||||
name = self.bcd.value_key(v)
|
||||
|
||||
print(f"{padding}{name: <16}: [{type_name: <10}]; ({length: < 4}) {str_value}")
|
||||
|
||||
def list(self):
|
||||
root = self.bcd.root()
|
||||
objects = self.bcd.node_get_child(root, "Objects")
|
||||
|
||||
for child in self.bcd.node_children(objects):
|
||||
entry_id = self.bcd.node_name(child)
|
||||
|
||||
elements = self.bcd.node_get_child(child, "Elements")
|
||||
description_entry = self.bcd.node_get_child(elements, "12000004")
|
||||
|
||||
if description_entry:
|
||||
values = self.bcd.node_values(description_entry)
|
||||
if values:
|
||||
(type_name, length, str_value) = format_value(self.bcd, values[0])
|
||||
print(f"{entry_id}: {str_value}")
|
||||
else:
|
||||
print(f"{entry_id}: [no description value!?]")
|
||||
|
||||
|
||||
appdevice_entry = self.bcd.node_get_child(elements, "11000001")
|
||||
|
||||
if appdevice_entry:
|
||||
values = self.bcd.node_values(appdevice_entry)
|
||||
(length, data) = self.bcd.value_value(values[0])
|
||||
hex = data.hex()
|
||||
print(f"LEN: {length}, HEX: {hex}, RAW: {data}")
|
||||
if len(data) > 10:
|
||||
etype = struct.unpack_from('<I', data, offset = 16)
|
||||
print(f"Type: {etype}")
|
||||
|
||||
|
||||
|
||||
else:
|
||||
print(f"{entry_id}: [no description entry 12000004]")
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="Windows BCD parser",
|
||||
description="Parses the BCD",
|
||||
)
|
||||
|
||||
parser.add_argument("--db", type=str, metavar='BCD file', help="Database to use")
|
||||
parser.add_argument("--dump", action='store_true', help="Dumps the specified database")
|
||||
parser.add_argument("--list", action='store_true', help="Lists boot entries in the specified database")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
bcdobj = WindowsBCD(args.db)
|
||||
|
||||
if args.dump:
|
||||
# "/home/vadim/opengnsys/winboot/boot-copy/EFI/Microsoft/Boot/BCD"
|
||||
#bcd = Hivex(args.dump)
|
||||
|
||||
#root = bcd.root()
|
||||
#dump_all(root)
|
||||
bcdobj.dump()
|
||||
elif args.list:
|
||||
bcdobj.list()
|
|
@ -1,121 +0,0 @@
|
|||
|
||||
import logging
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
# pylint: disable=locally-disabled, line-too-long, logging-fstring-interpolation, too-many-lines
|
||||
|
||||
|
||||
class DiskLibrary:
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("OpengnsysDiskLibrary")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
def split_device_partition(self, device):
|
||||
"""
|
||||
Parses a device file like /dev/sda3 into the root device (/dev/sda) and partition number (3)
|
||||
|
||||
Args:
|
||||
device (str): Device in /dev
|
||||
|
||||
Returns:
|
||||
[base_device, partno]
|
||||
"""
|
||||
|
||||
r = re.compile("^(.*?)(\\d+)$")
|
||||
m = r.match(device)
|
||||
disk = m.group(1)
|
||||
partno = int(m.group(2))
|
||||
|
||||
self.logger.debug(f"{device} parsed into disk device {disk}, partition {partno}")
|
||||
return (disk, partno)
|
||||
|
||||
def get_disk_json_data(self, device):
|
||||
"""
|
||||
Returns the partition JSON data dump for the entire disk, even if a partition is passed.
|
||||
|
||||
This is specifically in the format used by sfdisk.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: JSON dump produced by sfdisk
|
||||
"""
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--json", disk], check=True, capture_output=True, encoding='utf-8')
|
||||
return result.stdout.strip()
|
||||
|
||||
def get_disk_uuid(self, device):
|
||||
"""
|
||||
Returns the UUID of the disk itself, if there's a GPT partition table.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: UUID
|
||||
"""
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--disk-id", disk], check=True, capture_output=True, encoding='utf-8')
|
||||
return result.stdout.strip()
|
||||
|
||||
def set_disk_uuid(self, device, uuid):
|
||||
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
subprocess.run(["/usr/sbin/sfdisk", "--disk-id", disk, uuid], check=True, encoding='utf-8')
|
||||
|
||||
|
||||
def get_partition_uuid(self, device):
|
||||
"""
|
||||
Returns the UUID of the partition, if there's a GPT partition table.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: UUID
|
||||
"""
|
||||
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--part-uuid", disk, str(partno)], check=False, capture_output=True, encoding='utf-8')
|
||||
if result.returncode != 0:
|
||||
# We're using a DOS partition table, no UUID.
|
||||
if "failed to get partition UUID" in result.stderr:
|
||||
return ""
|
||||
raise subprocess.CalledProcessError(result.returncode, result.args)
|
||||
|
||||
return result.stdout.strip()
|
||||
|
||||
def set_partition_uuid(self, device, uuid):
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
subprocess.run(["/usr/sbin/sfdisk", "--part-uuid", disk, str(partno), uuid], check=True, encoding='utf-8')
|
||||
|
||||
def get_partition_type(self, device):
|
||||
"""
|
||||
Returns the type UUID of the partition, if there's a GPT partition table.
|
||||
|
||||
Args:
|
||||
device (str): Block device, eg, /dev/sda3
|
||||
|
||||
Returns:
|
||||
str: UUID
|
||||
"""
|
||||
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
result = subprocess.run(["/usr/sbin/sfdisk", "--part-type", disk, str(partno)], check=True, capture_output=True, encoding='utf-8')
|
||||
return result.stdout.strip()
|
||||
|
||||
def set_partition_type(self, device, uuid):
|
||||
(disk, partno) = self.split_device_partition(device)
|
||||
|
||||
subprocess.run(["/usr/sbin/sfdisk", "--part-type", disk, str(partno), uuid], check=True, encoding='utf-8')
|
||||
|
||||
|
||||
|
|
@ -1,544 +0,0 @@
|
|||
|
||||
import logging
|
||||
import subprocess
|
||||
import os
|
||||
import json
|
||||
import blkid
|
||||
import time
|
||||
|
||||
from GitLib.ntfs import *
|
||||
|
||||
|
||||
|
||||
# pylint: disable=locally-disabled, line-too-long, logging-fstring-interpolation, too-many-lines
|
||||
|
||||
|
||||
class FilesystemLibrary:
|
||||
def __init__(self, ntfs_implementation = NTFSImplementation.KERNEL):
|
||||
self.logger = logging.getLogger("OpengnsysFilesystemLibrary")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
self.mounts = {}
|
||||
self.base_mount_path = "/mnt"
|
||||
self.ntfs_implementation = ntfs_implementation
|
||||
|
||||
self.update_mounts()
|
||||
|
||||
def _rmmod(self, module):
|
||||
self.logger.debug("Trying to unload module {module}...")
|
||||
subprocess.run(["/usr/sbin/rmmod", module], check=False)
|
||||
|
||||
def _modprobe(self, module):
|
||||
self.logger.debug("Trying to load module {module}...")
|
||||
subprocess.run(["/usr/sbin/modprobe", module], check=True)
|
||||
|
||||
|
||||
# _parse_mounts
|
||||
def update_mounts(self):
|
||||
"""
|
||||
Update the current mount points by parsing the /proc/mounts file.
|
||||
|
||||
This method reads the /proc/mounts file to gather information about
|
||||
the currently mounted filesystems. It stores this information in a
|
||||
dictionary where the keys are the mount points and the values are
|
||||
dictionaries containing details about each filesystem.
|
||||
|
||||
The details stored for each filesystem include:
|
||||
- device: The device file associated with the filesystem.
|
||||
- mountpoint: The directory where the filesystem is mounted.
|
||||
- type: The type of the filesystem (e.g., ext4, vfat).
|
||||
- options: Mount options associated with the filesystem.
|
||||
- dump_freq: The dump frequency for the filesystem.
|
||||
- passno: The pass number for filesystem checks.
|
||||
|
||||
The method also adds an entry for each mount point with a trailing
|
||||
slash to ensure consistency in accessing the mount points.
|
||||
|
||||
Attributes:
|
||||
mounts (dict): A dictionary where keys are mount points and values
|
||||
are dictionaries containing filesystem details.
|
||||
"""
|
||||
filesystems = {}
|
||||
|
||||
self.logger.debug("Parsing /proc/mounts")
|
||||
|
||||
with open("/proc/mounts", 'r', encoding='utf-8') as mounts:
|
||||
for line in mounts:
|
||||
parts = line.split()
|
||||
data = {}
|
||||
data['device'] = parts[0]
|
||||
data['mountpoint'] = parts[1]
|
||||
data['type'] = parts[2]
|
||||
data['options'] = parts[3]
|
||||
data['dump_freq'] = parts[4]
|
||||
data['passno'] = parts[5]
|
||||
|
||||
filesystems[data["mountpoint"]] = data
|
||||
filesystems[data["mountpoint"] + "/"] = data
|
||||
|
||||
self.mounts = filesystems
|
||||
|
||||
def find_mountpoint(self, device):
|
||||
"""
|
||||
Find the mount point for a given device.
|
||||
|
||||
This method checks if the specified device is currently mounted and returns
|
||||
the corresponding mount point if it is found.
|
||||
|
||||
Args:
|
||||
device (str): The path to the device to check.
|
||||
|
||||
Returns:
|
||||
str or None: The mount point of the device if it is mounted, otherwise None.
|
||||
"""
|
||||
norm = os.path.normpath(device)
|
||||
|
||||
self.logger.debug(f"Checking if {device} is mounted")
|
||||
for mountpoint, mount in self.mounts.items():
|
||||
#self.logger.debug(f"Item: {mount}")
|
||||
#self.logger.debug(f"Checking: " + mount['device'])
|
||||
if mount['device'] == norm:
|
||||
return mountpoint
|
||||
|
||||
return None
|
||||
|
||||
def find_device(self, mountpoint):
|
||||
"""
|
||||
Find the device corresponding to a given mount point.
|
||||
|
||||
Args:
|
||||
mountpoint (str): The mount point to search for.
|
||||
|
||||
Returns:
|
||||
str or None: The device corresponding to the mount point if found,
|
||||
otherwise None.
|
||||
"""
|
||||
self.update_mounts()
|
||||
self.logger.debug("Finding device corresponding to mount point %s", mountpoint)
|
||||
if mountpoint in self.mounts:
|
||||
return self.mounts[mountpoint]['device']
|
||||
else:
|
||||
self.logger.warning("Failed to find mountpoint %s", mountpoint)
|
||||
return None
|
||||
|
||||
def is_mounted(self, device = None, mountpoint = None):
|
||||
def is_mounted(self, device=None, mountpoint=None):
|
||||
"""
|
||||
Check if a device or mountpoint is currently mounted.
|
||||
|
||||
Either checking by device or mountpoint is valid.
|
||||
|
||||
Args:
|
||||
device (str, optional): The device to check if it is mounted.
|
||||
Defaults to None.
|
||||
mountpoint (str, optional): The mountpoint to check if it is mounted.
|
||||
Defaults to None.
|
||||
|
||||
Returns:
|
||||
bool: True if the device is mounted or the mountpoint is in the list
|
||||
of mounts, False otherwise.
|
||||
"""
|
||||
self.update_mounts()
|
||||
if device:
|
||||
return not self.find_mountpoint(device) is None
|
||||
else:
|
||||
return mountpoint in self.mounts
|
||||
|
||||
def unmount(self, device = None, mountpoint = None):
|
||||
def unmount(self, device=None, mountpoint=None):
|
||||
"""
|
||||
Unmounts a filesystem.
|
||||
|
||||
This method unmounts a filesystem either by the device name or the mountpoint.
|
||||
If a device is provided, it finds the corresponding mountpoint and unmounts it.
|
||||
If a mountpoint is provided directly, it unmounts the filesystem at that mountpoint.
|
||||
|
||||
Args:
|
||||
device (str, optional): The device name to unmount. Defaults to None.
|
||||
mountpoint (str, optional): The mountpoint to unmount. Defaults to None.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: If the unmount command fails.
|
||||
|
||||
Logs:
|
||||
Debug information about the unmounting process.
|
||||
"""
|
||||
if device:
|
||||
self.logger.debug("Finding mountpoint of %s", device)
|
||||
mountpoint = self.find_mountpoint(device)
|
||||
|
||||
if not mountpoint is None:
|
||||
self.logger.debug(f"Unmounting {mountpoint}")
|
||||
|
||||
done = False
|
||||
start_time = time.time()
|
||||
timeout = 60*15
|
||||
|
||||
|
||||
while not done and (time.time() - start_time) < timeout:
|
||||
ret = subprocess.run(["/usr/bin/umount", mountpoint], check=False, capture_output=True, encoding='utf-8')
|
||||
if ret.returncode == 0:
|
||||
done=True
|
||||
else:
|
||||
if "target is busy" in ret.stderr:
|
||||
self.logger.debug("Filesystem busy, waiting. %.1f seconds left", timeout - (time.time() - start_time))
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
raise subprocess.CalledProcessError(ret.returncode, ret.args, output=ret.stdout, stderr=ret.stderr)
|
||||
|
||||
# We've unmounted a new filesystem, update our filesystems list
|
||||
self.update_mounts()
|
||||
else:
|
||||
self.logger.debug(f"{device} is not mounted")
|
||||
|
||||
|
||||
def mount(self, device, mountpoint, filesystem = None):
|
||||
"""
|
||||
Mounts a device to a specified mountpoint.
|
||||
|
||||
Parameters:
|
||||
device (str): The device to be mounted (e.g., '/dev/sda1').
|
||||
mountpoint (str): The directory where the device will be mounted.
|
||||
filesystem (str, optional): The type of filesystem to be used (e.g., 'ext4', 'ntfs'). Defaults to None.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: If the mount command fails.
|
||||
|
||||
Logs:
|
||||
Debug information about the mounting process, including the mount command, return code, stdout, and stderr.
|
||||
|
||||
Side Effects:
|
||||
Creates the mountpoint directory if it does not exist.
|
||||
Updates the internal list of mounted filesystems.
|
||||
"""
|
||||
self.logger.debug(f"Mounting {device} at {mountpoint}")
|
||||
|
||||
if not os.path.exists(mountpoint):
|
||||
self.logger.debug(f"Creating directory {mountpoint}")
|
||||
os.mkdir(mountpoint)
|
||||
|
||||
mount_cmd = ["/usr/bin/mount"]
|
||||
|
||||
if not filesystem is None:
|
||||
mount_cmd = mount_cmd + ["-t", filesystem]
|
||||
|
||||
mount_cmd = mount_cmd + [device, mountpoint]
|
||||
|
||||
self.logger.debug(f"Mount command: {mount_cmd}")
|
||||
result = subprocess.run(mount_cmd, check=True, capture_output = True)
|
||||
|
||||
self.logger.debug(f"retorno: {result.returncode}")
|
||||
self.logger.debug(f"stdout: {result.stdout}")
|
||||
self.logger.debug(f"stderr: {result.stderr}")
|
||||
|
||||
# We've mounted a new filesystem, update our filesystems list
|
||||
self.update_mounts()
|
||||
|
||||
def ensure_mounted(self, device):
|
||||
"""
|
||||
Ensure that the given device is mounted.
|
||||
|
||||
This method attempts to mount the specified device to a path derived from
|
||||
the base mount path and the device's basename. If the device is of type NTFS,
|
||||
it uses the NTFSLibrary to handle the mounting process. For other filesystem
|
||||
types, it uses a generic mount method.
|
||||
|
||||
Args:
|
||||
device (str): The path to the device that needs to be mounted.
|
||||
|
||||
Returns:
|
||||
str: The path where the device is mounted.
|
||||
|
||||
Logs:
|
||||
- Info: When starting the mounting process.
|
||||
- Debug: Various debug information including the mount path, filesystem type,
|
||||
and success message.
|
||||
|
||||
Raises:
|
||||
OSError: If there is an error creating the mount directory or mounting the device.
|
||||
"""
|
||||
|
||||
self.logger.info("Mounting %s", device)
|
||||
|
||||
self.unmount(device = device)
|
||||
path = os.path.join(self.base_mount_path, os.path.basename(device))
|
||||
|
||||
self.logger.debug(f"Will mount repo at {path}")
|
||||
if not os.path.exists(path):
|
||||
os.mkdir(path)
|
||||
|
||||
if self.filesystem_type(device) == "ntfs":
|
||||
self.logger.debug("Handing a NTFS filesystem")
|
||||
|
||||
self._modprobe("ntfs3")
|
||||
self.ntfsfix(device)
|
||||
|
||||
ntfs = NTFSLibrary(self.ntfs_implementation)
|
||||
ntfs.mount_filesystem(device, path)
|
||||
self.update_mounts()
|
||||
|
||||
else:
|
||||
self.logger.debug("Handling a non-NTFS filesystem")
|
||||
self.mount(device, path)
|
||||
|
||||
self.logger.debug("Successfully mounted at %s", path)
|
||||
return path
|
||||
|
||||
|
||||
def filesystem_type(self, device = None, mountpoint = None):
|
||||
"""
|
||||
Determine the filesystem type of a given device or mountpoint.
|
||||
|
||||
Args:
|
||||
device (str, optional): The device to probe. If not provided, the device
|
||||
will be determined based on the mountpoint.
|
||||
mountpoint (str, optional): The mountpoint to find the device for. This
|
||||
is used only if the device is not provided.
|
||||
|
||||
Returns:
|
||||
str: The filesystem type of the device.
|
||||
|
||||
Raises:
|
||||
KeyError: If the filesystem type cannot be determined from the probe.
|
||||
|
||||
Logs:
|
||||
Debug: Logs the process of finding the device, probing the device, and
|
||||
the determined filesystem type.
|
||||
"""
|
||||
|
||||
if device is None:
|
||||
self.logger.debug("Finding device for mountpoint %s", mountpoint)
|
||||
device = self.find_device(mountpoint)
|
||||
|
||||
self.logger.debug(f"Probing {device}")
|
||||
|
||||
pr = blkid.Probe()
|
||||
pr.set_device(device)
|
||||
pr.enable_superblocks(True)
|
||||
pr.set_superblocks_flags(blkid.SUBLKS_TYPE | blkid.SUBLKS_USAGE | blkid.SUBLKS_UUID | blkid.SUBLKS_UUIDRAW | blkid.SUBLKS_LABELRAW)
|
||||
pr.do_safeprobe()
|
||||
|
||||
fstype = pr["TYPE"].decode('utf-8')
|
||||
self.logger.debug(f"FS type is {fstype}")
|
||||
|
||||
return fstype
|
||||
|
||||
def is_filesystem(self, path):
|
||||
"""
|
||||
Check if the given path is a filesystem root.
|
||||
|
||||
Args:
|
||||
path (str): The path to check.
|
||||
|
||||
Returns:
|
||||
bool: True if the path is a filesystem root, False otherwise.
|
||||
"""
|
||||
|
||||
# This is just an alias for better code readability
|
||||
return self.is_mounted(mountpoint = path)
|
||||
|
||||
def create_filesystem(self, fs_type = None, fs_uuid = None, device = None):
|
||||
"""
|
||||
Create a filesystem on the specified device.
|
||||
|
||||
Parameters:
|
||||
fs_type (str): The type of filesystem to create (e.g., 'ntfs', 'ext4', 'xfs', 'btrfs').
|
||||
fs_uuid (str): The UUID to assign to the filesystem.
|
||||
device (str): The device on which to create the filesystem (e.g., '/dev/sda1').
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the filesystem type is not recognized or if the filesystem creation command fails.
|
||||
|
||||
"""
|
||||
|
||||
self.logger.info(f"Creating filesystem {fs_type} with UUID {fs_uuid} in {device}")
|
||||
|
||||
if fs_type == "ntfs" or fs_type == "ntfs3":
|
||||
self.logger.debug("Creating NTFS filesystem")
|
||||
ntfs = NTFSLibrary(self.ntfs_implementation)
|
||||
ntfs.create_filesystem(device, "NTFS")
|
||||
ntfs.modify_uuid(device, fs_uuid)
|
||||
|
||||
else:
|
||||
command = [f"/usr/sbin/mkfs.{fs_type}"]
|
||||
command_args = []
|
||||
|
||||
if fs_type == "ext4" or fs_type == "ext3":
|
||||
command_args = ["-U", fs_uuid, "-F", device]
|
||||
elif fs_type == "xfs":
|
||||
command_args = ["-m", f"uuid={fs_uuid}", "-f", device]
|
||||
elif fs_type == "btrfs":
|
||||
command_args = ["-U", fs_uuid, "-f", device]
|
||||
else:
|
||||
raise RuntimeError(f"Don't know how to create filesystem of type {fs_type}")
|
||||
|
||||
command = command + command_args
|
||||
|
||||
self.logger.debug(f"Creating Linux filesystem of type {fs_type} on {device}, command {command}")
|
||||
result = subprocess.run(command, check = True, capture_output=True)
|
||||
|
||||
self.logger.debug(f"retorno: {result.returncode}")
|
||||
self.logger.debug(f"stdout: {result.stdout}")
|
||||
self.logger.debug(f"stderr: {result.stderr}")
|
||||
|
||||
|
||||
|
||||
def mklostandfound(self, path):
|
||||
"""
|
||||
Recreate the lost+found if necessary.
|
||||
|
||||
When cloning at the root of a filesystem, cleaning the contents
|
||||
removes the lost+found directory. This is a special directory that requires the use of
|
||||
a tool to recreate it.
|
||||
|
||||
It may fail if the filesystem does not need it. We consider this harmless and ignore it.
|
||||
|
||||
The command is entirely skipped on NTFS, as mklost+found may malfunction if run on it,
|
||||
and has no useful purpose.
|
||||
"""
|
||||
if self.is_filesystem(path):
|
||||
if self.filesystem_type(mountpoint=path) == "ntfs":
|
||||
self.logger.debug("Not running mklost+found on NTFS")
|
||||
return
|
||||
|
||||
|
||||
curdir = os.getcwd()
|
||||
result = None
|
||||
|
||||
try:
|
||||
self.logger.debug(f"Re-creating lost+found in {path}")
|
||||
os.chdir(path)
|
||||
result = subprocess.run(["/usr/sbin/mklost+found"], check=True, capture_output=True)
|
||||
except subprocess.SubprocessError as e:
|
||||
self.logger.warning(f"Error running mklost+found: {e}")
|
||||
|
||||
if result:
|
||||
self.logger.debug(f"retorno: {result.returncode}")
|
||||
self.logger.debug(f"stdout: {result.stdout}")
|
||||
self.logger.debug(f"stderr: {result.stderr}")
|
||||
|
||||
os.chdir(curdir)
|
||||
|
||||
def ntfsfix(self, device):
|
||||
"""
|
||||
Run the ntfsfix command on the specified device.
|
||||
|
||||
This method uses the ntfsfix utility to fix common NTFS problems on the given device.
|
||||
|
||||
This allows mounting an unclean NTFS filesystem.
|
||||
|
||||
Args:
|
||||
device (str): The path to the device to be fixed.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: If the ntfsfix command fails.
|
||||
"""
|
||||
self.logger.debug(f"Running ntfsfix on {device}")
|
||||
subprocess.run(["/usr/bin/ntfsfix", "-d", device], check=True)
|
||||
|
||||
|
||||
def unload_ntfs(self):
|
||||
"""
|
||||
Unloads the NTFS filesystem module.
|
||||
|
||||
This is a function added as a result of NTFS kernel module troubleshooting,
|
||||
to try to ensure that NTFS code is only active as long as necessary.
|
||||
|
||||
The module is internally loaded as needed, so there's no load_ntfs function.
|
||||
|
||||
It may be removed in the future.
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the module cannot be removed.
|
||||
"""
|
||||
self._rmmod("ntfs3")
|
||||
|
||||
def find_boot_device(self):
|
||||
"""
|
||||
Searches for the EFI boot partition on the system.
|
||||
|
||||
This method scans the system's partitions to locate the EFI boot partition,
|
||||
which is identified by the GUID "C12A7328-F81F-11D2-BA4B-00A0C93EC93B".
|
||||
|
||||
Returns:
|
||||
str: The device node of the EFI partition if found, otherwise None.
|
||||
|
||||
Logs:
|
||||
- Debug messages indicating the progress of the search.
|
||||
- A warning message if the EFI partition is not found.
|
||||
"""
|
||||
disks = []
|
||||
|
||||
self.logger.debug("Looking for EFI partition")
|
||||
with open("/proc/partitions", "r", encoding='utf-8') as partitions_file:
|
||||
line_num=0
|
||||
for line in partitions_file:
|
||||
if line_num >=2:
|
||||
data = line.split()
|
||||
disk = data[3]
|
||||
disks.append(disk)
|
||||
self.logger.debug(f"Disk: {disk}")
|
||||
|
||||
line_num = line_num + 1
|
||||
|
||||
for disk in disks:
|
||||
self.logger.debug("Loading partitions for disk %s", disk)
|
||||
#disk_json_data = subprocess.run(["/usr/sbin/sfdisk", "-J", f"/dev/{disk}"], check=False, capture_output=True)
|
||||
sfdisk_out = subprocess.run(["/usr/sbin/sfdisk", "-J", f"/dev/{disk}"], check=False, capture_output=True)
|
||||
|
||||
if sfdisk_out.returncode == 0:
|
||||
disk_json_data = sfdisk_out.stdout
|
||||
disk_data = json.loads(disk_json_data)
|
||||
|
||||
for part in disk_data["partitiontable"]["partitions"]:
|
||||
self.logger.debug("Checking partition %s", part)
|
||||
if part["type"] == "C12A7328-F81F-11D2-BA4B-00A0C93EC93B":
|
||||
self.logger.debug("EFI partition found at %s", part["node"])
|
||||
return part["node"]
|
||||
else:
|
||||
self.logger.debug("sfdisk returned with code %i, error %s", sfdisk_out.returncode, sfdisk_out.stderr)
|
||||
|
||||
|
||||
self.logger.warning("Failed to find EFI partition!")
|
||||
|
||||
def temp_unmount(self, mountpoint):
|
||||
"""
|
||||
Temporarily unmounts the filesystem at the given mountpoint.
|
||||
|
||||
This method finds the device associated with the specified mountpoint,
|
||||
and returns the information to remount it with temp_remount.
|
||||
|
||||
The purpose of this function is to temporarily unmount a filesystem for
|
||||
actions like fsck, and to mount it back afterwards.
|
||||
|
||||
Args:
|
||||
mountpoint (str): The mountpoint of the filesystem to unmount.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the information needed to remount the filesystem.
|
||||
"""
|
||||
device = self.find_device(mountpoint)
|
||||
fs = self.filesystem_type(mountpoint = mountpoint)
|
||||
|
||||
data = {"mountpoint" : mountpoint, "device" :device, "filesystem" : fs}
|
||||
|
||||
self.logger.debug("Temporarily unmounting device %s, mounted on %s, fs type %s", mountpoint, device, fs)
|
||||
|
||||
self.unmount(mountpoint = mountpoint)
|
||||
return data
|
||||
|
||||
def temp_remount(self, unmount_data):
|
||||
"""
|
||||
Remounts a filesystem unmounted with temp_unmount
|
||||
|
||||
This method remounts a filesystem using the data provided by temp_unmount
|
||||
|
||||
Args:
|
||||
unmount_data (dict): A dictionary containing the data needed to remount the filesystem.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
|
||||
self.logger.debug("Remounting temporarily unmounted device %s on %s, fs type %s", unmount_data["device"], unmount_data["mountpoint"], unmount_data["filesystem"])
|
||||
self.mount(device = unmount_data["device"], mountpoint=unmount_data["mountpoint"], filesystem=unmount_data["filesystem"])
|
|
@ -1,22 +0,0 @@
|
|||
|
||||
|
||||
def parse_kernel_cmdline():
|
||||
"""Parse the kernel arguments to obtain configuration parameters in Oglive
|
||||
|
||||
OpenGnsys passes data in the kernel arguments, for example:
|
||||
[...] group=Aula_virtual ogrepo=192.168.2.1 oglive=192.168.2.1 [...]
|
||||
|
||||
Returns:
|
||||
dict: Dict of configuration parameters and their values.
|
||||
"""
|
||||
params = {}
|
||||
|
||||
with open("/proc/cmdline", encoding='utf-8') as cmdline:
|
||||
line = cmdline.readline()
|
||||
parts = line.split()
|
||||
for part in parts:
|
||||
if "=" in part:
|
||||
key, value = part.split("=")
|
||||
params[key] = value
|
||||
|
||||
return params
|
|
@ -1,111 +0,0 @@
|
|||
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class NTFSImplementation(Enum):
|
||||
KERNEL = 1
|
||||
NTFS3G = 2
|
||||
|
||||
|
||||
class NTFSLibrary:
|
||||
"""
|
||||
A library for managing NTFS filesystems.
|
||||
|
||||
Attributes:
|
||||
logger (logging.Logger): Logger for the class.
|
||||
implementation (NTFSImplementation): The implementation to use for mounting NTFS filesystems.
|
||||
"""
|
||||
|
||||
def __init__(self, implementation):
|
||||
"""
|
||||
Initializes the instance with the given implementation.
|
||||
|
||||
Args:
|
||||
implementation: The implementation to be used by the instance.
|
||||
|
||||
Attributes:
|
||||
logger (logging.Logger): Logger instance for the class, set to debug level.
|
||||
implementation: The implementation provided during initialization.
|
||||
"""
|
||||
self.logger = logging.getLogger("NTFSLibrary")
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
self.implementation = implementation
|
||||
|
||||
self.logger.debug("Initializing")
|
||||
|
||||
def create_filesystem(self, device, label):
|
||||
"""
|
||||
Creates an NTFS filesystem on the specified device with the given label.
|
||||
|
||||
Args:
|
||||
device (str): The device path where the NTFS filesystem will be created.
|
||||
label (str): The label to assign to the NTFS filesystem.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Logs:
|
||||
Logs the creation process with the device and label information.
|
||||
"""
|
||||
self.logger.info(f"Creating NTFS in {device} with label {label}")
|
||||
|
||||
subprocess.run(["/usr/sbin/mkntfs", device, "-Q", "-L", label], check=True)
|
||||
|
||||
|
||||
def mount_filesystem(self, device, mountpoint):
|
||||
"""
|
||||
Mounts a filesystem on the specified mountpoint using the specified NTFS implementation.
|
||||
|
||||
Args:
|
||||
device (str): The device path to be mounted (e.g., '/dev/sda1').
|
||||
mountpoint (str): The directory where the device will be mounted.
|
||||
|
||||
Raises:
|
||||
ValueError: If the NTFS implementation is unknown.
|
||||
|
||||
"""
|
||||
self.logger.info(f"Mounting {device} in {mountpoint} using implementation {self.implementation}")
|
||||
if self.implementation == NTFSImplementation.KERNEL:
|
||||
subprocess.run(["/usr/bin/mount", "-t", "ntfs3", device, mountpoint], check = True)
|
||||
elif self.implementation == NTFSImplementation.NTFS3G:
|
||||
subprocess.run(["/usr/bin/ntfs-3g", device, mountpoint], check = True)
|
||||
else:
|
||||
raise ValueError("Unknown NTFS implementation: {self.implementation}")
|
||||
|
||||
def modify_uuid(self, device, uuid):
|
||||
"""
|
||||
Modify the UUID of an NTFS device.
|
||||
|
||||
This function changes the UUID of the specified NTFS device to the given UUID.
|
||||
It reads the current UUID from the device, logs the change, and writes the new UUID.
|
||||
|
||||
Args:
|
||||
device (str): The path to the NTFS device file.
|
||||
uuid (str): The new UUID to be set, in hexadecimal string format.
|
||||
|
||||
Raises:
|
||||
IOError: If there is an error opening or writing to the device file.
|
||||
"""
|
||||
|
||||
ntfs_uuid_offset = 0x48
|
||||
ntfs_uuid_length = 8
|
||||
|
||||
binary_uuid = bytearray.fromhex(uuid)
|
||||
binary_uuid.reverse()
|
||||
|
||||
self.logger.info(f"Changing UUID on {device} to {uuid}")
|
||||
with open(device, 'r+b') as ntfs_dev:
|
||||
self.logger.debug("Reading %i bytes from offset %i", ntfs_uuid_length, ntfs_uuid_offset)
|
||||
|
||||
ntfs_dev.seek(ntfs_uuid_offset)
|
||||
prev_uuid = bytearray(ntfs_dev.read(ntfs_uuid_length))
|
||||
prev_uuid.reverse()
|
||||
prev_uuid_hex = bytearray.hex(prev_uuid)
|
||||
self.logger.debug(f"Previous UUID: {prev_uuid_hex}")
|
||||
|
||||
self.logger.debug("Writing...")
|
||||
ntfs_dev.seek(ntfs_uuid_offset)
|
||||
ntfs_dev.write(binary_uuid)
|
|
@ -0,0 +1,47 @@
|
|||
#!/bin/bash
|
||||
# Script de ejemplo para arancar un sistema operativo instalado.
|
||||
# Nota: se usa como base para el programa de arranque de OpenGnsys Admin.
|
||||
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -lt 2 -o $# -gt 3 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "Formato: $PROG ndisco nfilesys [str_kernel str_initrd str_kernelparams]"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Comprobar errores.
|
||||
PART=$(ogDiskToDev "$1" "$2") || exit $?
|
||||
MNTDIR=$(ogMount $1 $2) || exit $?
|
||||
|
||||
echo "[0] Inicio del proceso de arranque."
|
||||
|
||||
# Si el equipo está hibernado chequeamos el f.s. y borramos el hiberfile (error cod.6)
|
||||
mount |grep -q "$MNTDIR.*(rw"
|
||||
if [ $? -ne 0 ]; then
|
||||
ogEcho log session "${MSG_WARNING}: $MSG_MOUNTREADONLY"
|
||||
ogUnmount $1 $2
|
||||
ogCheckFs $1 $2
|
||||
|
||||
PART=$(ogDiskToDev "$1" "$2")
|
||||
mkdir -p $MNTDIR
|
||||
ntfs-3g -o remove_hiberfile $PART $MNTDIR
|
||||
ogEcho log session "Particion desbloqueada"
|
||||
|
||||
ogUnmount $1 $2
|
||||
ogMount $1 $2
|
||||
fi
|
||||
|
||||
|
||||
if which bootOsCustom &>/dev/null; then
|
||||
echo "[10] Configuración personalizada del inicio."
|
||||
bootOsCustom $@
|
||||
fi
|
||||
|
||||
echo "[70] Desmontar todos los sistemas de archivos."
|
||||
sync
|
||||
for (( i=1; i <= $(ogDiskToDev | wc -w); i++ )); do
|
||||
ogUnmountAll $i &>/dev/null
|
||||
done
|
||||
echo "[80] Desmontar cache local."
|
||||
ogUnmountCache
|
||||
echo "[90] Arrancar sistema operativo."
|
||||
ogBoot "$@"
|
|
@ -0,0 +1,79 @@
|
|||
#!/bin/bash
|
||||
|
||||
#/**
|
||||
# BuildToOrder
|
||||
#@brief Script de ejemplo para realizar una configuracion del sistema operativo antes de generar imagen o de restaurado.
|
||||
#@brief Activa el uso de los contralodres de disco más usados en windows 7.
|
||||
#@brief (puede usarse como complemento para el programa de creación de imágenes o de restauración).
|
||||
#@param 1 disco
|
||||
#@param 2 particion
|
||||
#@return
|
||||
#@TODO
|
||||
#@exception
|
||||
#@version 1.0.4 - Discos ide + SATA.
|
||||
#@author
|
||||
#@date 2012-10-05
|
||||
#@version 1.1.1b - Funciona para Windows8 y Windows 10. Si la clave no existe (tiene valor vacío) se crea.
|
||||
#@date 2020-05-04
|
||||
|
||||
|
||||
#Control de parametros.
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -ne 2 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "Formato: $PROG ndisco nparticion"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
|
||||
MNTDIR=$(ogMount $1 $2)
|
||||
|
||||
# filtro Tipo de sistema operativo.
|
||||
OSTYPE="$(ogGetOsType $1 $2)"
|
||||
|
||||
|
||||
case "$OSTYPE" in
|
||||
Windows)
|
||||
echo "Filtro versión de sistema operativo windows."
|
||||
TYPE=$(ogGetOsVersion $1 $2)
|
||||
case "$TYPE" in
|
||||
*Windows\ XP)
|
||||
echo "Versión de sistema operativo Windows XP no soportado"
|
||||
exit
|
||||
;;
|
||||
*Windows\ 7*)
|
||||
# Claves a modificar
|
||||
KEYS="intelide pciide msahci iaStorV iaStor LSI_SAS"
|
||||
|
||||
;;
|
||||
*Windows\ *8*|*10*)
|
||||
# Claves a modificar
|
||||
KEYS="intelide pciide storahci iaStorV iaStorAC iaStorAVC LSI_SAS"
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "$TYPE"
|
||||
CONTROLSET="ControlSet001 ControlSet002"
|
||||
for C in $CONTROLSET;
|
||||
# Si no existe la rama de registro continuo a la siguiente.
|
||||
[ "$(ogListRegistryKeys $MNTDIR SYSTEM '\'${C})" == "" ] && continue
|
||||
|
||||
for K in $KEYS; do
|
||||
FULLK='\'$C'\Services\'$K'\Start'
|
||||
VALUE=$(ogGetRegistryValue $MNTDIR SYSTEM "$FULLK")
|
||||
# Si el valor está vacío la creo.
|
||||
if [ "$VALUE" == "" ]; then
|
||||
ogDeleteRegistryValue $MNTDIR SYSTEM "$FULLK"
|
||||
ogAddRegistryValue $MNTDIR SYSTEM "$FULLK" DWORD
|
||||
fi
|
||||
ogSetRegistryValue $MNTDIR SYSTEM "$FULLK" '0'
|
||||
echo " * $C $K enabled"
|
||||
done
|
||||
done
|
||||
;;
|
||||
Linux)
|
||||
echo "Versión de Sistema Operativo GNU/Linux no soportado"
|
||||
;;
|
||||
*)
|
||||
echo "Sistema Operativo no soportado"
|
||||
;;
|
||||
esac
|
|
@ -0,0 +1,324 @@
|
|||
#!/bin/bash
|
||||
|
||||
#/**
|
||||
# cloneremoteFromMaster
|
||||
#@brief Restaura una particion o imagen sobre las particiones de equipos cliente remotos
|
||||
#@param 1 str_origen admite dirección IP del equipo Master.
|
||||
#@param 2 str_origen admite int_disk str_REPO|str_CACHE
|
||||
#@param 3 str_origen admite int partorigen stre_imagen
|
||||
#@param 4 str_sesion multicast|unicast
|
||||
#@param $5 int_disco_destino
|
||||
#@param $6 init_particion_destino
|
||||
#@param $7 str_tool_clone
|
||||
#@param $8 str_tool_compresor
|
||||
#@param ejemplo: cloneRemoteFromMaster 172.17.36.11 1 1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop
|
||||
#@param ejemplo: cloneRemoteFromMaster 172.17.36.11 REPO /imagen1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop
|
||||
#@param ejemplo: cloneRemoteFromMaster 172.17.36.11 CACHE /imagen1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop
|
||||
#@return
|
||||
#@exception OG_ERR_FORMAT formato incorrecto.
|
||||
#@exception $OG_ERR_IMGSIZEPARTITION=30 #Imagen demasiado pequeña para ser clonada
|
||||
#@exception OG_ERR_REDUCEFS=17 #error al reducir sistema de archivos.
|
||||
#@exception OG_ERR_EXTENDFS=18 #errror al expandir el sistema de archivos.
|
||||
#@exception OG_ERR_UCASTSYNTAXT=50 # Error en la generación de sintaxis de transferenica unicast
|
||||
#@exception OG_ERR_UCASTSENDPARTITION=51 # Error en envio UNICAST de una particion
|
||||
#@exception OG_ERR_UCASTSENDFILE=52 # Error en envio UNICAST de un fichero
|
||||
#@exception OG_ERR_UCASTRECEIVERPARTITION=53 #Error en la recepcion UNICAST de una particion
|
||||
#@exception OG_ERR_UCASTRECEIVERFILE=54 #Error en la recepcion UNICAST de un fichero
|
||||
#@exception OG_ERR_MCASTSYNTAXT=55 # Error en la generacion de sintaxis de transferenica Multicast.
|
||||
#@exception OG_ERR_MCASTSENDFILE=56 # Error en envio MULTICAST de un fichero
|
||||
#@exception OG_ERR_MCASTRECEIVERFILE=57 #Error en la recepcion MULTICAST de un fichero
|
||||
#@exception OG_ERR_MCASTSENDPARTITION=58 # Error en envio MULTICAST de una particion
|
||||
#@exception OG_ERR_MCASTRECEIVERPARTITION=59 # Error en la recepcion MULTICAST de una particion
|
||||
#@exception OG_ERR_PROTOCOLJOINMASTER=60 # Error en la conexion de una sesion UNICAST|MULTICAST con el MASTER
|
||||
#@note
|
||||
#@todo:
|
||||
#@version 0.9.1 - integración con OpenGnsys
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2009/03/17
|
||||
#@version 0.9.2 - adaptacion a OpenGnsys
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2010/07/27
|
||||
#@version 0.1.0 - gestion unicast
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011/01/26
|
||||
#@version 1.0 - control de errores para el ogAdmServer
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011/04/24
|
||||
#@version 1.0 - Uso de parted para controlar tamaño particion destino. Requiere Formateo FS previo -parted usa FS para el tamanyo".
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011/04/24
|
||||
#@version 1.0.1 - Se elimina la operación de reducir la particion.
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011/05/16
|
||||
#@version 1.0.3 - se integra con httpd-log.
|
||||
#@version 1.0.3 - Habilita el uso de la variable OGWINREDUCE=TRUE|TRUE para reducir el sistema de archivos a enviar
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011/12/22
|
||||
#@version 1.0.6 - Uso de la funcion ogExecuteAndLog
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2012/02/12
|
||||
#@version 1.1.0.a - sesion multicast cliente puerto:master:0:0 (ticket #872)
|
||||
#@author Antonio J. Doblas Viso
|
||||
#@date 2018/09/11
|
||||
#*/ ##
|
||||
#*/ ##
|
||||
|
||||
#test 1. cliente sin particiones. Detectado TODO: crear estrucutras de particiones
|
||||
#test 2. cliente con particion mas pequeña. Detectado.
|
||||
#test 3. cleinte con particion destinio no formateado. Detectado.
|
||||
#test 4. cliente con particion destino ocupado por el usuario pwd . FALLO.
|
||||
#test 5. master sin origen particion.
|
||||
#test 6. master sin origen fichero.
|
||||
|
||||
TIME1=$SECONDS
|
||||
PROG="$(basename $0)"
|
||||
|
||||
trap "pkill faucet; exit 1" 0 1 2 3 6 9 14 15
|
||||
|
||||
#AYUDA
|
||||
if [ $# -lt 1 -o "$1" == "help" ]; then
|
||||
echo "cloneRemoteFromMaster ipmaster disk init [MULTICAST|UNICAST] session disk part tool comp"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
#ERROR
|
||||
if [ $# -lt 6 ]; then
|
||||
ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ipMaster SOURCE_disco SOURCE_particion [MULTICAST|UNICAST] SESSION TARGET_disk TARGET_partition"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
#Load engine configurator from engine.cfg file.
|
||||
#Carga el configurador del engine desde el fichero engine.cfg
|
||||
# Valores por defecto: #IMGPROG="partclone" ; #IMGCOMP="lzop" ; #IMGEXT="img" #IMGREDUCE="TRUE"
|
||||
[ -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 " " > $OGLOGCOMMAND
|
||||
|
||||
ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*"
|
||||
|
||||
# Procesar parámetros de entrada
|
||||
HOSTIP=`ogGetIpAddress`
|
||||
if [ -z "$HOSTIP" ]
|
||||
then
|
||||
source /tmp/net-eth*
|
||||
HOSTIP=`ogGetIpAddress`
|
||||
fi
|
||||
MASTERIP="$1"
|
||||
PROTOCOL="$4"
|
||||
case "${PROTOCOL^^}" in
|
||||
MULTICAST)
|
||||
SESSIONMCASTSERVER=$5
|
||||
SESSIONMCASTCLIENT=`echo $5 | awk -F: '{print $1}'`:$MASTERIP:0:0
|
||||
;;
|
||||
UNICAST)
|
||||
SESSIONUCASTSERVER=$5
|
||||
SESSIONUCASTCLIENT=`echo $5 | awk -F: '{print $1}'`:$MASTERIP
|
||||
;;
|
||||
*)
|
||||
exit $(ogRaiseError $OG_ERR_FORMAT "Protocolo $PROTOCOL no soportado en esta operacion"; echo $?)
|
||||
;;
|
||||
esac
|
||||
# contenedor destino (disco particion)
|
||||
DISKTARGET="$6"
|
||||
PARTTARGET="$7"
|
||||
#herramienta de compresión.
|
||||
TOOLCLONE="$8"
|
||||
COMPRESOR="$9"
|
||||
|
||||
pkill faucet
|
||||
|
||||
# Preparando Instrucción según sea Master o Client
|
||||
case $MASTERIP in
|
||||
$HOSTIP)
|
||||
ogEcho log session "[1] Equipo Master preparando el origen de los datos a enviar"
|
||||
ogGetPath $2 $3.img &>/dev/null; RC=$?;
|
||||
ogDiskToDev $2 $3 &>/dev/null; RETVAL=$?;
|
||||
|
||||
if [ "$RC" == "0" ]; then
|
||||
IMG=$(ogGetPath $2 $3.img); MODEMASTER=SENDFILE
|
||||
elif [ "$RETVAL" == "0" ]; then
|
||||
DISKSOURCE=$2; PARTSOURCE=$3; MODEMASTER=SENDPARTITION
|
||||
else
|
||||
ogRaiseError $OG_ERR_NOTFOUND "$2 $3"; exit $?
|
||||
fi
|
||||
echo $MODEMASTER
|
||||
# Preparando instrucción del Master segun $MODEMASTER{SENDPARTITION SENDFILE}
|
||||
case "$MODEMASTER" in
|
||||
SENDPARTITION)
|
||||
ogEcho log session "[5] Master en modo $MODEMASTER: informacion inicial a los clientes-slaves"
|
||||
if ps aux | grep -v grep | grep "faucet 4000"
|
||||
then
|
||||
ogRaiseError $OG_ERR_NOTFOUND "MASTER: puerto en uso: 118"; exit $?
|
||||
else
|
||||
faucet 4000 --out echo "WORKING" &
|
||||
fi
|
||||
ogEcho log session "[10]: Desmontando DISK:$DISKSOURCE PARTITION:$PARTSOURCE"
|
||||
ogUnmount $2 $3 || exit $(ogRaiseError $OG_ERR_LOCKED "no se puede desmontar $2 $3 l124"; echo $?)
|
||||
#Obtener tamaño de la partición.
|
||||
SIZE=$(ogGetPartitionSize $2 $3) || exit $(ogRaiseError $OG_ERR_REDUCEFS "Error al detectar tamaño partcion $2 $3 l127"; echo $?)
|
||||
|
||||
# Si es UEFI copio el cargador de arranque a la partición
|
||||
OSTYPE="$(ogGetOsType $2 $3)"
|
||||
if ogIsEfiActive && [ "$OSTYPE" == "Windows" ]; then
|
||||
ogEcho log session "[12] $MSG_HELP_ogCopyEfiBootLoader"
|
||||
ogCopyEfiBootLoader $2 $3
|
||||
fi
|
||||
|
||||
if [ "$OGWINREDUCE" == "TRUE" ]
|
||||
then
|
||||
ogEcho log session "[15]: Calculando la reduccion del sistema de archivos DISK:$DISKSOURCE PARTITION:$PARTSOURCE SIZE:$SIZE"
|
||||
ogReduceFs $2 $3 || exit $(ogRaiseError $OG_ERR_REDUCEFS "Error al reducir el FS $2 $3 l129"; echo $?)
|
||||
fi
|
||||
|
||||
REDSIZE=$(ogGetFsSize $2 $3) || exit $(ogRaiseError $OG_ERR_REDUCEFS "Error al detectar el nuevo FS $2 $3 l130"; echo $?)
|
||||
TIMEAUX=$[SECONDS-TIME1]
|
||||
ogEcho log session "[20]: Preparada para enviar el sistema de archivos: Tamaño datos: $REDSIZE origne: $DISKSOURCE $PARTSOURCE"
|
||||
ogEcho log session " tiempo de reducción del sistema de archivos: $[TIMEAUX/60]m $[TIMEAUX%60]s"
|
||||
|
||||
#if [ $REDSIZE -lt $SIZE ]; then
|
||||
# echo "[24] Redimensionar partición a $REDSIZE KB."
|
||||
# ogSetPartitionSize $2 $3 $REDSIZE
|
||||
#fi
|
||||
|
||||
ogEcho log session "[25] Master en Modo $MODEMASTER: informacion de transferencia a los clientes-slaves $PROTOCOL $TOOLCLONE $COMPRESOR $REDSIZE"
|
||||
pkill faucet
|
||||
if ps aux | grep -v grep | grep "faucet 4000"
|
||||
then
|
||||
ogRaiseError $OG_ERR_NOTFOUND "MASTER: puerto en uso: 140"; exit $?
|
||||
else
|
||||
faucet 4000 --out echo "READY $TOOLCLONE $COMPRESOR $REDSIZE" &
|
||||
fi
|
||||
case "${PROTOCOL^^}" in
|
||||
MULTICAST)
|
||||
ogEcho log session "[29] Transferencia Multicast: ogMcastSendPartition $DISKSOURCE $PARTSOURCE $SESSIONMCASTSERVER $TOOLCLONE $COMPRESOR "
|
||||
ogExecAndLog session "ogMcastSendPartition" "$DISKSOURCE" "$PARTSOURCE" "$SESSIONMCASTSERVER" "$TOOLCLONE" "$COMPRESOR" || RETVAL=$?
|
||||
;;
|
||||
UNICAST)
|
||||
sleep 60
|
||||
ogEcho log session "[29] Transferencia Unicast: ogUcastSendPartition $DISKSOURCE $PARTSOURCE $SESSIONUCASTSERVER $TOOLCLONE $COMPRESOR"
|
||||
ogExecAndLog session "ogUcastSendPartition" "$DISKSOURCE" "$PARTSOURCE" "$SESSIONUCASTSERVER" "$TOOLCLONE" "$COMPRESOR" || RETVAL=$?
|
||||
;;
|
||||
esac
|
||||
|
||||
#if [ $REDSIZE -lt $SIZE ]; then
|
||||
# echo "[85] Redimensionar partición a $SIZE KB."
|
||||
# ogSetPartitionSize $2 $3 $SIZE
|
||||
ogEcho log session "[90] Extender sistema de archivos."
|
||||
ogExtendFs $2 $3
|
||||
#fi
|
||||
pkill faucet
|
||||
if [ $RETVAL == 0 ]
|
||||
then
|
||||
exit 0
|
||||
else
|
||||
exit $(ogRaiseError $OG_ERR_MCASTSENDPARTITION "Error al enviar la particion $2 $3 con protocolo $PROTOCOL l167"; echo $?)
|
||||
fi
|
||||
|
||||
;;
|
||||
SENDFILE)
|
||||
ogEcho log session "[5] Master en modo $MODEMASTER: informacion inicial a los clientes-slaves"
|
||||
ogEcho log session "[10]: Preparando Imagen: $IMG"
|
||||
TOOLCLONE=$(ogGetImageProgram $2 $3) || exit $(ogRaiseError $OG_ERR_LOCKED "TOOLCLONE no detectado l174"; echo $?)
|
||||
COMPRESOR=$(ogGetImageCompressor $2 $3) || exit $(ogRaiseError $OG_ERR_LOCKED "COMPRESOR NO DETECTADO l175"; echo $?)
|
||||
REDSIZE=$(ogGetImageSize $2 $3) || exit $(ogRaiseError $OG_ERR_LOCKED "REDSIZE NO DETECTADO l176"; echo $?)
|
||||
ogEcho log session "[25] Master en Modo $MODEMASTER"
|
||||
ogEcho log "Informacion de transferencia a los clientes-slaves $PROTOCOL $TOOLCLONE $COMPRESOR $REDSIZE"
|
||||
if ps aux | grep -v grep | grep "faucet 4000"
|
||||
then
|
||||
ogRaiseError $OG_ERR_NOTFOUND "MASTER: puerto en uso: 140"; exit $?
|
||||
else
|
||||
faucet 4000 --out echo "READY $TOOLCLONE $COMPRESOR $REDSIZE" &
|
||||
fi
|
||||
case "${PROTOCOL^^}" in
|
||||
MULTICAST)
|
||||
echo "[29] ogMcastSendFile $2 $3.img $SESSIONMCASTSERVER "
|
||||
ogMcastSendFile $2 $3.img $SESSIONMCASTSERVER || RETVAL=$?
|
||||
;;
|
||||
UNICAST)
|
||||
sleep 60
|
||||
echo "[29] ogUcastSendFile $2 $3.img $SESSIONUCASTSERVER"
|
||||
ogUcastSendFile $2 $3.img $SESSIONUCASTSERVER || RETVAL=$?
|
||||
;;
|
||||
esac
|
||||
pkill faucet
|
||||
if [ $RETVAL == 0 ]
|
||||
then
|
||||
exit 0
|
||||
else
|
||||
exit $(ogRaiseError $OG_ERR_MCASTSENDFILE "Error al enviar la image $2 $3.img con protocolo $PROTOCOL l200"; echo $?)
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
# FIN Preparando instrucción del Master segun $MODEMASTER{SENDPARTITION SENDFILE}
|
||||
;;
|
||||
*)
|
||||
ogEcho log session "[1] Equipo -Client- preparando para recibir datos $PROTOCOL"
|
||||
ogDiskToDev $DISKTARGET $PARTTARGET &>/dev/null || exit $(ogRaiseError $OG_ERR_LOCKED "El cliente no tiene esas particiones $DISKTARGET $PARTTARGET l211"; echo $?)
|
||||
# TODO: si el cliente no está en la lista de clientes UNICAST salir.
|
||||
case "${PROTOCOL^^}" in
|
||||
UNICAST)
|
||||
echo "$SESSIONUCASTSERVER" | grep $HOSTIP || exit $(ogRaiseError $OG_ERR_PROTOCOLJOINMASTER "Este cliente no pertence a la sesion UNICAST l214"; echo $?)
|
||||
;;
|
||||
esac
|
||||
ogEcho log session "[2] Desmontando particion destino"
|
||||
ogUnmount $DISKTARGET $PARTTARGET || exit $(ogRaiseError $OG_ERR_LOCKED "no se puede desmontar la particion destino $2 $3 l218"; echo $?)
|
||||
ogEcho log session "[25] Buscando informacion extra sobre la clonacion con el master $MASTERIP: "
|
||||
sleep 10
|
||||
TIMEWAITMASTER=120
|
||||
TIMEWAITING=0
|
||||
GETINFO="NONE"
|
||||
while [ "${GETINFO}" != "OK" ]
|
||||
do
|
||||
INFOEXTRA=`hose $MASTERIP 4000 --in cat 2>/dev/null`
|
||||
sleep 10; echo -n "."
|
||||
#echo comienza el timeout $TIMEWAITMASTER para abortar
|
||||
[ -z "$INFOEXTRA" ] && let TIMEWAITMASTER=$TIMEWAITMASTER-10
|
||||
[ "$TIMEWAITMASTER" -gt "0" ] || exit $(ogRaiseError $OG_ERR_PROTOCOLJOINMASTER " l230 "; echo $?)
|
||||
#Si primer parametro desde el server es READY, salimos del bucle
|
||||
GETINFO=$(echo $INFOEXTRA | awk '{print $1}')
|
||||
[ "$GETINFO" == "READY" ] && GETINFO="OK"
|
||||
done
|
||||
echo $INFOEXTRA
|
||||
TOOLCLONE=$(echo $INFOEXTRA | awk '{print $2}')
|
||||
COMPRESOR=$(echo $INFOEXTRA | awk '{print $3}')
|
||||
SIZEIMAGE=$(echo $INFOEXTRA | awk '{print $4}')
|
||||
ogEcho log "$INFOEXTRA = herramienta= $TOOLCLONE compresor= $COMPRESOR size= $SIZEIMAGE"
|
||||
ogMount $DISKTARGET $PARTTARGET || ogFormat $DISKTARGET $PARTTARGET
|
||||
#SIZEPARTTARGET=$(parted `ogDiskToDev $DISKTARGET $PARTTARGET` unit kB print | grep Disk | awk -F" " '{print $3}' | tr -d kB);
|
||||
SIZEPARTTARGET=$(ogGetPartitionSize $DISKTARGET $PARTTARGET )
|
||||
ogEcho log session "[28] comprobando que el tamaño de la imagen $SIZEIMAGE es menor que el de la particion destino $SIZEPARTTARGET"
|
||||
# comprobamos que el tamaño de a imagen es menor que la del cliente.
|
||||
if [ "$SIZEIMAGE" -lt "$SIZEPARTTARGET" ]
|
||||
then
|
||||
ogEcho log session "[30] Iniciando Cliente $PROTOCOL "
|
||||
case "${PROTOCOL^^}" in
|
||||
MULTICAST)
|
||||
ogEcho log session "ogMcastReceiverPartition $DISKTARGET $PARTTARGET $SESSIONMCASTCLIENT $TOOLCLONE $COMPRESOR"
|
||||
ogExecAndLog command "ogMcastReceiverPartition" "$DISKTARGET" "$PARTTARGET" "$SESSIONMCASTCLIENT" "$TOOLCLONE" "$COMPRESOR" || exit $(ogRaiseError $OG_ERR_MCASTRECEIVERPARTITION " l251 "; echo $?)
|
||||
;;
|
||||
UNICAST)
|
||||
ogEcho log session "ogUcastReceiverPartition $DISKTARGET $PARTTARGET $SESSIONUCASTCLIENT $TOOLCLONE $COMPRESOR"
|
||||
ogExecAndLog command "ogUcastReceiverPartition" "$DISKTARGET" "$PARTTARGET" "$SESSIONUCASTCLIENT" "$TOOLCLONE" "$COMPRESOR" || exit $(ogRaiseError $OG_ERR_UCASTRECEIVERPARTITION " l230 "; echo $?)
|
||||
;;
|
||||
esac
|
||||
if which configureOsCustom &>/dev/null; then
|
||||
ogEcho log session "[90] configureOsCustom $DISKTARGET $PARTTARGET"
|
||||
# Si $2 = num_disk las varibles REPO IMGNAME estan vacias
|
||||
! [[ $2 =~ ^[0-9]+$ ]] && REPO="$2" && IMGNAME="$3"
|
||||
configureOsCustom $DISKTARGET $PARTTARGET $REPO $IMGNAME
|
||||
else
|
||||
ogEcho log session "[90] $MSG_SCRIPTS_OS_CONFIGURE $DISKTARGET $PARTTARGET"
|
||||
configureOs $DISKTARGET $PARTTARGET
|
||||
fi
|
||||
|
||||
else
|
||||
# Si el tamaño de los datos recibidos es más grande que la particion destino
|
||||
ogRaiseError $OG_ERR_IMGSIZEPARTITION "ERROR tamanio particion= $SIZEPARTTARGET menor que la imagen= $SIZEIMAGE"; exit $?
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
TIME=$[SECONDS-TIME1]
|
||||
ogEcho log session "[100] Duración de la operación $[TIME/60]m $[TIME%60]s"
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
#!/bin/bash
|
||||
|
||||
#/**
|
||||
# configureOs
|
||||
#@brief Script para realizar la configuracion del sistema operativo restaurado.
|
||||
#@param 1 disco
|
||||
#@param 2 particion
|
||||
#@return
|
||||
#@TODO comprobar que el tipo de particion corresponde con el sistema de archivos.
|
||||
#@exception OG_ERR_FORMAT # 1 formato incorrecto.
|
||||
#@version 1.0.1 - Integracion cambio de nombre, extender fs, chequear particion activa
|
||||
#@author
|
||||
#@date 2011-05-11
|
||||
#@version 1.0.1 - Configura el sector de la particion y el gestor de windows para iniciarse desde cualquier particion.
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011-05-20
|
||||
#@version 1.0.2 - Configura el sector de la particion y el gestor de linux para iniciarse desde cualquier particion.
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011-11-22
|
||||
#@version 1.0.3 - Configura el chkdisk en el arranque de windows, segun variable OGWINCHKDISK del engine.cfg.
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2011-12-23
|
||||
#@version 1.0.4 - Inyecta el cliente para gestión del sistema operativo.
|
||||
#@author Ramon Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2012-04-11
|
||||
#@version 1.0.5 - Postconfiguración para Mac OS X.
|
||||
#@author Ramon Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2013-10-11
|
||||
#@version 1.1.0 - Postconfiguración para agente de sistema operativo basado en REST.
|
||||
#@author Ramon Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2016-08-16
|
||||
#@version 1.0.6b - llamadas opcionales para mejoras varias. Descomentar la instruccion para su activacion. ogConfigureFstab
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2016-11-03
|
||||
#@version 1.1.1 - Equipos UEFI: para Windows copia cargador de arranque a partición UEFI, para linux configura particion ESP en fstab. (ticket #802 #889 #890)
|
||||
#@author Irina Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2019-01-08
|
||||
#*/ ##
|
||||
|
||||
# Carga el configurador del engine y los parámetros de red.
|
||||
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
|
||||
[ -f $DEVICECFG ] && source $DEVICECFG
|
||||
|
||||
# Si el sistema de archivos no esta extendido, ampliarlo al tamaño de su partición.
|
||||
PARTSIZE=$(ogGetPartitionSize $1 $2) || exit $?
|
||||
FSSIZE=$(ogGetFsSize $1 $2)
|
||||
if [ $FSSIZE -lt $PARTSIZE ]; then
|
||||
echo "Extender sistema de archivos."
|
||||
ogExtendFs $1 $2
|
||||
fi
|
||||
|
||||
# Si no existe partición activa, activar este sistema.
|
||||
FLAGACTIVE=$(ogGetPartitionActive $1)
|
||||
[ -z $FLAGACTIVE ] && ogSetPartitionActive $1 $2
|
||||
|
||||
# Si el sistema de archivos es de solo lectura, no hacer la post-configuración.
|
||||
MNTDIR=$(ogMount $1 $2)
|
||||
if ! ogIsWritable $1 $2; then
|
||||
echo "AVISO: sistema de archivos de solo lectura, no se ejecuta postconfiguración."
|
||||
exit
|
||||
fi
|
||||
|
||||
# Nombre del cliente.
|
||||
HOST="$(ogGetHostname)"
|
||||
|
||||
# Post-configuración personalizada para cada tipo de sistema operativo.
|
||||
OSTYPE="$(ogGetOsType $1 $2)"
|
||||
case "$OSTYPE" in
|
||||
Windows) # Postconfiguración de Windows.
|
||||
# Cambiar nombre en sistemas Windows.
|
||||
HOST=${HOST:-"pc"}
|
||||
ogSetWindowsName $1 $2 "$HOST"
|
||||
# Si es UEFI copio el cargador de arranque a la partición EFI e instalo Grub.
|
||||
if ogIsEfiActive; then
|
||||
ogRestoreEfiBootLoader $1 $2
|
||||
ogGrubInstallMbr $(ogGetEsp) TRUE
|
||||
else
|
||||
# Configurar el boot sector de la partición Windows.
|
||||
ogFixBootSector $1 $2
|
||||
fi
|
||||
# Configurar el gestor de arranque de Windows XP/Vista/7.
|
||||
ogWindowsBootParameters $1 $2
|
||||
# Registrar en Windows que la partición indicada es su nueva unidad C:\
|
||||
ogWindowsRegisterPartition $1 $2 C $1 $2
|
||||
# Configurar nuevo agente OGAgent.
|
||||
ogConfigureOgagent $1 $2
|
||||
# Eliminar el antiguo cliente de Windows.
|
||||
if [ -n "$(ogGetPath $MNTDIR/windows/ogAdmWinClient.exe)$(ogGetPath $MNTDIR/winnt/ogAdmWinClient.exe)" ]; then
|
||||
ogInstallMiniSetup $1 $2 postconf.cmd
|
||||
ogUninstallWindowsClient $1 $2 postconf.cmd
|
||||
fi
|
||||
;;
|
||||
Linux) # Postconfiguración de GNU/Linux.
|
||||
# Configuro fstab: particion de Swap y si es UEFI además la partición EFI.
|
||||
ogConfigureFstab $1 $2
|
||||
# Si es UEFI instalo Grub en la partición EFI
|
||||
ogIsEfiActive && ogGrubInstallMbr $(ogGetEsp) TRUE
|
||||
## Instala (no configura) el codigo de arranque del Grub en la partición (no lo configura, se mantiene el original de la imagen)
|
||||
ogGrubInstallPartition $1 $2
|
||||
# Eliminar el antiguo cliente de Linux.
|
||||
[ -n "$(find $MNTDIR/usr/sbin $MNTDIR/sbin $MNTDIR/usr/local/sbin -name ogAdmLnxClient -print)" ] && ogUninstallLinuxClient $1 $2
|
||||
# Configurar nuevo agente OGAgent.
|
||||
ogConfigureOgagent $1 $2
|
||||
## Modificar el nombre del equipo
|
||||
echo "Asignar nombre Linux \"$HOST\"."
|
||||
ETC=$(ogGetPath $1 $2 /etc)
|
||||
[ -d "$ETC" ] && echo "$HOST" >$ETC/hostname 2>/dev/null
|
||||
;;
|
||||
MacOS) # Postconfiguración de Mac OS X.
|
||||
# Fichero indicador de activación de postconfiguración.
|
||||
touch $MNTDIR/osxpostconf
|
||||
|
||||
# Crear fichero de configuración del servicio de arranque.
|
||||
cat << EOT >$MNTDIR/Library/LaunchDaemons/es.opengnsys.postconfd.plist
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>es.opengnsys.postconfd.sh</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>/var/root/postconfd.sh</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>StandardOutPath</key>
|
||||
<string>/var/log/postconfd.log</string>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>/var/log/postconfd.err</string>
|
||||
<key>Debug</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
EOT
|
||||
|
||||
# Programa de inicio que será ejecutado en el arranque de Mac OS X.
|
||||
cat << EOT >$MNTDIR/var/root/postconfd.sh
|
||||
#!/bin/bash
|
||||
# postconfd - ejecución de scripts de inicio.
|
||||
|
||||
# Ejecutar postconfiguración si existe el fichero indicador.
|
||||
if [ -e /osxpostconf ]; then
|
||||
# Tomar nombre del equipo.
|
||||
HOST="$HOST"
|
||||
if [ -z "\$HOST" ]; then
|
||||
# Si no hay nombre asociado, activar la red para obtener datos del DHCP.
|
||||
source /etc/rc.common
|
||||
CheckForNetwork
|
||||
while [ "\$NETWORKUP" != "-YES-" ]; do
|
||||
sleep 5
|
||||
NETWORKUP=
|
||||
CheckForNetwork
|
||||
done
|
||||
# Componer nombre del equipo a partir de datos del DHCP.
|
||||
IP=\$(ifconfig en0 inet | awk '{if (\$1=="inet") print \$2}')
|
||||
HOST="mac-\$(echo \${IP//./-} | cut -f3-4 -d-)"
|
||||
fi
|
||||
# Asignar nombre del equipo.
|
||||
scutil --set ComputerName "\$HOST"
|
||||
scutil --set LocalHostName "\$HOST"
|
||||
scutil --set HostName "\$HOST"
|
||||
hostname "\$HOST"
|
||||
# Descromprimir ficheros de versión para obtener inventario de aplicaciones.
|
||||
find /Applications -type d -name "*.app" -prune -exec \
|
||||
ditto --nopreserveHFSCompression "{}/Contents/version.plist" "{}/Contents/version.plist.uncompress"
|
||||
rm -f /osxpostconf # Borrar fichero indicador de psotconfiguración
|
||||
fi
|
||||
EOT
|
||||
# Dar permiso de ejecución.
|
||||
chmod 700 $MNTDIR/var/root/postconfd.sh
|
||||
# Configurar nuevo agente OGAgent de sistema operativo.
|
||||
ogConfigureOgagent $1 $2
|
||||
;;
|
||||
esac
|
||||
exit 0
|
|
@ -0,0 +1,182 @@
|
|||
#!/bin/bash
|
||||
|
||||
#/**
|
||||
#@file createImage
|
||||
#@brief Scirpt de ejemplo para crear una imagen de un sistema de archivos.
|
||||
#@brief Se usa como base para el programa de creación de imágenes de OpenGnsys Admin).
|
||||
#@param 1 disco
|
||||
#@param 2 particion
|
||||
#@param 3 REPO|CACHE
|
||||
#@param 4 imagen
|
||||
#@return
|
||||
#@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.
|
||||
#@note
|
||||
#@todo: que hacer, si el tamaño de la cache es sufciente, pero no tiene espacio libre
|
||||
#@todo: que hacer, si hay una imagen con igual nombre en la cache
|
||||
#@version 1.0 - control de errores para el ogAdmServer
|
||||
#@author
|
||||
#@date 2011-04-10
|
||||
#@version 1.0.1 - Control de espacio requerido
|
||||
#@author Antonio J.Doblas Viso
|
||||
#@date 2011-05-10
|
||||
#@version 1.0.2 - Separacion de log
|
||||
#@author Antonio J.Doblas Viso
|
||||
#@date 2011-08-4
|
||||
#@version 1.1.0 - La copia de seguridad de la imagen antigua se hace después de las comprobaciones.
|
||||
#@author Irina Gomez - ETSII Universidad de Sevilla
|
||||
#@date 2016-10-14
|
||||
#@version 1.1.0 - Se muestra el espacio necesario para alojar la imagen y el disponible (ticket #771)
|
||||
#@author Irina Gomez - ETSII Universidad de Sevilla
|
||||
#@date 2017-03-28
|
||||
#@version 1.1.1 - #802 Equipos EFI: se guarda el cargador de arranque y UUID de las particiones
|
||||
#@author Irina Gomez - ETSII Universidad de Sevilla
|
||||
#@date 2019-01-08
|
||||
#*/ ##
|
||||
|
||||
# Test 1. crear una imagen en un REPO sin espacio libre.
|
||||
# test 2. crear una imagen en un REPO en modo solo lectura.
|
||||
# test 3. intentar crear una imagen en la cache de un equipo que no la disponga.
|
||||
# test 4. crear una imagen en la Cache sin espacio sufiente.
|
||||
# test 5. intentar crear una imagen, en la que no se puede reducir el FS.
|
||||
|
||||
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -ne 4 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE imagen"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
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
|
||||
|
||||
# Valores por defecto en etc/engine.cfg
|
||||
#IMGPROG="partclone"
|
||||
#IMGCOMP="lzop"
|
||||
IMGEXT=${IMGEXT:-"img"}
|
||||
#IMGREDUCE="TRUE"
|
||||
REPO="${3^^}"
|
||||
|
||||
# Unidad organizativa
|
||||
[ "$ogunit" != "" ] && OGUNIT="$ogunit"
|
||||
|
||||
# Clear temporary file used as log track by httpdlog
|
||||
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
|
||||
# salvo si es llamado desde createImageCustom
|
||||
if [ "$(ogGetCaller)" != "createImageCustom" ]; then
|
||||
echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp
|
||||
fi
|
||||
|
||||
ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*"
|
||||
|
||||
# Si es una ip y es igual a la del equipo restaura desde cache
|
||||
[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE"
|
||||
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
|
||||
ogCheckIpAddress $REPO
|
||||
if [ $? == 0 -o $REPO == "REPO" ] ; then
|
||||
# Si falla el cambio -> salimos con error repositorio no valido
|
||||
ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?)
|
||||
REPO="REPO"
|
||||
fi
|
||||
|
||||
# Si el repositorio es CACHE comprobamos que exista
|
||||
if [ "$REPO" == "CACHE" ]; then
|
||||
! ogFindCache >/dev/null && exit $(ogRaiseError $OG_ERR_NOTCACHE "CACHE "; echo $?)
|
||||
fi
|
||||
|
||||
# Obtener información de los parámetros de entrada.
|
||||
PART=$(ogDiskToDev "$1" "$2" 2>/dev/null) || exit $(ogRaiseError $OG_ERR_PARTITION "$1 $2"; echo $?)
|
||||
|
||||
#Comprobamos acceso de escritura.
|
||||
DIRTEMP=$(date +%Y%m%d-%H%M%S)
|
||||
ogMakeDir $REPO /$4$DIRTEMP 2>/dev/null || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO"; echo $?) && ogDeleteTree $REPO /$4$DIRTEMP
|
||||
|
||||
IMGDIR=$(ogGetParentPath "$REPO" "/$4")
|
||||
# Si no existe, crear subdirectorio de la imagen.
|
||||
if [ $? != 0 ]; then
|
||||
ogEcho log session "[5] $MSG_HELP_ogMakeDir \"$REPO $(dirname "$4")."
|
||||
ogMakeDir "$REPO" $(dirname "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?)
|
||||
IMGDIR=$(ogGetParentPath "$REPO" "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?)
|
||||
fi
|
||||
IMGFILE=$IMGDIR/$(basename "/$4").$IMGEXT
|
||||
|
||||
echo " " > $OGLOGCOMMAND
|
||||
# Borramos ficheros de paginacion y configuracion
|
||||
ogCleanOs $1 $2
|
||||
|
||||
#Comprobar espacio que requerira la imagen para ser almacenada
|
||||
read SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$REPO" "$4")
|
||||
|
||||
ogEcho log session "[16] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED $SIZEFREE"
|
||||
[ "$ISENOUGHSPACE" == "TRUE" ] || exit $(ogRaiseError session $OG_ERR_CACHESIZE "$REPO"; echo $?)
|
||||
|
||||
# Comprobar consistencia del sistema de archivos.
|
||||
echo " " > $OGLOGCOMMAND
|
||||
SIZEFS=$(ogGetFsSize $1 $2)
|
||||
ogEcho log session "[20] $MSG_HELP_ogCheckFs $PART $SIZEFS (KB)"
|
||||
ogUnmount $1 $2 2>/dev/null
|
||||
ogCheckFs $1 $2 || exit $(ogRaiseError $OG_ERR_PARTITION "ogCheckFs $1 $2" && echo $?)
|
||||
|
||||
# Si es UEFI copio el cargador de arranque a la partición
|
||||
OSTYPE="$(ogGetOsType $1 $2)"
|
||||
if ogIsEfiActive && [ "$OSTYPE" == "Windows" ]; then
|
||||
ogEcho log session "[25] $MSG_HELP_ogCopyEfiBootLoader"
|
||||
ogCopyEfiBootLoader $1 $2
|
||||
fi
|
||||
|
||||
# Evaluar variable de engine.cfg para reducir el sistema de archivos en la creacion
|
||||
if [ "$IMGREDUCE" == "TRUE" ]
|
||||
then
|
||||
ogEcho log session "[30] $MSG_HELP_ogReduceFs"
|
||||
ogReduceFs $1 $2 &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_REDUCEFS "$1 $2"; echo $?)
|
||||
NEWSIZEFS=$(ogGetFsSize $1 $2)
|
||||
TIMEAUX=$[SECONDS-TIME1]
|
||||
ogEcho log session " $MSG_SCRIPTS_TIME_PARTIAL ( $NEWSIZEFS KB ) : $[TIMEAUX/60]m $[TIMEAUX%60]s"
|
||||
fi
|
||||
|
||||
# Renombrar el fichero de imagen si ya existe.
|
||||
if [ -f "$IMGFILE" ]; then
|
||||
ogEcho log session "[35] $MSG_SCRIPTS_FILE_RENAME \"$IMGFILE\" -> \"$IMGFILE.ant\"."
|
||||
mv "$IMGFILE" "$IMGFILE.ant"
|
||||
mv "$IMGFILE.torrent" "$IMGFILE.torrent.ant" 2>/dev/null
|
||||
mv "$IMGFILE.sum" "$IMGFILE.sum.ant" 2>/dev/null
|
||||
mv "$IMGFILE.full.sum" "$IMGFILE.full.sum.ant" 2>/dev/null
|
||||
fi
|
||||
|
||||
# Crear la imagen.
|
||||
echo " " > $OGLOGCOMMAND
|
||||
TIME2=$SECONDS
|
||||
ogEcho log session "[40] $MSG_HELP_ogCreateImage : ogCreateImage $1 $2 $REPO $4 $IMGPROG $IMGCOMP"
|
||||
ogCreateImage "$1" "$2" "$REPO" "/$4" "$IMGPROG" "$IMGCOMP" &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_IMAGE "ogCreteImage"; echo $?)
|
||||
RESUMECREATEIMAGE=$(grep "Total Time:" $OGLOGCOMMAND)
|
||||
TIMEAUX2=$[SECONDS-TIME2]
|
||||
ogEcho log session " $RESUMECREATEIMAGE "
|
||||
ogEcho log session " $MSG_SCRIPTS_TIME_PARTIAL : $[TIMEAUX2/60]m $[TIMEAUX2%60]s"
|
||||
|
||||
# Extender sistema de archivos
|
||||
TIME3=$SECONDS
|
||||
ogEcho log session "[90] Extender sistema de archivos."
|
||||
ogExtendFs $1 $2 || exit $(ogRaiseError $OG_ERR_EXTENDFS "$1 $2"; echo $?)
|
||||
SIZEFS2=$(ogGetFsSize $1 $2)
|
||||
TIMEAUX3=$[SECONDS-TIME3]
|
||||
ogEcho log session " $MSG_HELP_ogExtendFs $NEWSIZEFS -> $SIZEFS = $SIZEFS2: $[TIMEAUX3/60]m $[TIMEAUX3%60]s"
|
||||
|
||||
#TODO que hacer si error al extender sistemade archivos
|
||||
|
||||
#resumen de la operacion
|
||||
IMGSIZE=$(ls -s `ogGetPath $REPO /$4.$IMGEXT`| cut -f1 -d" ")
|
||||
IMGOS=$(ogGetImageInfo `ogGetPath $REPO /$4.$IMGEXT`)
|
||||
|
||||
TIME=$[SECONDS-TIME1]
|
||||
ogEcho log session "[100] $MSG_SCRIPTS_TIME_TOTAL $[TIME/60]m $[TIME%60]s"
|
||||
ogEcho log session " FileSystem $PART with $NEWSIZEFS KB data created onto file-image as $4 and used $IMGSIZE KB across DFS $ogprotocol"
|
||||
ogEcho log session " Image-file $4 metada: $IMGOS"
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
ogCreatePartitions "$@"
|
||||
exit 0
|
|
@ -0,0 +1,246 @@
|
|||
#!/bin/bash
|
||||
#/**
|
||||
#@file deployImage
|
||||
#@brief Proceso completo de despliegue de imagen, incluyendo actualización de la caché, restauración y post-configuración (este script es llamado por la interfaz RestaurarImagen).
|
||||
#@param $1 Repositorio (CACHE, REPO o dirección IP)
|
||||
#@param $2 Nombre canónico de la imagen (sin extensión)
|
||||
#@param $3 Número de disco
|
||||
#@param $4 Número de particion
|
||||
#@param $5 Protocolo (UNICAST, por defecto, MULTICAST o TORRENT)
|
||||
#@param $6 Opciones del protocolo
|
||||
#@exception OG_ERR_FORMAT 1 formato incorrecto.
|
||||
#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados.
|
||||
#@exception OG_ERR_PARTITION 3 # Error en partición de disco.
|
||||
#@exception OG_ERR_LOCKED 4 partición bloqueada por otra operación.
|
||||
#@exception OG_ERR_IMAGE 5 error al restaurar la imagen del sistema.
|
||||
#@exception OG_ERR_IMGSIZEPARTITION 30 Tamaño de la particion es menor al tamaño de la imagen.
|
||||
#@exception OG_ERR_NOTCACHE No existe cache -15-
|
||||
#@exception OG_ERR_CACHESIZE Tamaño de la paticion menor al archivo a descargar -16-
|
||||
#@version 1.0.1 - Separación en protocolos de transferencia y postconfiguracion
|
||||
#@author Antonio J. Doblas Viso. Universidad de Málaga
|
||||
#@date 2011-05-11
|
||||
#@version 1.0.1 - Separación de los ficheros-log para ser gestionado por el httpd-log
|
||||
#@author Antonio J. Doblas Viso. Universidad de Málaga
|
||||
#@date 2011-05-11
|
||||
#@version 1.0.2 - Logica basada en fichero de configuracion engine.cfg
|
||||
#@author Antonio J. Doblas Viso. Universidad de Málaga
|
||||
#@date 2012-01-11
|
||||
#@version 1.0.5 - Renominación del script como "deployImage".
|
||||
#@author Antonio J. Doblas Viso y Ramón M. Gómez.
|
||||
#@date 2013-12-04
|
||||
#@version 1.0.6 - Se añade la gestión de errores de la CACHE cuando en el engine.cfg se define RESTOREPROTOCOLNOCACHE=NONE.
|
||||
#@author Antonio J. Doblas Viso.
|
||||
#@date 2015-02-23
|
||||
#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario
|
||||
#@author Irina Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2015-06-16
|
||||
#@version 1.1 - Control de errores en transferencia multicast (ticket #781)
|
||||
#@author Irina Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2017/04/20
|
||||
#**/
|
||||
|
||||
|
||||
#Descripcion:
|
||||
# Si Repositorio es el global (REPO) realiza un deploy.
|
||||
# Si Repositorio es local (CACHE) realiza un restoreImage CACHE
|
||||
# El deploy, si detecta que el cliente no tiene una CACHE o no tiene espacio suficiente consulta el engine.cfg RESTOREPROTOCOLNOCACHE
|
||||
|
||||
|
||||
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -lt 4 ]; then
|
||||
ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO imagen ndisco nparticion [ UNICAST-DIRECT|UNICAST|UNICAST-CACHE|MULTICAST-DIRECT|MULTICAST|MULTICAST-CACHE|TORRENT [opciones protocolo] ]"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Asignación de variables (repositorio y protocolo se convierten a mayúsculas).
|
||||
TIME1=$SECONDS
|
||||
REPO="${1^^}"
|
||||
REPO=${REPO:-"REPO"}
|
||||
IMGNAME="$2"
|
||||
DISK="$3"
|
||||
PART="$4"
|
||||
PROTO="${5^^}"
|
||||
PROTO="${PROTO:-"UNICAST"}"
|
||||
PROTOOPT="$6"
|
||||
# Unidad organizativa.
|
||||
[ "$ogunit" != "" ] && OGUNIT="$ogunit"
|
||||
|
||||
#Load engine configurator from engine.cfg file.
|
||||
#Carga el configurador del engine desde el fichero engine.cfg
|
||||
[ -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 " " > $OGLOGCOMMAND
|
||||
[ "$(ogGetCaller)" == "EjecutarScript" ] || echo -n "" > $OGLOGSESSION
|
||||
|
||||
# Registro de inicio de ejecución
|
||||
ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*"
|
||||
|
||||
# Si el origen(pariticion) esta bloqueada salir.
|
||||
ogIsLocked $DISK $PART && exit $(ogRaiseError session $OG_ERR_LOCKED "$MSG_PARTITION, $DISK $PART"; echo $?)
|
||||
|
||||
ogEcho log session "$MSG_HELP_ogUnmount $DISK $PART"
|
||||
ogUnmount $DISK $PART 2>/dev/null
|
||||
|
||||
# Valor por defecto para el repositorio.
|
||||
if [ "$REPO" == "$(ogGetIpAddress)" -o "$REPO" == "CACHE" ]; then
|
||||
MODE="CACHE"
|
||||
else
|
||||
ogCheckIpAddress "$REPO"
|
||||
if [ $? == 0 -o "$REPO" == "REPO" ]; then
|
||||
# Si falla el cambio -> salimos con error repositorio no valido
|
||||
ogChangeRepo $REPO ${OGUNIT} || exit $(ogRaiseError $OG_ERR_NOTFOUND "$REPO $OGUNIT"; echo $?)
|
||||
MODE="REPO"
|
||||
fi
|
||||
fi
|
||||
|
||||
#Informacioin previa de la imagen
|
||||
IMGOS=$(ogGetImageInfo `ogGetPath $MODE $IMGNAME.img`)
|
||||
case $? in
|
||||
0) ;;
|
||||
1) ogRaiseError session $OG_ERR_NOTFOUND "$REPO $2" || exit $? ;;
|
||||
5) ogRaiseError session $OG_ERR_IMAGEFILE "$REPO $2" || exit $? ;;
|
||||
*) ogRaiseError session $OG_ERR_GENERIC || exit $? ;;
|
||||
esac
|
||||
IMGSIZE=$(ls -s `ogGetPath $MODE $IMGNAME.img`| cut -f1 -d" ")
|
||||
|
||||
ogEcho log session "[1] REPO=$REPO IMG-FILE=$IMGNAME.img SIZE=$IMGSIZE (KB) METADATA=$IMGOS"
|
||||
|
||||
# Procesar repositorio.
|
||||
case "$MODE" in
|
||||
CACHE) # Repositorio en caché local.
|
||||
NEXTOPERATION=CACHE
|
||||
;;
|
||||
REPO) # Repositorio remoto por defecto.
|
||||
case "$PROTO" in
|
||||
MULTICAST-DIRECT)
|
||||
NEXTOPERATION=MULTICAST
|
||||
;;
|
||||
UNICAST-DIRECT)
|
||||
NEXTOPERATION=UNICAST
|
||||
;;
|
||||
|
||||
# Si protocolo es torrent|torrent-cache o multicast|multicast-cache
|
||||
TORRENT|TORRENT-CACHE|MULTICAST|MULTICAST-CACHE|UNICAST|UNICAST-CACHE)
|
||||
# Eliminamos CACHE o DIRECT
|
||||
PROTO=${PROTO%%-*}
|
||||
ogEcho log session "[2] updateCache "$REPO" \"/$IMGNAME.img\" $PROTO $PROTOOPT"
|
||||
TIME2=$SECONDS
|
||||
updateCache "$REPO" "/$IMGNAME.img" "$PROTO" "$PROTOOPT"
|
||||
RETVAL=$?
|
||||
TIME2=$[SECONDS-TIME2]
|
||||
ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL updateCache $[TIME2/60]m $[TIME2%60]s"
|
||||
case $RETVAL in
|
||||
0)
|
||||
ogEcho log session "[50] updateCache (OK)"
|
||||
NEXTOPERATION=CACHE
|
||||
;;
|
||||
15|16)
|
||||
# no se permite usar la cache (no existe(15) o no espacio sufiente (16). Se consulta engine.cfg para RESTOREPROTOCOLNOCACHE [ multicast unicast none ]
|
||||
ogEcho log session "[50] $MSG_ERR_NOTCACHE ; $MSG_ERR_CACHESIZE "
|
||||
ogEcho log session "[50] $MSG_SCRIPTS_CHECK_ENGINE: RESTOREPROTOCOLNOTCACHE=$RESTOREPROTOCOLNOTCACHE "
|
||||
case "$RESTOREPROTOCOLNOTCACHE" in
|
||||
MULTICAST)
|
||||
case "$PROTO" in
|
||||
MULTICAST) NEXTOPERATION=MULTICAST ;;
|
||||
TORRENT) NEXTOPERATION=UNICAST ;;
|
||||
UNICAST) NEXTOPERATION=UNICAST ;;
|
||||
esac
|
||||
;;
|
||||
UNICAST)
|
||||
NEXTOPERATION=UNICAST
|
||||
;;
|
||||
NONE)
|
||||
case $RETVAL in
|
||||
15)
|
||||
ogEcho log session "[100] $MSG_ERR_NOTCACHE"
|
||||
ogRaiseError session $OG_ERR_NOTCACHE "NOT CACHE"
|
||||
exit $?
|
||||
;;
|
||||
16)
|
||||
ogEcho log session "[100] $MSG_ERR_CACHESIZE "
|
||||
ogRaiseError session $OG_ERR_CACHESIZE "CACHE FULL"
|
||||
exit $?
|
||||
;;
|
||||
esac # del segundo RETAVAL
|
||||
;;
|
||||
esac # del RESTOREPROTOCOLNOTCACHE
|
||||
;;
|
||||
57|60)
|
||||
# Time-out en la transferencia multicast (El mensaje de error está enviado)
|
||||
exit $RETVAL
|
||||
;;
|
||||
*)
|
||||
# Error desconocido
|
||||
exit $RETVAL
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*) # Error: protocolo desconocido.
|
||||
ogRaiseError session $OG_ERR_FORMAT "$MSG_ERR_FORMAT, $PROTO"
|
||||
exit $?
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
*) # Error: repositorio desconocido.
|
||||
ogRaiseError session $OG_ERR_FORMAT "$MSG_ERR_FORMAT, $REPO"
|
||||
exit $?
|
||||
;;
|
||||
esac
|
||||
|
||||
TIME3=$SECONDS
|
||||
|
||||
# Obtener parámetros de restauración.
|
||||
case "$NEXTOPERATION" in
|
||||
CACHE)
|
||||
PARAMS="CACHE $IMGNAME $DISK $PART" ;;
|
||||
UNICAST)
|
||||
PARAMS="$REPO $IMGNAME $DISK $PART" ;;
|
||||
MULTICAST)
|
||||
PARAMS="$REPO $IMGNAME $DISK $PART $PROTO $PROTOOPT" ;;
|
||||
esac
|
||||
|
||||
# Si existe, ejecuta script personalizado "restoreImageCustom"; si no, llama al genérico "restoreImage".
|
||||
if which restoreImageCustom &>/dev/null; then
|
||||
ogEcho log session "[55] $MSG_HELP_ogRestoreImage: restoreImageCustom $PARAMS"
|
||||
restoreImageCustom $PARAMS
|
||||
else
|
||||
ogEcho log session "[55] $MSG_HELP_ogRestoreImage: restoreImage $PARAMS"
|
||||
restoreImage $PARAMS
|
||||
fi
|
||||
RETVAL=$?
|
||||
|
||||
# Mostrar resultados.
|
||||
RESUMERESTOREIMAGE=$(grep -m 1 "Total Time:" $OGLOGCOMMAND)
|
||||
ogEcho log session " [ ] $RESUMERESTOREIMAGE "
|
||||
# Si la transferencia ha dado error me salgo.
|
||||
if [ $RETVAL -ne 0 ] ; then
|
||||
ogRaiseError session $OG_ERR_IMAGE "$REPO $IMGNAME" 2>&1
|
||||
# Muestro registro de fin de ejecución si no viene de Ejecutar Script
|
||||
[ "$(ogGetCaller)" == "EjecutarScript" ] || ogEcho log session "$MSG_INTERFACE_END $OG_ERR_IMAGE"
|
||||
exit $OG_ERR_IMAGE
|
||||
fi
|
||||
TIME3=$[SECONDS-TIME3]
|
||||
ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL : $[TIME3/60]m $[TIME3%60]s"
|
||||
|
||||
# Si existe, ejecuta script personalizado de postconfiguración "configureOsCustom"; si no, llama al genérico "configureOs".
|
||||
if which configureOsCustom &>/dev/null; then
|
||||
ogEcho log session "[90] configureOsCustom"
|
||||
configureOsCustom "$DISK" "$PART" "$REPO" "$IMGNAME"
|
||||
else
|
||||
ogEcho log session "[90] $MSG_SCRIPTS_OS_CONFIGURE "
|
||||
configureOs "$DISK" "$PART"
|
||||
fi
|
||||
|
||||
TIME=$[SECONDS-TIME1]
|
||||
ogEcho log session "[100] $MSG_SCRIPTS_TIME_TOTAL $[TIME/60]m $[TIME%60]s"
|
||||
|
||||
# Registro de fin de ejecución
|
||||
# Si se ha llamado desde ejecutar script no lo muestro para no repetir.
|
||||
if [ "$(ogGetCaller)" != "EjecutarScript" ] ; then
|
||||
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
|
||||
exit $RETVAL
|
||||
fi
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
#!/bin/bash
|
||||
# Scirpt de ejemplo para formatear un sistema de archivos.
|
||||
# Nota: se usa como base para el programa de formateo de OpenGnsys Admin).
|
||||
|
||||
TIME1=$SECONDS
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -ne 2 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Desmontar y formatear el sistema de archivos.
|
||||
echo "[5] Desmontando sistema de archivos"
|
||||
ogUnmountFs "$@" || exit $?
|
||||
echo "[20] Formateando sistema de archivos"
|
||||
ogFormatFs "$@"
|
||||
|
||||
TIME=$[SECONDS-TIME1]
|
||||
echo "[100] Duración de la operación $[TIME/60]m $[TIME%60]s"
|
|
@ -0,0 +1,81 @@
|
|||
#!/bin/bash
|
||||
# generateMenuDefault - Crea fichero con la página web de inicio del cliente
|
||||
# con información de red y de los sistemas operativos instalados,
|
||||
# crea fichero con información del contenido de la caché local.
|
||||
|
||||
|
||||
DEVICE=${DEVICE:-"eth0"}
|
||||
source /tmp/net-$DEVICE.conf
|
||||
FILEINFOHTML=$OGLOG/`ogGetIpAddress`.info.html
|
||||
FILEINFOCACHE=$OGLOG/`ogGetIpAddress`.cache.txt
|
||||
ogMountCache 2>/dev/null
|
||||
CACHECONTENIDO="ls -m $OGCAC/$OGIMG 2>/dev/null"
|
||||
|
||||
SPEED=$(LANG=C ethtool $DEVICE 2>/dev/null | awk '$1~/Speed/ {print $2}')
|
||||
case "${SPEED,,}" in
|
||||
1000mb/s) ;;
|
||||
100mb/s) SPEED="<font color=\"blue\">$SPEED</font>" ;;
|
||||
10mb/s) SPEED="<font color=\"grey\">$SPEED</font>" ;;
|
||||
*) SPEED="<font color=\"red\">$SPEED</font>" ;;
|
||||
esac
|
||||
DUPLEX=$(LANG=C ethtool $DEVICE 2>/dev/null | awk '$1~/Duplex/ {print $2}')
|
||||
case "${DUPLEX,,}" in
|
||||
full) ;;
|
||||
*) DUPLEX="<font color=\"red\">$DUPLEX</font>"
|
||||
esac
|
||||
|
||||
CACHESIZEFREE=$(ogGetFreeSize `ogFindCache`)
|
||||
if [ $CACHESIZEFREE == 0 ]; then
|
||||
echo '0.MB,' > $FILEINFOCACHE
|
||||
else
|
||||
expr $CACHESIZEFREE / 1024 > $FILEINFOCACHE 2>/dev/null && echo '.MB,' >> $FILEINFOCACHE
|
||||
fi
|
||||
|
||||
# Crear menú por defecto.
|
||||
cat > $FILEINFOHTML << EOT
|
||||
<div align="center" style="font-family: Arial, Helvetica, sans-serif;">
|
||||
<p style="color:#999999; font-size: 16px; margin: 2em;">
|
||||
|
||||
<table border="1" width="100%">
|
||||
<tr>
|
||||
<td rowspan="2"><p align="left"><img border="0" src="../images/iconos/logoopengnsys.png"><p> </td>
|
||||
<td> $MSG_HOSTNAME </td> <td> $MSG_IPADDR </td> <td> $MSG_MACADDR </td> <td> $MSG_SPEED </td> <td> $MSG_DUPLEX </td> </tr>
|
||||
<tr> <td>$HOSTNAME </td> <td> $(ogGetIpAddress) </td> <td> $(ogGetMacAddress) </td> <td> $SPEED </td> <td> $DUPLEX </td> </tr>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<h1>$MSG_MENUTITLE</h1>
|
||||
EOT
|
||||
|
||||
# Si existe el fichero de configuración creado por el script getConfiguration, ...
|
||||
cfgfile=/tmp/getconfig
|
||||
if [ -f $cfgfile ]; then
|
||||
# Tomar los datos del fichero.
|
||||
awk -v boot="$MSG_BOOT" '
|
||||
{ n=split($0,sep,";");
|
||||
for (i=1; i<n; i++) {
|
||||
split (sep[i],dua,":");
|
||||
if (dua[5]!="" && dua[5]!="DATA") {
|
||||
printf ("<p><a href=\"command:bootOs %s %s\">%s %s (%s, %s)</a></p>\n",
|
||||
dua[1],dua[2],boot,dua[5],dua[1],dua[2]);
|
||||
}
|
||||
}
|
||||
}' $cfgfile >>$FILEINFOHTML
|
||||
else
|
||||
# Si no, obtener los datos de los discos.
|
||||
for ((d=1; d<=$(ogDiskToDev | wc -w); d++)); do
|
||||
for ((p=1; p<=$(ogGetPartitionsNumber $d); p++)); do
|
||||
VERSION=$(ogGetOsVersion $d $p 2>/dev/null | cut -f2 -d:)
|
||||
[ -n "$VERSION" ] && echo "<p><a href=\"command:bootOs $d $p\">$MSG_BOOT $VERSION ($d, $p)</a></p>" >>$FILEINFOHTML
|
||||
done
|
||||
done
|
||||
fi
|
||||
# Añadir opción de apagado.
|
||||
cat >> $FILEINFOHTML << EOT
|
||||
<p><a href="command:poweroff">$MSG_POWEROFF</a></p>
|
||||
</div>
|
||||
EOT
|
||||
|
||||
# Crear contenido de la caché.
|
||||
eval $CACHECONTENIDO >> $FILEINFOCACHE
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
ogGetFsType "$@"
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
ogGetIpAddress "$@"
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
ogGetOsVersion "$@"
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
#!/bin/bash
|
||||
# Scirpt de iniciación de la caché local de disco.
|
||||
# Nota: se usa como base para el programa de configuración de equipos de OpenGnsys Admin).
|
||||
# Formato: initCache [int_ndisk [int_npart]] {-1 | 0 | int_size} [NOMOUNT]
|
||||
# Versión: 0.9.1, 2009/03/17, - Ramón Gómez, Univ. Sevilla - Versión inicial.
|
||||
# Versión: 0.9.2, 2010/07/27, - Ramón Gómez, Univ. Sevilla - redefinir parámetro.
|
||||
# Version: 1.0.5, 2012/09/18, - Univ. Huelva - Nuevo parametro para indicar el disco donde se creara la CACHE, si no se indica, se usa 1
|
||||
# Version: 1.1.0, 2016/06/16, - Ramón Gómez, Univ. Sevilla - Nuevos parámetros: partición de caché (por defecto, 4) y cadena opcional "NOMOUNT" para dejar la caché sin montar.
|
||||
|
||||
TIME1=$SECONDS
|
||||
PROG="$(basename $0)"
|
||||
EXECFORMAT="$PROG [int_ndisk [int_npart]] {-1 | 0 | int_size} [NOMOUNT]"
|
||||
|
||||
# Si el último parámetro es la cadena "NOMOUNT", marcar para no montar y descartarlo.
|
||||
if [[ "${*^^}" =~ \ NOMOUNT$ ]]; then
|
||||
MOUNT=0
|
||||
PARAMS=$[$#-1]
|
||||
else
|
||||
MOUNT=1
|
||||
PARAMS=$#
|
||||
fi
|
||||
# Tomar valores según el número de parámetros restantes.
|
||||
case $PARAMS in
|
||||
1) # Por defecto, disco 1 partición 4.
|
||||
NDISK=1
|
||||
NPART=4
|
||||
SIZE=$1
|
||||
;;
|
||||
2) # Elegir disco y partición 4 por defecto.
|
||||
NDISK=$1
|
||||
NPART=4
|
||||
SIZE=$2
|
||||
;;
|
||||
3) # Elegir disco y partición.
|
||||
NDISK=$1
|
||||
NPART=$2
|
||||
SIZE=$3
|
||||
;;
|
||||
*) # Error de formato.
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT"
|
||||
exit $?
|
||||
;;
|
||||
esac
|
||||
|
||||
# Si disco o partición no son mayores o iguales que 1, error.
|
||||
if [ -n "${NDISK//[-0-9]/}${NPART//[-0-9]/}" ] || [ $NDISK -lt 1 ] || [ $NPART -lt 1 ] ; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT"
|
||||
exit $?
|
||||
fi
|
||||
# Si tamaño no es numérico o tamaño<-1, error.
|
||||
if [ -n "${SIZE//[-0-9]/}" ] || [ $SIZE -lt -1 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT"
|
||||
exit $?
|
||||
fi
|
||||
# Si tamaño=0, no hacer nada.
|
||||
if [ $SIZE -eq 0 ]; then
|
||||
echo "No modificar la caché local."
|
||||
exit
|
||||
fi
|
||||
# Si tamaño=-1, borrar caché.
|
||||
if [ $SIZE -eq -1 ]; then
|
||||
echo "[10] Trabajar sin caché local."
|
||||
ogUnmountCache 2>/dev/null
|
||||
ogDeleteCache
|
||||
else
|
||||
# Si la caché actual está definida en otro disco y partición, se elimina.
|
||||
if [ -n "$(ogFindCache)" -a "$NDISK $NPART" != "$(ogFindCache)" ]; then
|
||||
echo "[10] Detectada otra caché, eliminarla"
|
||||
ogUnmountCache 2>/dev/null
|
||||
ogDeleteCache
|
||||
fi
|
||||
# Tomamos el tamaño actual. Si no existe cache será 0.
|
||||
OLDSIZE=$(ogGetCacheSize 2>/dev/null) || OLDSIZE=0
|
||||
|
||||
# Error si tamaño definido no es >0.
|
||||
if [ ! $SIZE -gt 0 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_ERR_FORMAT: !($SIZE>0)"
|
||||
exit $?
|
||||
fi
|
||||
# Si no existe caché o si cambia su tamaño, crearla.
|
||||
CACHESIZE=$(ogGetCacheSize 2>/dev/null)
|
||||
if [ "$SIZE" != "$CACHESIZE" ]; then
|
||||
echo "[10] Crar partición de caché local."
|
||||
ogUnmountCache 2>/dev/null
|
||||
ogCreateCache $NDISK $NPART $SIZE
|
||||
ogUpdatePartitionTable $NDISK
|
||||
fi
|
||||
# Si caché no montada y no formateada o cambia el tamaño: formatear.
|
||||
CACHE=$(ogFindCache) || exit $?
|
||||
if ! ogIsFormated $CACHE || [ $SIZE -ne $OLDSIZE ]; then
|
||||
echo "[50] Formatear caché local."
|
||||
ogFormatCache
|
||||
fi
|
||||
echo "[70] Comprobar montaje de caché local."
|
||||
ogMountCache 2>/dev/null
|
||||
# Si error al montar, chequear sistema de archivos y volver a montar.
|
||||
if [ $? != 0 ]; then
|
||||
echo "[80] Comprobar consistencia y volver a montar caché local."
|
||||
ogCheckFs $CACHE
|
||||
ogMountCache || exit $?
|
||||
fi
|
||||
# Dejar desmontada la caché si se ha solicitado.
|
||||
if [ $MOUNT == 0 ]; then
|
||||
echo "[90] Dejar desmontada la caché local."
|
||||
ogUnmountCache 2>/dev/null
|
||||
fi
|
||||
fi
|
||||
# Duración del proceso.
|
||||
TIME=$[SECONDS-TIME1]
|
||||
echo "[100] Duración de la operación $[TIME/60]m $[TIME%60]s"
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
#!/bin/bash
|
||||
|
||||
#/**
|
||||
# installOfflineMode
|
||||
#@brief Prepara el equipo cliente para el modo offline.
|
||||
#@param no
|
||||
#@return
|
||||
#@exception OG_ERR_NOTFOUND Fichero o dispositivo no encontrado.
|
||||
#@exception OG_ERR_NOTCACHE No existe cache.
|
||||
#@author Irina Gomez. ETSII. Universidad de Sevilla
|
||||
#@date 2013/12/5
|
||||
#*/ ##
|
||||
|
||||
PROG="$(basename $0)"
|
||||
if [ "$*" == "help" ]; then
|
||||
ogHelp "$PROG $MSG_HELP_installOfflineMode" \
|
||||
"$PROG [ no param ]"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ogEcho log session "$MSG_HELP_installOfflineMode"
|
||||
# Cargamos las variables de entorno.
|
||||
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
|
||||
DIRTFTP="/opt/oglive/tftpboot"
|
||||
DIROGCLIENT="$DIRTFTP/ogclient"
|
||||
# Comprobamos que el DIROGCLIENT esta montado desde repo
|
||||
df |grep "$(ogGetRepoIp).*$DIRTFTP" &>/dev/null || ogRaiseError $OG_ERR_NOTFOUND "REPO OGclient" || exit $?
|
||||
|
||||
# Copiamos el kernel y el initrd.
|
||||
ogEcho log session " [10] updateBootCache"
|
||||
updateBootCache || ogRaiseError $OG_ERR_NOTCACHE || exit $?
|
||||
|
||||
# Creamos los dir necesarios.
|
||||
ogEcho log session " [40] mkdir -p $OGCAC/{ogclient, menus, log}."
|
||||
[ -d $OGCAC/menus/images/iconos ] || mkdir -p $OGCAC/menus/images/iconos
|
||||
[ -d $OGCAC/ogclient ] || mkdir -p $OGCAC/ogclient
|
||||
[ -d $OGCAC/log ] || mkdir -p $OGCAC/log
|
||||
[ -d $OGCAC/opt/opengnsys/images ] || mkdir -p $OGCAC/opt/opengnsys/images
|
||||
|
||||
# Comparamos el cliente en el server y en cache
|
||||
ogEcho log session " [60] cp $DIROGCLIENT/ogclient.sqfs $OGCAC/ogclient/"
|
||||
SERVEROGCLIENT=$(cat $DIROGCLIENT/ogclient.sqfs.sum 2>/dev/null)
|
||||
CACHEOGCLIENT=$(cat $OGCAC/ogclient/ogclient.sqfs.sum 2>/dev/null)
|
||||
|
||||
if [ "$CACHEOGCLIENT" != "$SERVEROGCLIENT" ]; then
|
||||
cp $DIROGCLIENT/ogclient.sqfs $OGCAC/ogclient/
|
||||
cp $DIROGCLIENT/ogclient.sqfs.sum $OGCAC/ogclient/
|
||||
fi
|
||||
|
||||
# Si se ha generado el menu de inicio lo copiamos a cache.
|
||||
IPCLIENT=$(ogGetIpAddress)
|
||||
MENU=$OGLOG/$IPCLIENT.info.html
|
||||
ICONO="images/iconos/logoopengnsys.png"
|
||||
[ -f $MENU ] || generateMenuDefault
|
||||
ogEcho log session " [90] cp $MENU $OGCAC/menus/$IPCLIENT.html"
|
||||
cp $MENU $OGCAC/menus/$IPCLIENT.html
|
||||
sed -i s/"..\/images"/"images"/g $OGCAC/menus/$IPCLIENT.html
|
||||
wget --no-check-certificate https://$(ogGetRepoIp)/opengnsys/$ICONO -O $OGCAC/menus/$ICONO
|
||||
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
#!/bin/bash
|
||||
# #/**
|
||||
# launchOgagentInstaller ndisk npart [windowsadmin]
|
||||
#@brief Scheduling OpenGnsys Agent installation at next boot or administrator session.
|
||||
#@param integer ndsik disk number
|
||||
#@param integer npart partition number
|
||||
#@param string windowsadmin administrator user (only for Windows)
|
||||
#@author Ramón M. Gómez, ETSII Univ. Sevilla
|
||||
#@version 1.1.0 - Initial version.
|
||||
#@date 2018-02-16
|
||||
#*/ ##
|
||||
|
||||
# Global variables.
|
||||
PROG="$(basename "$0")"
|
||||
if which curl &>/dev/null; then
|
||||
DOWNLOAD="curl -k -f --connect-timeout 1 -o"
|
||||
else
|
||||
DOWNLOAD="wget --no-check-certificate -T 1 -O"
|
||||
fi
|
||||
|
||||
# Show help.
|
||||
if [ "$*" == "help" ]; then
|
||||
echo "$PROG: scheduling OpenGnsys Agent installation."
|
||||
echo "Format: $PROG ndisk npart [windowsadmin]"
|
||||
exit 0
|
||||
fi
|
||||
# Error control.
|
||||
if ! typeset -Fp ogRaiseError &>/dev/null; then
|
||||
echo "$PROG: it can only be executed by an ogLive client." >&2
|
||||
exit 1
|
||||
fi
|
||||
[ $# == 2 -o $# == 3 ] || ogRaiseError $OG_ERR_FORMAT "$PROG ndisk npart [adminuser]" || exit $OG_ERR_FORMAT
|
||||
MNTDIR=$(ogMount "$1" "$2") || exit $?
|
||||
OGVERSION=$($DOWNLOAD - https://$(ogGetServerIp)/opengnsys/rest/info 2>/dev/null | jq -r .version)
|
||||
[ -n "$OGVERSION" ] || ogRaiseError $OG_ERR_NOTFOUND "GET /rest/info" || exit $OG_ERR_NOTFOUND
|
||||
|
||||
case "$(ogGetOsType $1 $2)" in
|
||||
Windows) # OGAgent for Windows.
|
||||
HIVE="$(ogGetHivePath "$MNTDIR" "$3")"
|
||||
[ -n "$HIVE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 $3/NTUSER.DAT" || exit $OG_ERR_NOTFOUND
|
||||
# Downloading OGAgent installer for Windows.
|
||||
OGAGENTFILE="OGAgentSetup-${OGVERSION/pre/}.exe"
|
||||
TMPDIR="$(ogGetPath "$MNTDIR/Windows/Temp")"
|
||||
if ogListSoftware $1 $2 | grep -qi "opengnsys agent"; then
|
||||
echo "OGAgent for Windows is already installed, you need to uninstall it before re-install."
|
||||
else
|
||||
if eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null; then
|
||||
# Run once OGAgent Installer.
|
||||
if hivexsh -w << EOT 2>/dev/null; then
|
||||
load $HIVE
|
||||
cd \\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce
|
||||
setval 1
|
||||
Install OGAgent
|
||||
string:C:\\Windows\\Temp\\$OGAGENTFILE /S /server $(ogGetServerIp)
|
||||
commit
|
||||
close
|
||||
exit
|
||||
EOT
|
||||
echo "Scheduled OGAgent installation after \"$3\" logon"
|
||||
echo " (for connection problems, check configuration file)."
|
||||
else
|
||||
ogRaiseError $OG_ERR_NOTWRITE "$1 $2 .../$3/NTUSER.DAT"
|
||||
exit $OG_ERR_NOTWRITE
|
||||
fi
|
||||
else
|
||||
ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /Windows/Temp/$OGAGENTFILE"
|
||||
exit $OG_ERR_NOTFOUND
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
Linux) # OGAgent for Linux (only deb and redhat-based backages; TODO suse-based package).
|
||||
if ogListSoftware $1 $2 | grep -qi "ogagent"; then
|
||||
echo "OGAgent for Linux is already installed, you need to uninstall it before re-install."
|
||||
else
|
||||
SYSTEMDDIR="$MNTDIR/lib/systemd"
|
||||
[ -d "$SYSTEMDDIR" -a -d "${SYSTEMDDIR/lib/etc}" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 systemd" || exit $OG_ERR_NOTFOUND
|
||||
# Downloading OGAgent installer for Linux.
|
||||
if [ -e $MNTDIR/etc/debian_version ]; then # Debian-based
|
||||
OGAGENTFILE="ogagent_${OGVERSION/pre/}_all.deb"
|
||||
CODE="if ! dpkg -l ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then apt-get update; apt-get install -y /var/tmp/$OGAGENTFILE; fi"
|
||||
fi
|
||||
if [ -e $MNTDIR/etc/redhat-release ]; then # RedHat-based
|
||||
OGAGENTFILE="ogagent-${OGVERSION/pre/}-1.noarch.rpm"
|
||||
CODE="if ! rpm -q ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then yum install -y /var/tmp/$OGAGENTFILE; fi"
|
||||
fi
|
||||
[ -n "$OGAGENTFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 ogagent" || exit $OG_ERR_NOTFOUND
|
||||
TMPDIR="$MNTDIR/var/tmp"
|
||||
if eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null; then
|
||||
# Creating systemd script.
|
||||
cat << EOT > $SYSTEMDDIR/systemd-launchogagent
|
||||
#!/bin/bash
|
||||
[ $EUID = 0 ] || exit 4
|
||||
start() {
|
||||
$CODE
|
||||
sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg
|
||||
service ogagent start
|
||||
}
|
||||
restart() {
|
||||
service ogagent stop
|
||||
if [ -f /var/tmp/$OGAGENTFILE ]; then
|
||||
apt-get update
|
||||
apt-get install -y --reinstall /var/tmp/$OGAGENTFILE
|
||||
fi
|
||||
sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg
|
||||
service ogagent start
|
||||
}
|
||||
|
||||
case "\$1" in
|
||||
start|restart) "\$1" ;;
|
||||
esac
|
||||
EOT
|
||||
chmod +x $SYSTEMDDIR/systemd-launchogagent
|
||||
# Creating systemd service.
|
||||
cat << EOT > $SYSTEMDDIR/system/launchogagent.service
|
||||
[Unit]
|
||||
Description=Installing and configuring OGAgent
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
ExecStart=/lib/systemd/systemd-launchogagent start
|
||||
TimeoutStartSec=5min
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOT
|
||||
ln -fs /lib/systemd/system/launchogagent.service \
|
||||
${SYSTEMDDIR/lib/etc}/system/multi-user.target.wants
|
||||
echo "Scheduled OGAgent installation at next boot"
|
||||
echo " (process will be executed in the background, do not shutdown until finish)."
|
||||
else
|
||||
ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /var/tmp/$OGAGENTFILE"
|
||||
exit $OG_ERR_NOTFOUND
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
MacOS) # OGAgent for macOS (TODO).
|
||||
echo "OGAgent installer for macOS is not implemented yet."
|
||||
;;
|
||||
*) # OS not detected or OGAgent not implemented.
|
||||
ogRaiseError $OG_ERR_NOTOS "$1 $2"
|
||||
exit $OG_ERR_NOTOS
|
||||
;;
|
||||
esac
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
#!/bin/bash
|
||||
# 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
|
||||
|
||||
PROG=$(basename "$0")
|
||||
if [ $# -ne 0 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG "
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Directorio del servidor donde se exportan los ficheros de registro.
|
||||
SERVERLOGDIR=$(mount | awk -v d=$OGLOG '
|
||||
BEGIN {FS="[: ]"}
|
||||
{if ($4==d) dir=$2}
|
||||
END {print dir}')
|
||||
|
||||
# Fichero de listado: hard-IP
|
||||
HARDFILE="hard-$(ogGetIpAddress)"
|
||||
# Redirigir salida al fichero de listado.
|
||||
ogListHardwareInfo>$OGLOG/$HARDFILE || exit $?
|
||||
# Salida: camino del fichero de listado en el servidor de repositorio.
|
||||
#echo $SERVERLOGDIR/$HARDFILE
|
||||
echo $OGLOG/$HARDFILE
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
ogListPartitions "$@" | sed 's/\(EMPTY:0 \)*$//'
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
ogListPrimaryPartitions "$@"
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
#!/bin/bash
|
||||
# Scirpt de ejemplo para almacenear en fichero temporal el listado de software.
|
||||
# Nota: se usa como base para el programa de recogida de listado de software de OpenGnsys Admin.
|
||||
# Formato: listSoftwareInfo [-r] ndisk npart
|
||||
# -r listado reducido (sin parches de Windows)
|
||||
|
||||
PROG=$(basename "$0")
|
||||
REDUCED="no"
|
||||
if [ "$1" = "-r" ]; then
|
||||
REDUCED="yes"
|
||||
shift
|
||||
fi
|
||||
if [ $# -ne 2 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Directorio del servidor donde se exportan los ficheros de registro.
|
||||
SERVERLOGDIR=$(mount | awk -v d=$OGLOG '
|
||||
BEGIN {FS="[: ]"}
|
||||
{if ($4==d) dir=$2}
|
||||
END {print dir}')
|
||||
|
||||
# Fichero de listado: soft-IP-ndisco-npart
|
||||
SOFTFILE="soft-$(ogGetIpAddress)-$1-$2"
|
||||
# Redirigir salida al fichero de listado.
|
||||
if [ "$REDUCED" = "no" ]; then
|
||||
ogListSoftware "$1" "$2" >$OGLOG/$SOFTFILE || exit $?
|
||||
else
|
||||
ogListSoftware "$1" "$2" | egrep -v "\(KB[0-9]{6}\)" >$OGLOG/$SOFTFILE || exit $?
|
||||
fi
|
||||
# Salid: camino del fichero de listado en el servidor de repositorio.
|
||||
#echo $SERVERLOGDIR/$SOFTFILE
|
||||
echo $OGLOG/$SOFTFILE
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
#!/bin/bash
|
||||
# Scirpt de ejemplo para iniciar el browser del cliente con un menú predefinido
|
||||
|
||||
PROG=$(basename "$0")
|
||||
if [ $# -ne 1 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG urlmenu"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
url="$1"
|
||||
browser -qws $url
|
|
@ -0,0 +1,22 @@
|
|||
#!/bin/bash
|
||||
# Script de ejemplo para enviar eco a la consola remota al ejecutar un comando de la shell
|
||||
# Formato: remoteConsole
|
||||
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -ne 0 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG "
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Directorio del servidor donde se exportan los ficheros de registro.
|
||||
SERVERLOGDIR=$(mount | awk -v d=$OGLOG '
|
||||
BEGIN {FS="[: ]"}
|
||||
{if ($4==d) dir=$2}
|
||||
END {print dir}')
|
||||
|
||||
# Fichero de listado: hard-IP
|
||||
ECOFILE="eco-$(ogGetIpAddress)"
|
||||
# Redirigir salida al fichero de listado.
|
||||
/tmp/_hidrascript_ >$OGLOG/$ECOFILE || exit $?
|
||||
# Salida: camino del fichero de listado en el servidor de repositorio.
|
||||
echo $SERVERLOGDIR/$ECOFILE
|
|
@ -0,0 +1,106 @@
|
|||
#!/bin/bash
|
||||
#/**
|
||||
#@file restoreImage
|
||||
#@brief Script de ejemplo para restaurar una imagen.
|
||||
#@param $1 Repositorio (CACHE, REPO o dirección IP)
|
||||
#@param $2 Nombre canónico de la imagen (sin extensión)
|
||||
#@param $3 Número de disco
|
||||
#@param $4 Número de particion
|
||||
#@param $5 Protocolo (UNICAST, UNICAST-DIRECT, MULTICAST o MULTICAST-DIRECT)
|
||||
#@param $6 Opciones del protocolo
|
||||
#@exception OG_ERR_FORMAT 1 formato incorrecto.
|
||||
#@exception OG_ERR_NOTFOUND 2 cambio de repositorio: repositorio no encontrado
|
||||
#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados.
|
||||
#@exception $OG_ERR_MCASTRECEIVERFILE 57 Error en la recepción Multicast de un fichero
|
||||
#@exception $OG_ERR_PROTOCOLJOINMASTER 60 Error en la conexión de una sesión Unicast|Multicast con el Master
|
||||
#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario
|
||||
#@author Irina Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2015-06-16
|
||||
#@version 1.1 - Control de errores en transferencia multicast (ticket #781)
|
||||
#@author Irina Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2017/04/20
|
||||
#**/
|
||||
|
||||
TIME1=$SECONDS
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -lt 4 ]; then
|
||||
ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones protocolo]"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
#Load engine configurator from engine.cfg file.
|
||||
#Carga el configurador del engine desde el fichero engine.cfg
|
||||
# Valores por defecto: #IMGPROG="partclone" ; #IMGCOMP="lzop" ; #IMGEXT="img" #IMGREDUCE="TRUE"
|
||||
[ -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 " " > $OGLOGCOMMAND
|
||||
ogCheckStringInGroup "$(ogGetCaller)" "deployImage restoreImageCustom" || echo -n "" > $OGLOGSESSION;
|
||||
|
||||
ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*"
|
||||
|
||||
# Procesar parámetros de entrada
|
||||
REPO="${1^^}"
|
||||
IMGNAME="$2"
|
||||
DISK="$3"
|
||||
PART="$4"
|
||||
PROTO="${5^^}"
|
||||
PROTO=${PROTO:-"UNICAST"}
|
||||
PROTOOPT="$6"
|
||||
# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento
|
||||
if [ "${PROTO%-*}" == "MULTICAST" ] && [[ ${PROTOOPT##*:} =~ ^-?[0-9]+$ ]]; then
|
||||
[ ${MCASTWAIT:-0} -lt ${PROTOOPT##*:} ] && let MCASTWAIT=${PROTOOPT##*:}+5
|
||||
fi
|
||||
IMGTYPE="${IMGTYPE:-"img"}"
|
||||
|
||||
# Unidad organizativa
|
||||
[ "$ogunit" != "" ] && OGUNIT="$ogunit/"
|
||||
|
||||
# Si es una ip y es igual a la del equipo restaura desde cache
|
||||
[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE"
|
||||
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
|
||||
ogCheckIpAddress $REPO
|
||||
if [ $? == 0 -o $REPO == "REPO" ] ; then
|
||||
# Si falla el cambio -> salimos con error repositorio no valido
|
||||
ogChangeRepo $REPO ${OGUNIT%/} || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO $OGUNIT'; echo $?)
|
||||
REPO="REPO"
|
||||
fi
|
||||
|
||||
# Comprobar que existe la imagen del origen.
|
||||
IMGFILE=$(ogGetPath "$REPO" "$IMGNAME.$IMGTYPE")
|
||||
IMGDIR=$(ogGetParentPath "$REPO" "$IMGNAME")
|
||||
if [ "$IMGFILE" == "" -o "$IMGDIR" == "" ]; then
|
||||
ogRaiseError session $OG_ERR_NOTFOUND "$REPO, ${IMGNAME%/*}"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Procesar protocolos de transferencia.
|
||||
case "$PROTO" in
|
||||
UNICAST|UNICAST-DIRECT)
|
||||
# Restaurar la imagen.
|
||||
ogEcho log session "[40] ogRestoreImage $REPO $IMGNAME $DISK $PART UNICAST"
|
||||
ogExecAndLog command ogRestoreImage "$REPO" "$IMGNAME" "$DISK" "$PART"
|
||||
RETVAL=$?
|
||||
;;
|
||||
MULTICAST|MULTICAST-DIRECT)
|
||||
PORT=$(echo $PROTOOPT | cut -f1 -d":")
|
||||
TOOL=$(ogGetImageProgram REPO $IMGNAME)
|
||||
COMPRESS=$(ogGetImageCompressor REPO $IMGNAME)
|
||||
#TODO comprobar parametros anteriores
|
||||
ogEcho log session "[40] ogMcastReceiverPartition $DISK $PART $PORT $TOOL $COMPRESS"
|
||||
ogMcastRequest "$IMGNAME.img" "$PROTOOPT" || exit $?
|
||||
ogExecAndLog command ogMcastReceiverPartition "$DISK" "$PART" "$PORT" "$TOOL" "$COMPRESS"
|
||||
RETVAL=$?
|
||||
;;
|
||||
*) # Protocolo desconocido.
|
||||
ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones ]"
|
||||
exit $?
|
||||
esac
|
||||
|
||||
TIME=$[SECONDS-TIME1]
|
||||
ogEcho log session "[100] Duracion de la operacion $[TIME/60]m $[TIME%60]s"
|
||||
|
||||
# Código de salida del comando prinicpal de restauración.
|
||||
exit $RETVAL
|
||||
|
|
@ -1,22 +1,15 @@
|
|||
#!/bin/bash
|
||||
|
||||
cp /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.back
|
||||
cp /etc/lighttpd/conf-enabled/10-cgi.conf /etc/lighttpd/conf-enabled/10-cgi.conf.back
|
||||
|
||||
#httd-log-status
|
||||
cp /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.back
|
||||
cp /opt/opengnsys/lib/httpd/lighttpd.conf /etc/lighttpd/
|
||||
cp /opt/opengnsys/lib/httpd/10-cgi.conf /etc/lighttpd/conf-enabled/
|
||||
|
||||
chmod 755 /opt
|
||||
cp /etc/lighttpd/conf-enabled/10-cgi.conf /etc/lighttpd/conf-enabled/10-cgi.conf.back
|
||||
cp /opt/opengnsys/lib/httpd/10-cgi.conf /etc/lighttpd/conf-enabled/
|
||||
/etc/init.d/lighttpd start
|
||||
chmod 755 /opt
|
||||
mkdir -p /usr/lib/cgi-bin
|
||||
cp /opt/opengnsys/lib/httpd/* /usr/lib/cgi-bin
|
||||
/etc/init.d/lighttpd start
|
||||
|
||||
## dstat fails because /var/lib/pcp/pmns/root does not exist.
|
||||
## we work around that by starting/stopping pmcd once. When it starts, it creates the missing file.
|
||||
if [[ ! -f /var/lib/pcp/pmns/root ]]; then
|
||||
/etc/init.d/pmcd start &>/dev/null
|
||||
/etc/init.d/pmcd stop &>/dev/null
|
||||
fi
|
||||
dstat --disk --net > /tmp/bandwidth &
|
||||
|
||||
#TODO:
|
||||
dstat -dn 10 > /tmp/bandwidth &
|
||||
echo "WAITING" >> $OGLOGSESSION
|
||||
# http-log-status
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
#!/bin/bash
|
||||
|
||||
|
||||
|
||||
#Este scripts llama directamente a la función ogMcastSendFile $1 $2
|
||||
#1 path absoluto del fichero.
|
||||
#2 la session multicast.
|
||||
# ogMcastSendFile [ str_repo | int_ndisk int_npart ] /Relative_path_file sessionMulticast
|
||||
#@brief Envía un fichero por multicast ORIGEN(fichero) DESTINO(sessionmulticast)
|
||||
#@param (2 parámetros) $1 path_aboluto_fichero $2 sesionMcast
|
||||
|
||||
|
||||
|
||||
export OPENGNSYS="${OPENGNSYS:-/opt/opengnsys/client}"
|
||||
export OGBIN=$OPENGNSYS/bin
|
||||
export OGETC=$OPENGNSYS/etc
|
||||
export OGLIB=$OPENGNSYS/lib
|
||||
export OGAPI=$OGLIB/engine/bin
|
||||
export OGSCRIPTS=$OPENGNSYS/scripts
|
||||
export OGIMG=$OPENGNSYS/images
|
||||
export OGCAC=$OPENGNSYS/cache
|
||||
export OGLOG=$OPENGNSYS/log
|
||||
|
||||
for i in $OGAPI/*.lib; do
|
||||
. $i
|
||||
done
|
||||
|
||||
if [ "$engine" = "testing" ]
|
||||
then
|
||||
for i in $OGAPI/*.testing; do
|
||||
. $i
|
||||
done
|
||||
fi
|
||||
|
||||
export PATH=$PATH:/opt/opengnsys/bin
|
||||
|
||||
export OG_ERR_FORMAT=1 # Formato de ejecución incorrecto.
|
||||
export OG_ERR_NOTFOUND=2 # Fichero o dispositivo no encontrado.
|
||||
export OG_ERR_PARTITION=3 # Error en partición de disco.
|
||||
export OG_ERR_LOCKED=4 # Partición o fichero bloqueado.
|
||||
export OG_ERR_IMAGE=5 # Error al crear o restaurar una imagen.
|
||||
export OG_ERR_NOTOS=6 # Sin sistema operativo.
|
||||
export OG_ERR_NOTEXEC=7 # Programa o función no ejecutable.
|
||||
|
||||
|
||||
|
||||
# Si se solicita, mostrar ayuda.
|
||||
if [ "$*" == "help" ]; then
|
||||
ogHelp "sendFileMcast /absolute_path_file sesionMcast" \
|
||||
"sendFileMcast /opt/opengnsys/images/aula1/hd500.vmx 9000:full-duplex:239.194.17.2:70M:20:300"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# los demas errores controlados por la funcion ogMcastSendFile
|
||||
|
||||
ogMcastSendFile $1 $2
|
|
@ -0,0 +1,47 @@
|
|||
#!/bin/bash
|
||||
# #/**
|
||||
# setBootMode
|
||||
#@brief Script to configure the PXE mode to client
|
||||
#@param 1 template
|
||||
#@date 2012-02-2-9
|
||||
#@version 1.0.1 - Recoge como parametro el nombre interno de la plantilla en vez del nombre de fichero para que funcione correctamente al llamar a setclientmode y anade un nuevo parametro de modo de trabajo (0 o 1) que indica que el cambio del fichero PXE del servidor sera temporal o permanente
|
||||
#@author Juan Carlos Garcia - Univ. Zaragoza
|
||||
#@date 2015-11-17
|
||||
#*/ ##
|
||||
|
||||
#REPOIP="$(ogGetRepoIp)"
|
||||
|
||||
# Asignamos la IP del servidor de administracion que es el destino del script
|
||||
SERVERIP="$(ogGetServerIp)"
|
||||
PORT=2011
|
||||
TEMPLATE=$(grep -l "^#.* $1 *$" /opt/oglive/tftpboot/menu.lst/templates/*)
|
||||
PCNAME="$(hostname)"
|
||||
|
||||
PROG="$(basename $0)"
|
||||
if [ "$*" == "help" ]; then
|
||||
ogHelp "$PROG" "$PROG template [ 0 | 1 ] (0 - Temporary 1, - Permanent) " \
|
||||
"$PROG ogLive 1" \
|
||||
"$PROG 1hd-1partition 0"
|
||||
exit
|
||||
fi
|
||||
|
||||
|
||||
# Control básico de errores.
|
||||
if [ $# -ne 2 ]; then
|
||||
ogRaiseError $OG_ERR_FORMAT "$MSG_ERR_FORMAT: $PROG TEMPLATE_NAME [ 0 | 1 ] (0 - Temporary, 1 - Permanent)"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
if [ -z "$TEMPLATE" ]; then
|
||||
ogRaiseError $OG_ERR_NOTFOUND "$MSG_ERR_NOTFOUND: $1"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
if [ $2 != "0" ] && [ $2 != "1" ]; then
|
||||
ogRaiseError $OG_ERR_NOTFOUND "$MSG_ERR_FORMAT: modo $2 no existe"
|
||||
exit $?
|
||||
fi
|
||||
# Crea un pipe con el servidor de administracion que llama a setclientmode pasandole los parametros de nombre de plantilla, nombre PC y modo de trabajo (0 o 1)
|
||||
hose $SERVERIP $PORT --out sh -c "echo -ne SET_CLIENTMODE $1 $PCNAME $2"
|
||||
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
#!/bin/bash
|
||||
|
||||
#/**
|
||||
# updateBootCache
|
||||
#@brief acelerador arranque pxe. incorpora a la cache el initrd y el kernel.
|
||||
#@param 1
|
||||
#@param ejemplo:
|
||||
#@return
|
||||
#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15
|
||||
#@exception OG_ERR_NOTFOUND=2 # Fichero o dispositivo no encontrado.
|
||||
#@note
|
||||
#@todo:
|
||||
#@version 1.0.1 - requiere el gestor de arranque grub2dos
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2010/07/27
|
||||
#@version 1.1.0 - Permite varios ogLive dentro de subdirectorios
|
||||
#@author Irina Gómez. ETSII Universidad de Sevilla
|
||||
#@date 2017/04/27
|
||||
#@version 1.1.0 - Se permite varios ogLives en la CACHE
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga
|
||||
#@date 2017/05/31
|
||||
#@version 1.1.0 - Limpieza de codigo, control errores
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga
|
||||
#@date 2018-01-21
|
||||
#*/ ##
|
||||
|
||||
OGLIVEDIR=${oglivedir:-"ogLive"}
|
||||
OGBTFTP="/opt/oglive/tftpboot/$OGLIVEDIR"
|
||||
OGBCACHE="$OGCAC/boot/$OGLIVEDIR"
|
||||
|
||||
#control de errores
|
||||
[ -d "$OGBTFTP" ] || exit $(ogRaiseError $OG_ERR_NOTFOUND "$OGBTFTP"; echo $?)
|
||||
ogMountCache || exit $(ogRaiseError $OG_ERR_NOTCACHE "CACHE "; echo $?)
|
||||
|
||||
[ -d $OGBCACHE ] || mkdir -p $OGBCACHE
|
||||
|
||||
# comparamos los del server
|
||||
SERVERVMLINUZ=`cat ${OGBTFTP}/ogvmlinuz.sum 2>/dev/null`
|
||||
SERVERINITRD=`cat ${OGBTFTP}/oginitrd.img.sum 2>/dev/null`
|
||||
|
||||
#comparamos los de la cache
|
||||
CACHEVMLINUZ=`cat ${OGBCACHE}/ogvmlinuz.sum 2>/dev/null`
|
||||
CACHEINITRD=`cat ${OGBCACHE}/oginitrd.img.sum 2>/dev/null`
|
||||
|
||||
echo "MD5 on SERVER: $SERVERVMLINUZ $SERVERINITRD"
|
||||
echo "MD5 on CACHE: $CACHEVMLINUZ $CACHEINITRD"
|
||||
|
||||
|
||||
if [ "$CACHEVMLINUZ" != "$SERVERVMLINUZ" ]
|
||||
then
|
||||
echo "ogvmlinuz updating"
|
||||
cp "${OGBTFTP}/ogvmlinuz" "${OGBCACHE}/ogvmlinuz"
|
||||
cp "${OGBTFTP}/ogvmlinuz.sum" "${OGBCACHE}/ogvmlinuz.sum"
|
||||
DOREBOOT=true
|
||||
fi
|
||||
if [ "$CACHEINITRD" != "$SERVERINITRD" ]
|
||||
then
|
||||
echo "oginitrd updating"
|
||||
cp "${OGBTFTP}/oginitrd.img" "${OGBCACHE}/oginitrd.img"
|
||||
cp "${OGBTFTP}/oginitrd.img.sum" "${OGBCACHE}/oginitrd.img.sum"
|
||||
DOREBOOT=true
|
||||
fi
|
||||
|
||||
echo $DOREBOOT
|
||||
# [ "$DOREBOOT" == "true" ] && busybox reboot -f
|
|
@ -0,0 +1,315 @@
|
|||
#!/bin/bash
|
||||
#/**
|
||||
# updateCache
|
||||
#@brief Actualiza la cache del cliente con imagen o fichero iso.
|
||||
#@param 1 REPO Origen del fichero. -accesible por nfs-samba-
|
||||
#@param 2 str_fichero nombre del fichero a actualizar.
|
||||
#@param 3 str_protoco. TORRENT | MULTICAST | UNICAST.
|
||||
#@param 4 str_opcionesprotocolo
|
||||
#@param 4 str_opcionesupdatecache
|
||||
#@ejemplo: oneRemoteFromMaster 172.17.36.11 CACHE /imagen1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop
|
||||
#@return
|
||||
#@exception OG_ERR_FORMAT formato incorrecto.
|
||||
#@exception OG_ERR_NOTCACHE No existe cache -15-
|
||||
#@exception $OG_ERR_CACHESIZE Tamaño de la paticion menor al archivo a descargar -16-
|
||||
#@exception $OG_ERR_MCASTRECEIVERFILE Error en la recepción Multicast de un fichero -57-
|
||||
#@exception $OG_ERR_PROTOCOLJOINMASTER Error en la conexión de una sesión Unicast|Multicast con el Master -60-
|
||||
#@note
|
||||
#@todo:
|
||||
#@version 0.9.1 - integracion EAC
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2008/03/17
|
||||
#@version 0.9.2 - integracion OpenGnsys
|
||||
#@author Antonio J. Doblas Viso. Universidad de Malaga.
|
||||
#@date 2010/07/27
|
||||
#@version 1.0.1 - Control de espacio requerido
|
||||
#@author Antonio J.Doblas Viso
|
||||
#@date 2011-05-10
|
||||
#@version 2.0.1 - Imagenes sincronizadas
|
||||
#@date 2013-02-20
|
||||
#@version 1.0.5 - uso de md5 full para las transferencias torrent, en la llamada => ogUpdateCacheIsNecesary
|
||||
#@date 2014-07-09
|
||||
#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario
|
||||
#@author Irina Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2015-06-16
|
||||
#@version 1.1 - Control de errores en transferencia multicast (ticket #781)
|
||||
#@author Irina Gomez, ETSII Universidad de Sevilla
|
||||
#@date 2017/04/20
|
||||
#*/ ##
|
||||
|
||||
PROG="$(basename $0)"
|
||||
if [ $# -lt 3 ]; then
|
||||
ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG str_REPO _str_Relative_Path_OGIMG_with_/ PROTOCOLO OPCIONES_PROTOCOLO OPCIONES_UPDATECACHE"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
#Carga del configurador del engine
|
||||
[ -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 " " > $OGLOGCOMMAND
|
||||
|
||||
if ! [ "$(ogGetCaller)" == "deployImage" -o "$(ogGetCaller)" == "restoreBaseImage" -o "$(ogGetCaller)" == "restoreDiffImage" ]; then
|
||||
echo -n "" > $OGLOGSESSION;
|
||||
|
||||
# Registro de inicio de ejecución
|
||||
ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*"
|
||||
fi
|
||||
|
||||
REPOSITORIO="${1^^}"
|
||||
PROTOCOLO="${3^^}"
|
||||
OPTPROTOCOLO="$4"
|
||||
# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento
|
||||
if [ "${PROTOCOLO%-*}" == "MULTICAST" ] && [[ ${OPTPROTOCOLO##*:} =~ ^-?[0-9]+$ ]]; then
|
||||
[ ${MCASTWAIT:0} -lt ${OPTPROTOCOLO##*:} ] && let MCASTWAIT=${OPTPROTOCOLO##*:}+5
|
||||
fi
|
||||
|
||||
# Unidad organizativa.
|
||||
[ "$ogunit" != "" ] && OGUNIT="$ogunit/"
|
||||
|
||||
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
|
||||
ogCheckIpAddress $REPOSITORIO
|
||||
if [ $? == 0 -o $REPOSITORIO == "REPO" ] ; then
|
||||
# Si falla el cambio -> salimos con error repositorio no valido
|
||||
ogChangeRepo $REPOSITORIO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND $REPOSITORIO; echo $?)
|
||||
REPOSITORIO="REPO"
|
||||
fi
|
||||
REPOIP=$(ogGetRepoIp)
|
||||
ogEcho log session $REPOSITORIO $REPOIP $PROTOCOLO $OPTPROTOCOLO
|
||||
|
||||
# Si el repositorio local CACHE no existe error 15.
|
||||
if ! $(ogFindCache >/dev/null); then
|
||||
ogRaiseError session $OG_ERR_NOTCACHE "CACHE"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# comprobar si la imagen existe (.img, .img.diff o directorio)
|
||||
REPOFILE=$(ogGetPath "REPO" "/$2")
|
||||
[ -n "$REPOFILE" ] || exit $(ogRaiseError session $OG_ERR_NOTFOUND "REPO /$2"; echo $?)
|
||||
|
||||
ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_DOUPDATE"
|
||||
# Distingo si es monolitica o sincronizable
|
||||
file "$REPOFILE" | grep -i -e " BTRFS Filesystem " -e " ext4 filesystem " -e " directory" 2>&1 > /dev/null
|
||||
if [ $? == 0 ]; then
|
||||
IMGSYNC=TRUE
|
||||
# Para imagen sincronizada, si hay imagen en cache siempre protocolo = rsync.
|
||||
CACHEFILE="$(ogGetPath "CACHE" "/$2")"
|
||||
[ -n "$CACHEFILE" ] && PROTOCOLO="RSYNC"
|
||||
# Si es sincronizada tipo directorio siempre protocolo = rsync.
|
||||
[ -d $REPOFILE ] && PROTOCOLO="RSYNC" && IMGTYPE="dir"
|
||||
|
||||
# Si es imagen sincronizada siempre da distinto md5. No podemos comprobar -> actualizamos.
|
||||
RETVAL=0
|
||||
else
|
||||
# Si la imagen es monolitica y ha elegido protocolo = RSYNC salimos con error.
|
||||
[ $PROTOCOLO == "RSYNC" ] && exit $(ogRaiseError session $OG_ERR_DONTSYNC_IMAGE "REPO $2"; echo $?)
|
||||
IMGSYNC=FALSE
|
||||
ogUpdateCacheIsNecesary "$REPOSITORIO" "$2" "$PROTOCOLO"
|
||||
RETVAL=$?
|
||||
fi
|
||||
# si RETVAL=0 => actualizamos si RETVAL=1 no actaulizasmo-exit 0 || si RETVAL>2 exit 1
|
||||
[ "$RETVAL" == "1" ] && exit 0
|
||||
[ "$RETVAL" -gt "1" ] && exit $OG_ERR_UPDATECACHE
|
||||
|
||||
ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE"
|
||||
CACHESIZE=$(ogGetCacheSize)
|
||||
CACHESIZEFREE=$(ogGetFreeSize `ogFindCache`)
|
||||
FILESIZE=$(ls -sk $(ogGetPath $REPOSITORIO "$2") | cut -f1 -d" ")
|
||||
if [ "$IMGTYPE" == "dir" ]; then
|
||||
ogEcho log session " * $MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR"
|
||||
ogEcho log session " du -sk $REPOFILE"
|
||||
REALFILESIZE=$(du -sk "$REPOFILE"|awk '{print $1}')
|
||||
else
|
||||
REALFILESIZE=$(ls -l --block-size=1024 $REPOFILE | cut -f5 -d" ")
|
||||
fi
|
||||
|
||||
# La sincronizada, si existe la imagen en cache el espacio necesario
|
||||
# es la nueva menos lo que ocupa la que ya hay.
|
||||
if [ "$PROTOCOLO" == "RSYNC" ]; then
|
||||
if [ "$CACHEFILE" == "" ]; then
|
||||
CACHEFILESIZE=0
|
||||
else
|
||||
if [ "$IMGTYPE" == "dir" ]; then
|
||||
ogEcho log session " * $MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR $CACHEFILESIZE"
|
||||
ogEcho log session " du -sk $CACHEFILE"
|
||||
CACHEFILESIZE=$(du -sk $CACHEFILE |awk '{print $1}')
|
||||
else
|
||||
CACHEFILESIZE=$(ls -l --block-size=1024 "$CACHEFILE" | cut -f5 -d" ")
|
||||
fi
|
||||
fi
|
||||
let SIZEREQUIRED=$REALFILESIZE-$CACHEFILESIZE
|
||||
[ $SIZEREQUIRED -lt 0 ] && SIZEREQUIRED=0
|
||||
else
|
||||
SIZEREQUIRED=$FILESIZE
|
||||
fi
|
||||
|
||||
#ERROR CACHESIZE 16 (tamanyo de la CACHE insuficiente)
|
||||
if [ "$SIZEREQUIRED" -ge "$CACHESIZE" ]
|
||||
then
|
||||
ogEcho log session "$MSG_WARNING: $MSG_ERR_CACHESIZE: $2 = $SIZEREQUIRED > CACHE = $CACHESIZE"
|
||||
ogRaiseError session $OG_ERR_CACHESIZE "CACHE"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
|
||||
#ERROR CACHESIZE 16 (Espacio libre en CACHE insuficiente)
|
||||
if [ "$SIZEREQUIRED" -ge "$CACHESIZEFREE" ]
|
||||
then
|
||||
ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO: ACTIONCACHEFULL=$ACTIONCACHEFULL"
|
||||
case "$ACTIONCACHEFULL" in
|
||||
NONE)
|
||||
ogEcho log session "$MSG_WARNING: $MSG_ERR_CACHESIZE: $2 = $SIZEREQUIRED > FREE SPACE CACHE = $CACHESIZEFREE"
|
||||
ogRaiseError session $OG_ERR_CACHESIZE "CACHE FULL, NO SPACE FREE"
|
||||
exit $?
|
||||
;;
|
||||
FORMAT)
|
||||
ogEcho log session "[51] $MSG_HELP_ogFormatCache "
|
||||
ogUnmountCache
|
||||
ogFormatCache
|
||||
ogMountCache
|
||||
NEXTOPERATION=REPEAT
|
||||
;;
|
||||
DELETE)
|
||||
ogEcho log session "[51] #MSG_HELP_ogDeleteTree $OGCAC$OGIMG/* "
|
||||
rm -fr $OGCAC$OGIMG/*
|
||||
NEXOPERATION=REPEAT
|
||||
;;
|
||||
*)
|
||||
ogEcho log session "$MSG_WARNING: $MSG_ERR_CACHESIZE: $2 = $FILESIZE > CACHE = $CACHESIZEFREE"
|
||||
ogRaiseError session $OG_ERR_CACHESIZE "CACHE"
|
||||
exit $?
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Comprobamos que imagen cache igual a la del repo. Si sincronizada no podemos comprobar.
|
||||
[ "$IMGSYNC" == "TRUE" ] || ogUpdateCacheIsNecesary $REPOSITORIO "$2" "$PROTOCOLO"
|
||||
RETVAL=$?
|
||||
# si RETVAL=0 => actualizamos si RETVAL=1 no actaulizasmo-exit 0 || si RETVAL>2 exit 1
|
||||
[ "$RETVAL" == "1" ] && exit 0
|
||||
[ "$RETVAL" -gt "1" ] && exit $OG_ERR_UPDATECACHE
|
||||
|
||||
ogMountCache >/dev/null
|
||||
|
||||
## Si no existe, crear subdirectorio para el fichero en la cache.
|
||||
IMGDIR=$(ogGetParentPath CACHE "/$2")
|
||||
if [ $? != 0 ]; then
|
||||
ogEcho log session "[5] $MSG_HELP_ogMakeDir \"$2 $(dirname "$2")."
|
||||
ogMakeDir CACHE $(dirname "/$2")
|
||||
IMGDIR=$(ogGetParentPath CACHE "/$2") || exit $?
|
||||
fi
|
||||
|
||||
TIME1=$SECONDS
|
||||
|
||||
case "$PROTOCOLO" in
|
||||
TORRENT)
|
||||
ogEcho log session "ogCopyFile $REPOSITORIO $2.torrent absolute $OGCAC/$OGIMG"
|
||||
# tiempos
|
||||
timewait=$(expr $(printf '%d\n' 0x$(ogGetMacAddress | awk -F: '{print $5$6}')) \* 120 / 65535)
|
||||
ogExecAndLog command ogCopyFile $REPOSITORIO "$2.torrent" "$IMGDIR" || exit $?
|
||||
#TODO: comprobar que el tracker definido en el fichero es correcto.
|
||||
#TODO comprobar que el fichero torrent está en cache
|
||||
# retardamos el inicio -aleatorio de 0 a 120 segundos- al tracker para gestionar mas de +-40 equipos
|
||||
P2PWAIT=$[ ( $RANDOM % 120 ) + 1 ]
|
||||
ogEcho log session " [ ] $MSG_SCRIPTS_TASK_SLEEP : $P2PWAIT seconds"
|
||||
sleep $P2PWAIT
|
||||
ogEcho log session " [ ] $MSG_SCRIPTS_TASK_START: ogTorrentStart CACHE $2.torrent $4"
|
||||
ogExecAndLog command ogTorrentStart CACHE "$2.torrent" $4
|
||||
RESUMEUPDATECACHE=$(grep -m 1 -B1 "Download" $OGLOGCOMMAND)
|
||||
RESUMEUPDATECACHEbf=$(grep -m 1 "Download" $OGLOGCOMMAND)
|
||||
if [ "$RESUMEUPDATECACHEbf" == "Download complete." ]; then
|
||||
rm -f $IMGDIR$2".torrent.bf"
|
||||
fi
|
||||
;;
|
||||
MULTICAST)
|
||||
ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION: $REPOIP:${OPTPROTOCOLO%%:*}"
|
||||
#TODO: ticket 379
|
||||
NUMBER=$[ ( $RANDOM % 30 ) + 1 ]
|
||||
sleep $NUMBER
|
||||
#FIN TODO
|
||||
ogEcho log session ogMcastRequest "$2" $OPTPROTOCOLO
|
||||
ogExecAndLog command ogMcastRequest "$2" $OPTPROTOCOLO || exit $?
|
||||
ogEcho log session ogMcastReceiverFile ${OPTPROTOCOLO%%:*} CACHE "$2"
|
||||
ogExecAndLog command ogMcastReceiverFile ${OPTPROTOCOLO%%:*} CACHE "$2" || exit $?
|
||||
RESUMEUPDATECACHE=$(grep -m 1 -B1 "Transfer complete" $OGLOGCOMMAND.tmp)
|
||||
;;
|
||||
UNICAST)
|
||||
#ogEcho log session "unicast"
|
||||
ogExecAndLog command ogCopyFile $REPOSITORIO "$2" "$IMGDIR"
|
||||
sleep 5
|
||||
RESUMEUPDATECACHE=$(grep -m 1 "100%" $OGLOGCOMMAND.tmp)
|
||||
;;
|
||||
RSYNC)
|
||||
# Si parametro de protocolo no era rsync, mensaje de cambio protocolo
|
||||
[ "${3^^}" == "RSYNC" ] || ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_RSYNCPROTOCOLCHANGE"
|
||||
# Opciones de rsync
|
||||
USERRSYNC="opengnsys"
|
||||
PASSWORD=" --password-file=/scripts/passrsync "
|
||||
OPTRSYNC=" --delete --progress "
|
||||
[ "$ogrsyncz" == "true" ] && OPTRSYNC="z $OPTRSYNC"
|
||||
[ "$ogrsyncw" == "true" ] && OPTRSYNC="w$OPTRSYNC"
|
||||
|
||||
if [ -d $REPOFILE ]; then
|
||||
# Si es sincronizada tipo directorio.
|
||||
[ -d "$OGCAC$OGIMG/$2" ] || mkdir "$OGCAC$OGIMG/$2"
|
||||
ogEcho log session "rsync -aHAX$OPTRSYNC $USERRSYNC@$REPOIP::ogimages/$OGUNIT$2/ $OGCAC$OGIMG/$2"
|
||||
rsync -aHAX$OPTRSYNC $PASSWORD "$USERRSYNC@$REPOIP::ogimages/$OGUNIT$2/" "$OGCAC$OGIMG/$2" 2>> $OGLOGCOMMAND | egrep "^sent|^sending|^total%" >> $OGLOGCOMMAND
|
||||
else
|
||||
# Si es sincronizada tipo archivo.
|
||||
[ "${2##*.}" == "img" ] && IMGTYPE="img" || IMGTYPE="diff"
|
||||
IMGNAME="${2%.img*}"
|
||||
|
||||
DIRMOUNT=$(ogGetMountImageDir "$IMGNAME" $IMGTYPE)
|
||||
DIRLOCAL="/tmp/$DIRMOUNT"
|
||||
mkdir "$DIRLOCAL" 2>/dev/null
|
||||
ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG"
|
||||
|
||||
# Si la imagen no existe la creo
|
||||
# Si la imagen del repositorio es mayor, redimensiono la imagen de cache
|
||||
if [ "$CACHEFILE" == "" -o $CACHEFILESIZE -lt $REALFILESIZE ]; then
|
||||
ogEcho log session "$MSG_HELP_ogCreateFileImage"
|
||||
ogCreateFileImage CACHE "$IMGNAME" $IMGTYPE $REALFILESIZE
|
||||
TIMEAUX3=$[SECONDS-TIMEAUX3]
|
||||
ogEcho log session " $MSG_SCRIPTS_TASK_END, $MSG_SCRIPTS_TIME_PARTIAL: $[TIMEAUX3/60]m $[TIMEAUX3%60]s"
|
||||
fi
|
||||
# Montamos las imagenes para sincronizarlas. Quitamos / inicial.
|
||||
ogMountImage CACHE "${IMGNAME#\/}" $IMGTYPE || exit $?
|
||||
ogMountImage REPO "${IMGNAME#\/}" $IMGTYPE
|
||||
# Esperamos que se monte la imagen en el servidor
|
||||
ogWaitSyncImage REPO "$IMGNAME" $IMGTYPE "mounted" || exit $?
|
||||
ogEcho log session " rsync -aHAX$OPTRSYNC $USERRSYNC@$REPOIP::ogimages/$DIRMOUNT/ $DIRLOCAL"
|
||||
rsync -aHAX$OPTRSYNC $PASSWORD "$USERRSYNC@$REPOIP::ogimages/$DIRMOUNT/" "$DIRLOCAL" 2>>$OGLOGCOMMAND | egrep "^sent|^sending|^total|%" >> $OGLOGCOMMAND
|
||||
# RETVAL="1" -> OK RETVAL="2" -> error # valores igual que ogUpdateCacheIsNecesary
|
||||
[ ${PIPESTATUS[0]} -eq 0 ] && RETVAL="1"|| RETVAL="2"
|
||||
# Desmonto las imagenes
|
||||
ogUnmountImage CACHE "$IMGNAME" $IMGTYPE
|
||||
ogUnmountImage REPO "$IMGNAME" $IMGTYPE
|
||||
ogUnlockImage CACHE "$2"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
TIME1=$[SECONDS-TIME1]
|
||||
|
||||
ogEcho log session " [ ] $RESUMEUPDATECACHE "
|
||||
ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL updateCache $[TIME1/60]m $[TIME1%60]s"
|
||||
ogEcho log session " [ ] $MSG_SCRIPTS_TASK_START $MSG_HELP_ogCalculateChecksum "
|
||||
TIME2=$SECONDS
|
||||
# Si es imagen sincronizada siempre da distinto md5. No podemos comprobar
|
||||
if [ "$IMGSYNC" == "TRUE" ]; then
|
||||
# RETVAL="1" -> OK RETVAL="2" -> error # valores igual que ogUpdateCacheIsNecesary
|
||||
[ $PROTOCOLO == "RSYNC" ] || RETVAL=1
|
||||
else
|
||||
ogUpdateCacheIsNecesary $REPOSITORIO "$2" "$PROTOCOLO"
|
||||
RETVAL=$?
|
||||
fi
|
||||
if [ "$(ogGetCaller)" != "deployImage" ]; then
|
||||
TIME2=$[SECONDS-TIME2]
|
||||
ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL $MSG_HELP_ogCalculateChecksum $[TIME2/60]m $[TIME2%60]s"
|
||||
fi
|
||||
# si RETVAL=0 => actualizamos si RETVAL=1 no actaulizamos-exit 0 || si RETVAL>2 exit 1
|
||||
[ "$RETVAL" == "0" ] && exit $OG_ERR_UPDATECACHE
|
||||
[ "$RETVAL" == "1" ] && exit 0
|
||||
[ "$RETVAL" -gt "1" ] && exit $OG_ERR_UPDATECACHE
|
||||
|
|
@ -42,6 +42,7 @@ if len (sys.argv) < 3:
|
|||
sys.exit (1)
|
||||
_, repositorio, path, protocolo, *other = sys.argv
|
||||
optprotocolo = other[0] if len (other) > 0 else ''
|
||||
cacheopts = other[1] if len (other) > 1 else ''
|
||||
|
||||
if 'RSYNC' == protocolo:
|
||||
raise Exception ('synchronised images are no longer supported')
|
||||
|
@ -67,7 +68,7 @@ if protocolo.startswith ('MULTICAST') and re.match (r'^-?\d+$', wait):
|
|||
MCASTWAIT = int (wait) + 5
|
||||
# Unidad organizativa.
|
||||
## (no longer supported)
|
||||
#print (f'repositorio ({repositorio}) path ({path}) protocolo ({protocolo}) optprotocolo ({optprotocolo}) MCASTWAIT ({MCASTWAIT})')
|
||||
#print (f'repositorio ({repositorio}) path ({path}) protocolo ({protocolo}) optprotocolo ({optprotocolo}) cacheopts ({cacheopts}) MCASTWAIT ({MCASTWAIT})')
|
||||
|
||||
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
|
||||
if StringLib.ogCheckIpAddress (repositorio) or 'REPO' == repositorio:
|
||||
|
|
Loading…
Reference in New Issue