Refs #401 adds functions that needs oglivecli

ogboot_installer
qindel 2024-05-29 15:19:30 +00:00
parent 26dd204fdc
commit 3a0f8535c4
22 changed files with 3215 additions and 0 deletions

1748
bin/composer.phar 100644

File diff suppressed because it is too large Load Diff

18
bin/console 100755
View File

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
if (!is_file(dirname(__DIR__).'/vendor/autoload_runtime.php')) {
throw new LogicException('Symfony Runtime is missing. Try running "composer require symfony/runtime".');
}
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
$kernel = new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
return new Application($kernel);
};

514
bin/oglivecli 100755
View File

@ -0,0 +1,514 @@
#!/bin/bash
#/**
#@file oglivecli
#@brief Command line tool to manage ogLive clients.
#@usage oglivecli Command [Options ...]
#@param Command:
#@param help show this help
#@param version show script version
#@param config [Parameter] show configuration parameters
#@param check check system consistency
#@param convert convert old ogclient to new default ogLive client
#@param list list installed ogLive clients
#@param show all show JSON information about all installed ogLive clients
#@param show default show JSON information about ogLive client marked as default
#@param show Index|Dir show JSON information about an installed ogLive client
#@param search Index|Dir show corresponding index or directory
#@param download show a menu to download an ogLive ISO image from the OpenGnsys website
#@param download Iso download an specific ogLive ISO image from the OpenGnsys website
#@param install Iso install a new ogLive client from a downloaded ISO image
#@param uninstall Iso remove ISO image and uninstall its ogLive client
#@param uninstall Index|Dir uninstall an ogLive client
#@param get-default get index value for default ogLive client
#@param set-default Index set default ogLive client
#@param rebuild rebuild a lost configuration file
#@param assign Iso Index assign an ISO file to a JSON entry
#@param Options:
#@param Index a number, starting by 0
#@param Dir directory (relative to installation directory)
#@param Iso ISO file name (relative to download URL or download directory)
#@warning This script needs "jq" command.
#@version 1.1.0 - Initial version.
#@author Ramón M. Gómez - ETSII Univ. Sevilla
#@date 2016-12-05
#@version 1.1.1b - Use reduced directory names.
#@author Ramón M. Gómez - ETSII Univ. Sevilla
#@date 2020-01-17
#*/ ##
# Global constants definition.
PROG=$(basename "$(realpath "$0")") # Program name.
OPENGNSYS=/opt/ogboot # OpenGnsys main directory.
DOWNLOADDIR=$OPENGNSYS/lib # Directory to store ogLive images.
DOWNLOADURL="https://ognproject.evlt.uma.es/trac/downloads" # Download URL.
TFTPDIR=$OPENGNSYS/tftpboot # TFTP directory.
DEFOGLIVE="ogLive" # Default ogLive directory.
MINREL=20190601 # Mininum ogLive compatibility release.
INFOFILE=$OPENGNSYS/etc/ogliveinfo.json # Configuration file.
# Global and secondary functions.
source $OPENGNSYS/lib/ogfunctions.sh || exit 1
# Create/edit JSON file about installed ogLive clients.
function addToJson() {
local i DATA OGLIVEDIST="$1" OGLIVEKRNL="$2" OGLIVEARCH="$3" OGLIVEREV="$4"
local OGLIVEDIR=$(basename $5 2>/dev/null) OGLIVEISO=$(basename $6 2>/dev/null)
# JSON data for installed ogLive.
DATA=$(cat << EOT | jq .
{"distribution":"$OGLIVEDIST","kernel":"$OGLIVEKRNL","architecture":"$OGLIVEARCH","revision":"$OGLIVEREV","directory":"$OGLIVEDIR","iso":"$OGLIVEISO"}
EOT
)
# Check JSON file consistency.
if [ "$(jq -c keys $INFOFILE 2>/dev/null)" == '["default","oglive"]' ]; then
# Check if ogLive is defined into JSON file.
n=$(jq ".oglive | length" $INFOFILE)
for ((i=0; i<n; i++)); do
[ "$(jq ".check=$DATA | .check==.oglive[$i]" $INFOFILE)" == "true" ] && INDEX=$i
done
# Check if it needs to insert data.
if [ -z "$INDEX" ]; then
INDEX=$n
jq ".oglive |= (. + [$DATA])" $INFOFILE | sponge $INFOFILE
fi
# Show JSON entry.
jq ".oglive[$INDEX]" $INFOFILE
else
# Create new JSON file.
cat << EOT | jq . | tee $INFOFILE
{"oglive":[$DATA],"default":0}
EOT
fi
}
# Command functions.
# Convert default ogclient to a new ogLive format.
function convert() {
local OGCLIENT=ogclient OLDINFOFILE=$OPENGNSYS/doc/veroglive.txt
local OGLIVEKRNL OGLIVEDIR OGLIVEISO
[ $# -ne 0 ] && raiseError usage
[ ! -w $(dirname $INFOFILE) ] && raiseError access "Configuration file."
[ -n "$(stat -c "%N" $TFTPDIR/ogclient | awk '$3~/'$DEFOGLIVE'/ {print}')" ] && raiseError access "ogLive is already converted."
pushd $TFTPDIR >/dev/null || raiseError access "Installation directory."
[ ! -f $OGCLIENT/ogvmlinuz ] && raiseError notfound "\"ogclient\"."
# Add entry to JSON file using ogclient kernel version.
OGLIVEKRNL=$(file -bkr $OGCLIENT/ogvmlinuz | awk '/Linux/ {for(i=1;i<=NF;i++) if($i~/version/) {v=$(i+1);sub(/-.*/,"",v);print v}}')
OGLIVEDIR=$DEFOGLIVE-$OGLIVEKRNL
[ -r $OLDINFOFILE ] && OGLIVEISO="$(head -1 $OLDINFOFILE)"
addToJson "$(echo $OGLIVEISO|cut -f2 -d-)" "$OGLIVEKRNL" "i386" "${OGLIVEISO##*-}" "$OGLIVEDIR" "$OGLIVEISO.iso"
# Rename directory, link to default and clean old files.
mv -v $OGCLIENT $OGLIVEDIR
ln -vfs $OGLIVEDIR $DEFOGLIVE
rm -f $OGCLIENT
ln -vfs $DEFOGLIVE $OGCLIENT
mv -v $OGCLIENT.old $OGLIVEDIR.old 2>/dev/null
rm -fv {ogvmlinuz,oginitrd.img}{,.sum} $OLDINFOFILE
popd >/dev/null
# Delete old config file.
rm -f $OLDINFOFILE
}
# Show script configuration parameters.
function config() {
local DATA
DATA=$(cat << EOT
[
{ "param": "config-file", "description": "Configuration file", "value": "$INFOFILE" },
{ "param": "download-url", "description": "ogLive download URL", "value": "$DOWNLOADURL" },
{ "param": "download-dir", "description": "ogLive download directory", "value": "$DOWNLOADDIR" },
{ "param": "install-dir", "description": "ogLive installation directory", "value": "$TFTPDIR" },
{ "param": "default-name", "description": "Default ogLive name", "value": "$DEFOGLIVE" },
{ "param": "min-release", "description": "Minimum compatibility release", "value": "r$MINREL" }
]
EOT
)
case $# in
0) # Show all parameters.
echo "$DATA" | jq -r '.[] | .description + " (" + .param + ")," + .value' | column -ts,
;;
1) # Show specified parameter.
DATA=$(echo "$DATA" | jq -r ".[] | select(.param==\"$1\").value")
[ "$DATA" ] || raiseError notfound "\"$1\"."
echo "$DATA"
;;
*) # Usage error.
raiseError usage
;;
esac
}
# Check consistency, showing configuration problems.
function check() {
local ERR=0 AUX INST DEF
[ $# -ne 0 ] && raiseError usage
# Check for old system that needs conversion.
if [ -z "$(stat -c "%N" $TFTPDIR/ogclient | awk '$3~/'$DEFOGLIVE'/ {print}')" ]; then
echo "This server uses old ogclient, please run \"$PROG convert\" to update."
let ERR++
[ ! -f $INFOFILE ] && return $ERR
fi
# Check for other problems.
[ ! -f $INFOFILE ] && echo "Configuration file does not exists: $INFOFILE" && let ERR++
[ -f $INFOFILE -a "$(jq -c keys $INFOFILE 2>/dev/null)" != "[\"default\",\"oglive\"]" ] && echo "Format error in configuration file: $INFOFILE" && let ERR++
[ ! -e $TFTPDIR ] && echo "TFTP directory does not exist: $TFTPDIR." && let ERR++
# Check for installed ogLive clients.
INST=( $(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort) )
[[ ${#INST[@]} -eq 0 ]] && echo "No ogLive clients are installed." && let ERR++
DEF=( $(jq -r .oglive[].directory $INFOFILE 2>/dev/null | sort) )
# Compare installed and defined ogLive clients.
AUX=$(comm -23 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ogLive are installed but not defined: ${AUX//$'\n'/, }" && let ERR++
AUX=$(comm -13 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ogLive are defined but not installed: ${AUX//$'\n'/, }" && let ERR++
# Compare downloaded and defined ISO images.
INST=( $(find $DOWNLOADDIR/ -type f -name "$DEFOGLIVE-*.iso" -printf "%f\n" | sort) )
DEF=( $(jq -r .oglive[].iso $INFOFILE 2>/dev/null | sort) )
AUX=$(comm -23 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ISOs are downloaded but not defined: ${AUX//$'\n'/, }" && let ERR++
AUX=$(comm -13 <(printf "%s\n" ${INST[*]}) <(printf "%s\n" ${DEF[*]}))
[ -n "$AUX" ] && echo "Some ISOs are defined but not downloaded: ${AUX//$'\n'/, }" && let ERR++
# Check for new ISO files downloaded after installation.
AUX=$(jq -r '.oglive[] as $og | $og.iso + ":" + $og.directory' $INFOFILE 2>/dev/null | \
while IFS=":" read -r DEF INST; do
[ $DOWNLOADDIR/$DEF -nt $TFTPDIR/$INST ] && echo "$DEF"
done)
[ -n "$AUX" ] && echo "Some ISOs are downloaded after installation: ${AUX//$'\n'/, }" && let ERR++
AUX=$(jq -r '.oglive[] as $og | if ($og.revision[1:9] | tonumber) < '$MINREL' then $og.directory else "" end' $INFOFILE 2>/dev/null)
[ -n "$AUX" ] && echo "Some installed ogLive aren't fully compatible: ${AUX//$'\n'/, }" && let ERR++
DEF=$(jq -r ".oglive[$(getdefault)].directory" $INFOFILE 2>/dev/null)
INST=$(stat -c "%N" $TFTPDIR/$DEFOGLIVE | cut -f4 -d\')
[ "$DEF" != "$INST" ] && echo "Default ogLive is not linked to right directory: $DEF <> $INST" && let ERR++
# Print result.
[ $ERR -eq 0 ] && echo "OK!" || echo "Problems detected: $ERR"
return $ERR
}
# List installed ogLive clients.
function list() {
[ $# -ne 0 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
# List all defined indexes, directories and check if missing.
jq -r .oglive[].directory $INFOFILE | nl -v 0 | \
awk '{system("echo -n "$0"; test -d '$TFTPDIR'/"$2" || echo -n \" (missing)\"; echo")}' | column -t
}
# Show information about an installed ogLive client.
function show() {
local INDEX
[ $# -ne 1 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
# Show JSON entries.
case "$1" in
default) # Default index.
INDEX="[$(jq -r .default $INFOFILE)]" ;;
all) # All intries.
;;
[0-9]*) # Index.
INDEX="[$1]" ;;
*) # Directory.
INDEX="[$(search "$1" 2>/dev/null)]" || raiseError notfound "Directory \"$1\"."
;;
esac
jq ".oglive$INDEX" $INFOFILE || raiseError notfound "Index \"$1\"."
}
# Show index or directory corresponding to searching parameter.
function search() {
[ $# -ne 1 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
# Show corresponding index or directory.
list | awk -v d="$1" '{if ($2==d) print $1; if ($1==d) print $2}' | grep . || raiseError notfound "Index/Directory \"$1\"."
}
# Show a menu to select and download an ogLive ISO image from the OpenGnsys website.
function download() {
local OGLIVE NISOS i HTTPCODE ISOREL
# Verificar si el directorio de descarga existe y tiene permisos de escritura.
[ ! -d "$DOWNLOADDIR" ] && raiseError notfound "Directorio de descarga."
[ ! -w "$DOWNLOADDIR" ] && raiseError access "Directorio de descarga."
# Si no se proporciona ningún parámetro, mostrar el menú de descargas.
if [ -z "$1" ]; then
downloadMenu
else
local selected_name="$1"
# Obtener la lista de archivos disponibles.
OGLIVE=( $(curl -k --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") )
# Buscar el archivo seleccionado por nombre.
OGLIVEFILE=""
for iso in "${OGLIVE[@]}"; do
if [[ "$iso" == *"$selected_name"* ]]; then
OGLIVEFILE=$iso
break
fi
done
[ -n "$OGLIVEFILE" ] || raiseError download "Nombre \"$selected_name\" inválido."
# Obtener el tamaño de descarga.
local SOURCELENGTH=$(curl -k --head --retry 5 --retry-delay 5 --max-time 30 "$DOWNLOADURL/$OGLIVEFILE" | awk -F: '/Content-Length:/ {print $2}')
[ -n "$SOURCELENGTH" ] || raiseError download "$OGLIVEFILE"
# Descargar ogLive.
local TARGETFILE="$DOWNLOADDIR/$OGLIVEFILE"
trap "rm -f $TARGETFILE" 1 2 3 6 9 15
curl -k --retry 5 --retry-delay 5 "$DOWNLOADURL/$OGLIVEFILE" -o "$TARGETFILE" || raiseError download "\"$OGLIVEFILE\"."
install "$OGLIVEFILE"
fi
}
# Muestra un menú para seleccionar y descargar un archivo ogLive ISO del sitio web de OpenGnsys.
function downloadMenu() {
local OGLIVE NISOS i HTTPCODE ISOREL
OGLIVE=( $(curl -k --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") )
NISOS=${#OGLIVE[@]}
echo "Descargas disponibles (+ = instalado, * = compatibilidad completa):"
for i in $(seq 1 $NISOS); do
[ -e $DOWNLOADDIR/${OGLIVE[i-1]} ] && OGLIVE[i-1]="(+) ${OGLIVE[i-1]}"
ISOREL=${OGLIVE[i-1]##*-r}; ISOREL=${ISOREL%%.*}
[ $ISOREL -ge $MINREL ] && OGLIVE[i-1]="(*) ${OGLIVE[i-1]}"
echo "$i) ${OGLIVE[i-1]}"
done
}
# Show a menu to select and download an ogLive ISO image from the OpenGnsys website.
function download_old() {
local OGLIVE NISOS i HTTPCODE TARGETFILE
local ISOREL
[ $# -gt 1 ] && raiseError usage
[ ! -d $DOWNLOADDIR ] && raiseError notfound "Download directory."
[ ! -w $DOWNLOADDIR ] && raiseError access "Download directory."
# Check parameter.
if [ -n "$1" ]; then
# ogLive to download.
OGLIVEFILE="$1"
else
# Show download menu.
OGLIVE=( $(curl -k --silent $DOWNLOADURL | grep "$DEFOGLIVE.*iso") )
NISOS=${#OGLIVE[@]}
echo "Available downloads (+ = installed, * = full compatibility):"
for i in $(seq 1 $NISOS); do
[ -e $DOWNLOADDIR/${OGLIVE[i-1]} ] && OGLIVE[i-1]="(+) ${OGLIVE[i-1]}"
ISOREL=${OGLIVE[i-1]##*-r}; ISOREL=${ISOREL%%.*}
[ $ISOREL -ge $MINREL ] && OGLIVE[i-1]="(*) ${OGLIVE[i-1]}"
done
select opt in "${OGLIVE[@]}"; do
[ -n "$opt" ] && OGLIVEFILE=${opt##* } && break
done
fi
# Get download size.
SOURCELENGTH=$(curl -k --head --retry 5 --retry-delay 5 --max-time 30 $DOWNLOADURL/$OGLIVEFILE | awk -F: '/Content-Length:/ {print $2}')
[ -n "$SOURCELENGTH" ] || raiseError download "$OGLIVEFILE"
# Download ogLive.
TARGETFILE=$DOWNLOADDIR/$OGLIVEFILE
trap "rm -f $TARGETFILE" 1 2 3 6 9 15
curl -k --retry 5 --retry-delay 5 --max-time 30 $DOWNLOADURL/$OGLIVEFILE -o $TARGETFILE || raiseError download "\"$OGLIVEFILE\"."
}
# Install an ogLive client from a previously downloaded ISO image.
function install() {
local OGLIVEFILE OGLIVEDIST OGLIVEREV OGLIVEKRNL OGLIVEDIR OGINITRD OGSQFS OGCLIENT=ogclient
local COMPRESS SAMBAPASS TMPDIR RSYNCSERV RSYNCCLNT
[ $# -ne 1 ] && raiseError usage
OGLIVEFILE=$(realpath $DOWNLOADDIR/$1)
# Only 1 file in pathname expansion.
[ $(echo $OGLIVEFILE | wc -w) -gt 1 ] && raiseError usage
[ ! -f $OGLIVEFILE ] && raiseError notfound "Downloaded file: \"$1\"."
[ ! -r $OGLIVEFILE ] && raiseError access "Downloaded file: \"$1\"."
[ ! -w $(dirname $INFOFILE) ] && raiseError access "Configuration directory."
[ ! -w $TFTPDIR ] && raiseError access "Installation directory."
[ -z "$(file -b $OGLIVEFILE | grep "ISO.*ogClient")" ] && raiseError access "File is not an ogLive ISO image."
# Working directory:
# 64-bit: ogLive-KernelVersion-rCodeRelease
# 32-bit: ogLive-KernelVersion-i386-rCodeRelease
OGLIVEDIST="$(echo $OGLIVEFILE|cut -f2 -d-)"
OGLIVEREV="${OGLIVEFILE##*-}"; OGLIVEREV="${OGLIVEREV%%.*}"
OGLIVEKRNL="$(echo $OGLIVEFILE|cut -f3- -d-)"; OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEREV.*}"
OGLIVEARCH="$(echo $OGLIVEFILE|awk -F- '{print $(NF-1)}')"
case "$OGLIVEARCH" in
i386|amd64) # Get architecture.
OGLIVEKRNL="${OGLIVEKRNL%-$OGLIVEARCH}" ;;
*) # 32-bit by default.
OGLIVEARCH="i386" ;;
esac
OGLIVEDIR="$TFTPDIR/$DEFOGLIVE-${OGLIVEKRNL%%-*}-$OGLIVEARCH-$OGLIVEREV"
OGLIVEDIR="${OGLIVEDIR/amd64-/}"
# Get current or default Samba key.
OGINITRD=$OGLIVEDIR/oginitrd.img
[ ! -r $OGINITRD ] && OGINITRD=$TFTPDIR/$DEFOGLIVE/oginitrd.img
if [ -r $OGINITRD ]; then
COMPRESS=$(file -b "$OGINITRD" | awk '{print tolower($1);}')
SAMBAPASS=$($COMPRESS -dc $OGINITRD | \
cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
sed -n '/^[ ].*OPTIONS=/s/.*pass=\(\w*\).*/\1/p')
fi
# Make ogLive backup.
rm -fr ${OGLIVEDIR}.old
mv -fv $OGLIVEDIR ${OGLIVEDIR}.old 2>/dev/null
# Mount ogLive ISO image, update its files and unmount it.
TMPDIR=/tmp/${OGLIVEFILE%.iso}
mkdir -p $OGLIVEDIR $TMPDIR
trap "umount $TMPDIR; rm -fr $TMPDIR" 1 2 3 6 9 15
mount -o loop,ro $OGLIVEFILE $TMPDIR
cp -va $TMPDIR/ogclient/* $OGLIVEDIR || raiseError access "Cannot copy files to ogLive directory."
umount $TMPDIR
# Link to default directory if it's the first ogLive.
if [ ! -f $INFOFILE ]; then
rm -f $TFTPDIR/$DEFOGLIVE $TFTPDIR/$OGCLIENT
ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE
ln -vfs $DEFOGLIVE $TFTPDIR/$OGCLIENT
fi
# Recover or ask for a new Samba access key.
if [ -n "$SAMBAPASS" ]; then
echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | $OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)"
else
$OPENGNSYS/bin/setsmbpass "$(basename $OGLIVEDIR)"
fi
# Set permissions.
find -L $OGLIVEDIR -type d -exec chmod 755 {} \;
find -L $OGLIVEDIR -type f -exec chmod 644 {} \;
chown -R :opengnsys $OGLIVEDIR
# Mount SquashFS and check Rsync version.
OGSQFS=$OGLIVEDIR/ogclient.sqfs
mount -o loop,ro $OGSQFS $TMPDIR
# If Rsync server version > client version, link to compiled file.
RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
if [ -z "$RSYNCSERV" -o ${RSYNCSERV:-0} -gt ${RSYNCCLNT:-1} ]; then
[ -e $OPENGNSYS/client/bin/rsync-$RSYNCSERV ] && mv -f $OPENGNSYS/client/bin/rsync-$RSYNCSERV $OPENGNSYS/client/bin/rsync
else
# Else, rename compiled file using Rsync protocol number.
[ -e $OPENGNSYS/client/bin/rsync ] && mv -f $OPENGNSYS/client/bin/rsync $OPENGNSYS/client/bin/rsync-$($OPENGNSYS/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
fi
# Unmount SquashFS.
umount $TMPDIR
rmdir $TMPDIR
# Update JSON file.
addToJson "$OGLIVEDIST" "$OGLIVEKRNL" "$OGLIVEARCH" "$OGLIVEREV" "$OGLIVEDIR" "$OGLIVEFILE"
}
# Uninstall an ogLive client.
function uninstall() {
local ISO DIR INDEX DEFINDEX
[ $# -ne 1 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
[ ! -w $TFTPDIR ] && raiseError access "Installation directory."
# Get index and directory for the entry.
case "$1" in
*/*) # Error (access to other directory).
raiseError access "Cannot access outside installation directory."
;;
*.iso) # ISO file.
ISO="$1"
# Working directory (ogLive-Distribution-KernelVersion-CodeRevision).
DIR="$(echo $ISO|cut -f1,3 -d-)-${ISO##*-}"; DIR=${DIR%.*}
INDEX=$(search $DIR 2>/dev/null)
;;
[0-9]*) # Index.
INDEX=$1; DIR=$(search $INDEX 2>/dev/null)
;;
*) # Directory.
DIR="$1"; INDEX=$(search $DIR 2>/dev/null)
;;
esac
DEFINDEX=$(getdefault)
[[ $INDEX = $DEFINDEX ]] && raiseError access "Cannot uninstall default ogLive."
# Remove files and delete index entry.
rm -vfr ${ISO:+$DOWNLOADDIR/$ISO} ${DIR:+$TFTPDIR/$DIR} ### Remove $TFTPDIR/$DIR.old ?
if [ -n "$INDEX" ]; then
jq "del(.oglive[$INDEX])" $INFOFILE | sponge $INFOFILE
# Decrement default index if needed (removed < default).
[[ $INDEX < $DEFINDEX ]] && jq ".default=$((DEFINDEX-1))" $INFOFILE | sponge $INFOFILE
fi
}
# Get default ogLive index.
function getdefault() {
[ $# -ne 0 ] && raiseError usage
[ ! -r $INFOFILE ] && raiseError access "Configuration file."
# Read default parameter.
jq -r .default $INFOFILE || raiseError notfound "Undefined default index."
}
# Set default ogLive index.
function setdefault() {
local INDEX OGLIVEDIR
[ $# -ne 1 ] && raiseError usage
[ ! -w $INFOFILE ] && raiseError access "Configuration file."
INDEX=$1
# Check if index entry exists.
jq ".oglive[$INDEX]" $INFOFILE || raiseError notfound "Index \"$INDEX\"."
# Get ogLive directory.
OGLIVEDIR=$(jq -r ".oglive[$INDEX].directory" $INFOFILE) || raiseError notfound "Directory for index \"$INDEX\"."
# Update default parameter.
jq ".default=$INDEX" $INFOFILE | sponge $INFOFILE
# Link to default directory.
rm -f $TFTPDIR/$DEFOGLIVE
ln -vfs $(basename $OGLIVEDIR) $TFTPDIR/$DEFOGLIVE
}
# Rebuild a lost configuration file.
function rebuild() {
local i INST NF DEF
[ $# -ne 0 ] && raiseError usage
[ -f $INFOFILE ] && raiseError access "Configuration file exists."
INST=$(find $TFTPDIR/ -type d -name "$DEFOGLIVE-*" -a ! -name "*.old" -printf "%f\n" | sort)
for i in $INST; do
NF=$(echo $i | awk -F- '{print NF-1}')
case $NF in
1) addToJson "" "$(echo $i|cut -f2 -d-)" "i386" "" "$i" "" ;;
2) eval addToJson $(echo $i | awk -F- '{printf "\"\" %s amd64 %s %s \"\"",$2,$3,$0}') ;;
3) eval addToJson $(echo $i | awk -F- '{if ($3=="i386") printf "\"\" %s %s %s %s \"\"",$2,$3,$4,$0; else printf "%s %s i386 %s %s \"\"",$2,$3,$4,$0}') ;;
4) eval addToJson $(echo $i | awk -F- '{printf "%s %s %s %s %s \"\"",$2,$3,$4,$5,$0}') ;;
esac
# Check for is default oglive.
[ -n "$(stat -c "%N" $TFTPDIR/$DEFOGLIVE | awk '$3~/'$i'/ {print}')" ] && DEF="$i"
done
# Set default ogLive.
[ -n "$DEF" ] && setdefault $(search $DEF)
}
# Assign an ISO file to a JSON entry.
function assign() {
local ISOFILE DIR
[ $# -ne 2 ] && raiseError usage
[ ! -w $INFOFILE ] && raiseError access "Configuration file."
# Check if ISO file and index directory exist.
ISOFILE=$DOWNLOADFILE/$1
[ ! -f $DOWNLOADDIR/$ISOFILE ] && raiseError notfound "ISO file \"$1\"."
DIR=$(search $2 2>/dev/null)
[ ! -d $TFTPDIR/$DIR ] && raiseError notfound "Directory for index \"$2\"."
# Assign ISO file to JSON entry.
jq ".oglive[$2].iso=\"$1\"" $INFOFILE | sponge $INFOFILE && jq ".oglive[$2]" $INFOFILE
}
# Main progrram.
# Access control.
[ -r $OPENGNSYS/www/controlacceso.php ] && ACCESS="web"
[ "$USER" = "root" ] && ACCESS="root"
[ -z "$ACCESS" ] && raiseError access "Need to be root."
# Check dependencies.
which sponge &>/dev/null || raiseError notfound "Need to install \"moreutils\"."
# Commands control.
shopt -s extglob
case "$ACCESS" in
root) CMDS='+(help|version|convert|config|check|list|show|search|download|install|uninstall|get-default|set-default|rebuild|assign)' ;;
web) CMDS='+(list|show|search|get-default)' ;;
esac
case "$1" in
$CMDS) COMMAND="${1/-/}"; shift; $COMMAND "$@" ;;
*) raiseError usage ;;
esac
exit $?

66
lib/ogfunctions.sh 100644
View File

@ -0,0 +1,66 @@
#!/bin/bash
#/**
#@file ogfunctions.sh
#@brief Generic functions for OpenGnsys Server and OpenGnsys Repository.
#@version 1.1.1 - Initial version
#@author Ramón M. Gómez, ETSII Universidad de Sevilla
#@date 2017-10-08
#*/
# Showing an error message.
function raiseError() {
case "$1" in
usage)
echo "$PROG: Usage error: Type \"$PROG help\"" >&2
exit 1 ;;
notfound)
echo "$PROG: Resource not found: $2" >&2
exit 2 ;;
access)
echo "$PROG: Access error: $2" >&2
exit 3 ;;
download)
echo "$PROG: Download error: $2" >&2
exit 4 ;;
*)
echo "$PROG: Unknown error" >&2
exit 1 ;;
esac
}
# Showing help message.
function help() {
[ -n "$1" ] && DESCRIPTION="$1" || DESCRIPTION=$(grep "^#@brief" "$0" | cut -f2- -d" ")
shift
if [ -n "$1" ]; then
USAGE="$1"
shift
else
USAGE=$(grep "^#@usage" "$0" | cut -f2- -d" ")
[ -n "$USAGE" ] && PARAMS=$(awk '$1=="#@param" {sub($1,""); print "\t",$0}' "$0")
fi
# Showing help.
echo "$PROG: ${DESCRIPTION:-"no description"}"
echo "Usage: ${USAGE:-"no usage info"}"
[ -n "$PARAMS" ] && echo -e "$PARAMS"
if [ -n "$*" ]; then
echo "Examples:"
while (( "$#" )); do
echo -e "\t$1"
shift
done
fi
exit 0
}
# Metafunction to check if JSON result exists.
JQ=$(which jq 2>/dev/null) || raiseError notfound "Need to install \"jq\"."
function jq() {
local OUTPUT
OUTPUT=$($JQ "$@") || return $?
[[ "$OUTPUT" = "null" ]] && return 1
echo "$OUTPUT"
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,91 @@
#!/bin/bash
#___________________________________________________
#
# PARAMETROS RECIBIDOS DESDE EL CLIENTE:
# $1 Número de disco
# $2 Número de particion
# $3 Nombre canónico de la imagen (sin extensión)
# $4 Dirección del repositorio (REPO, por defecto)
#___________________________________________________
#$OG_ERR_NOTEXEC Si no es llamada por OG client
#$OG_ERR_LOCKED=4 Si la particion está bloqueada.
#Codigos de error del scripts createImage
#@exception OG_ERR_FORMAT # 1 formato incorrecto.
#@exception OG_ERR_PARTITION # 3 Error en partición de disco o en su sistema de archivos
#@exception OG_ERR_IMAGE # 5 Error en funcion ogCreateImage o ogRestoreImage.
#@exception OG_ERR_NOTWRITE # 14 error de escritura
#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15
#@exception OG_ERR_CACHESIZE # 16 si espacio de la cache local o remota no tiene espacio 16
#@exception OG_ERR_REDUCEFS # 17 error al reducir sistema de archivos.
#@exception OG_ERR_EXTENDFS # 18 Errror al expandir el sistema de archivos.
#Códigos de error de la funcion ogCreateImage
TIME1=$SECONDS
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp
# Registro de inicio de ejecución
ogEcho log session "$MSG_INTERFACE_START $0 $*"
# Solo ejecutable por OpenGnsys Client.
PATH=$PATH:$(dirname $0)
PROG=$(basename $0)
CALLER=$(ogGetCaller)
if [ "$CALLER" != "ogAdmClient" ]; then
ogRaiseError $OG_ERR_NOTEXEC "$CALLER -> $PROG"
exit $?
fi
# Valor por defecto para el repositorio.
REPO=${4:-"REPO"}
[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE"
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
ogCheckIpAddress $REPO
if [ $? == 0 -o $REPO == "REPO" ] ; then
# Unidad organizativa
[ "$ogunit" != "" ] && OGUNIT="$ogunit"
# Si falla el cambio -> salimos con error repositorio no valido
ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?)
REPO="REPO"
fi
# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura,
if [ "$REPO" == "REPO" -a "$boot" != "admin" ]
then
CambiarAcceso admin &>> $OGLOGFILE
RETVAL=$?
[ $RETVAL -gt 0 ] && exit $RETVAL
fi
ogEcho createImage "$1" "$2" "$4" /"$3"
# Si existe, ejecuta script personalizado "createImageCustom"; si no, llama al genérico "createImage".
if which createImageCustom &>/dev/null; then
createImageCustom "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND
else
createImage "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND
fi
RETVAL=$?
# Cambiar acceso a modo usuario, si es necesario.
[ "$REPO" == "REPO" -a "$boot" != "admin" ] && CambiarAcceso user
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
exit $RETVAL

View File

@ -0,0 +1,98 @@
#!/bin/bash
#___________________________________________________________________
#
# CREAR IMAGEN BÁSICA
#___________________________________________________________________
#
# Parámetros recibidos desde el cliente:
#
# $1 Número de disco
# $2 Número de particion
# $3 Nombre canónico de la imagen básica (sin extensión)
# $4 Dirección del repositorio
# $5 Es una cadena "nnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnn" donde "n" vale 0 ó 1.
# 1XX: Gestionar fichero completo en lugar de diferencas
# X1X: Eliminar archivos de la imagen que no estén en la partición
# XX1: Comprimir archivos para enviarlos por la red
# El valor X indica que no importa el valor que tenga el dato
# $6 Es una cadena "nnnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnnn" donde "n" vale 0 ó 1.
# 1XXX: Borrar la imagen del repositorio antes de crearla
# X1XX: Copiar Imagen básica también a la cache
# XX1X: Borrar previamente la imagen de la cache antes de copiarla
# XXX1: No borrar archivos en destino
# El valor X indica que no importa el valor que tenga el dato
# $7 Método de syncronización 1=Sincronización1 2=Sincronizacion2
# $8 Ruta de origen de la Imagen (Carpeta)
#___________________________________________________________________
#
# Control parámetros
#___________________________________________________________________
PROG="$(basename $0)"
if [ $# -lt 7 ]; then
usage=" ndisco nparticion nombre_imagen_basica ip_repositorio"
usage="$usage copiar_a_caché Borrar_cache_previamente Ruta_origen"
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG $usage"
exit $?
fi
#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 $*"
# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura,
PATH=$PATH:$(dirname $0)
CLIENTIP=$(ogGetIpAddress)
[ "$4" == "$CLIENTIP" ] && DEST=CACHE || DEST=REPO
if [ "$DEST" == "REPO" -a "$boot" != "admin" ]; then
CambiarAcceso admin &>> $OGLOGFILE
RETVAL=$?
[ $RETVAL -gt 0 ] && exit $RETVAL
fi
if [ $7 -eq 1 ]; then
#sincronizacion1
ogCrearImagenBasica "$@"
RETVAL=$?
fi
if [ $7 -eq 2 ]; then
# Sincronizacion2
flag=$5
WHOLE=${flag:0:1}
DELFILE=${flag:1:1}
COMPRESS=${flag:2:1}
# Nota los valores se pasan como variables de entorno,
# la idea es que mas adelante vayan en el fichero PXE.
[ $WHOLE -eq 1 ] && export ogrsyncw=true || export ogrsyncw=false
[ $DELFILE -eq 1 ] && export ogrsyncdel=true || export ogrsyncdel=false
[ $COMPRESS -eq 1 ] && export ogrsyncz=true || export ogrsyncz=false
# [ "$4" == "0.0.0.0" ] && DEST="CACHE" || DEST="REPO"
createBaseImage $1 $2 $DEST "$3"
RETVAL=$?
fi
# Si estamos en modo user montamos el repositorio en modo lectura.
[ "$DEST" == "REPO" -a "$boot" != "admin" ] && CambiarAcceso user
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
exit $RETVAL

View File

@ -0,0 +1,98 @@
#!/bin/bash
#___________________________________________________________________
#
# CREAR IMAGEN INCREMENTAL
#___________________________________________________________________
#
# Parámetros recibidos desde el cliente:
#
# $1 Número de disco
# $2 Número de particion
# $3 Nombre canónico de la imagen básica (sin extensión)
# $4 Dirección del repositorio
# $5 Nombre canónico de la imagen incremental (sin extensión)
# $6 Es una cadena "nnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnn" donde "n" vale 0 ó 1.
# 1XX: Gestionar fichero completo en lugar de diferencas
# X1X: Eliminar archivos de la imagen que no estén en la partición
# XX1: Comprimir archivos para enviarlos por la red
# El valor X indica que no importa el valor que tenga el dato
# $7 Es una cadena "nnnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnnn" donde "n" vale 0 ó 1.
# 1XXX: Borrar la imagen incremental del repositorio antes de crearla
# X1XX: Copiar imagen incremental también a la cache
# XX1X: Borrar previamente la imagen incremental de la cache antes de copiarla
# XXX1: No borrar archivos en destino
# El valor X indica que no importa el valor que tenga el dato
# $8 Método de syncronización 1=Sincronización1 2=Sincronizacion2
# $9 Ruta de origen de la Imagen (Carpeta)
#___________________________________________________________________
#
# Control parámetros
#___________________________________________________________________
PROG="$(basename $0)"
if [ $# -lt 8 ]; then
usage=" ndisco nparticion nombre_imagen_basica ip_repositorio nombre_imagen_incremental"
usage="$usage copiar_a_caché Borrar_cache_previamente Ruta_origen"
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG $usage"
exit $?
fi
#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 $*"
# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura,
PATH=$PATH:$(dirname $0)
CLIENTIP=$(ogGetIpAddress)
[ "$4" == "$CLIENTIP" ] && DEST=CACHE || DEST=REPO
if [ "$DEST" == "REPO" -a "$boot" != "admin" ]; then
CambiarAcceso admin &>> $OGLOGFILE
RETVAL=$?
[ $RETVAL -gt 0 ] && exit $RETVAL
fi
if [ $8 -eq 1 ]; then
#sincronizacion1
ogCrearSoftIncremental "$@"
RETVAL=$?
fi
if [ $8 -eq 2 ]; then
#sincronizacion 2
flag=$6
WHOLE=${flag:0:1}
DELFILE=${flag:1:1}
COMPRESS=${flag:2:1}
# Nota los valores se pasan como variables de entorno,
# la idea es que mas adelante vayan en el fichero PXE.
[ $WHOLE -eq 1 ] && export ogrsyncw=true || export ogrsyncw=false
[ $DELFILE -eq 1 ] && export ogrsyncdel=true || export ogrsyncdel=false
[ $COMPRESS -eq 1 ] && export ogrsyncz=true || export ogrsyncz=false
# REPOSITORIO: Si la ip es la del propio equipo CACHE, si no REPO
#CLIENTIP=$(ogGetIpAddress)
#[ "$4" == "$CLIENTIP" ] && DEST=CACHE || DEST=REPO
createDiffImage $1 $2 $DEST "$3" "$5"
RETVAL=$?
fi
# Si estamos en modo user montamos el repositorio en modo lectura.
[ "$DEST" == "REPO" -a "$boot" != "admin" ] && CambiarAcceso user
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
exit $RETVAL

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,15 @@
#!/bin/bash
#_______________________________________________________________________________________________________________________________
#
# PARAMETROS RECIBIDOS DESDE EL CLIENTE:
# $1 disco
# $2 par=Número de particion
# $3 Nombre canónico de la imagen
# $4 Dirección IP del repositorio
# $5 Protocolo UNICAST MULTICAST TORRENT
# $6 Opciones del protocolo
#_______________________________________________________________________________________________________________________________
# Llamar al script de despliegue "deployImage".
deployImage "$4" "$3" "$1" "$2" "$5" "$6" "$7" "$8" || exit $?

View File

@ -0,0 +1,89 @@
#!/bin/bash
#___________________________________________________________________
#
# RESTAURAR IMAGEN BÁSICA
#___________________________________________________________________
#
# Parámetros recibidos desde el cliente:
#
# $1 Número de disco
# $2 Número de particion
# $3 Nombre canónico de la imagen básica (sin extensión)
# $4 Dirección del repositorio
# $5 Tipo de transmisión 0=Unicast 1=Multicast
# $6 Es una cadena "nnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnn" donde "n" vale 0 ó 1.
# 1XX: Gestionar fichero completo en lugar de diferencas
# X1X: Eliminar archivos de la partición que no estén en la imagen
# XX1: Comprimir archivos para enviarlos por la red
# El valor X indica que no importa el valor que tenga el dato
# $7 Es una cadena "nnnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnnn" donde "n" vale 0 ó 1.
# 1XXX: Borrar la particion de destino antes de restaurar la imagen basica
# X1XX: Copiar Imagen básica también a la cache
# XX1X: Borrar previamente la imagen basica de la cache antes de copiarla
# XXX1: No borrar archivos en destino
# El valor X indica que no importa el valor que tenga el dato
# $8 Método de clonación 0=Desde caché 1=Desde repositorio
# $9 Metodo de sincronizacion 1=Sincronización1 2=Sincronizacion2
# $10 Ruta de origen de la Imagen (Carpeta)
#___________________________________________________________________
#
# Control parámetros
#___________________________________________________________________
PROG="$(basename $0)"
if [ $# -lt 9 ]; then
usage=" ndisco nparticion nombre_imagen_basica ip_repositorio copiar_a_caché "
usage="$usage Borrar_cache_previamente metodo_clonación Ruta_origen"
ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG $usage"
exit $?
fi
#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 " " > $OGLOGCOMMAND
# Registro de inicio de ejecución
ogEcho log session "$MSG_INTERFACE_START $0 $*"
if [ $9 -eq 1 ]; then
#sincronizacion1
ogRestaurarImagenBasica "$@"
RETVAL=$?
fi
if [ $9 -eq 2 ]; then
#sincronizacion2
# Opciones de clonacion
flag=$6
WHOLE=${flag:0:1}
DELFILE=${flag:1:1}
COMPRESS=${flag:2:1}
# Nota los valores se pasan como variables de entorno,
# la idea es que mas adelante vayan en el fichero PXE.
[ $WHOLE -eq 1 ] && export ogrsyncw=true || export ogrsyncw=false
[ $DELFILE -eq 1 ] && export ogrsyncdel=true || export ogrsyncdel=false
[ $COMPRESS -eq 1 ] && export ogrsyncz=true || export ogrsyncz=false
# Origen de la imagen.
[ $8 -eq 0 ] && DEST="CACHE" || DEST="REPO"
# Protocolo de clonacion y opciones
PROTO=${5%_*}
OPT=${5#*_}
restoreBaseImage $DEST "$3" $1 $2 $PROTO $OPT
RETVAL=$?
fi
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
exit $RETVAL

View File

@ -0,0 +1,82 @@
#!/bin/bash
#___________________________________________________________________
#
# RESTAURAR IMAGEN INCREMENTAL
#___________________________________________________________________
#
# Parámetros recibidos desde el cliente:
#
# $1 Número de disco
# $2 Número de particion
# $3 Nombre canónico de la imagen básica (sin extensión)
# $4 Dirección del repositorio
# $5 Nombre canónico del software incremental (sin extensión)
# $6 Tipo de transmisión 0=Unicast 1=Multicast
# $7 Es una cadena "nnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnn" donde "n" vale 0 ó 1.
# 1XX: Gestionar fichero completo en lugar de diferencas
# X1X: Eliminar archivos de la partición que no estén en la imagen
# XX1: Comprimir archivos para enviarlos por la red
# El valor X indica que no importa el valor que tenga el dato
# $8 Es una cadena "nnnn" tipo flags que codifica varios parametros.
# Tiene el formato "nnnn" donde "n" vale 0 ó 1.
# 1XXX: Borrar la particion de destino antes de restaurar la imagen basica
# X1XX: Copiar Imagen básica también a la cache
# XX1X: Borrar previamente la imagen basica de la cache antes de copiarla
# XXX1: No borrar archivos en destino
# El valor X indica que no importa el valor que tenga el dato
# $9 Método de clonación 0=Desde caché 1=Desde repositorio
# $10 Metodo de sincronizacion 1=Sincronización1 2=Sincronizacion2
# $11 Ruta de origen de la Imagen (Carpeta)
#___________________________________________________________________
#
# Control parámetros
#___________________________________________________________________
#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
# Registro de inicio de ejecución
ogEcho log session "$MSG_INTERFACE_START $0 $*"
if [ ${10} -eq 1 ]; then
#sincronizacion1
ogRestaurarSoftIncremental "$@"
RETVAL=$?
fi
if [ ${10} -eq 2 ]; then
#sincronizacion2
# Opciones de clonacion
flag=$7
WHOLE=${flag:0:1}
DELFILE=${flag:1:1}
COMPRESS=${flag:2:1}
# Nota los valores se pasan como variables de entorno,
# la idea es que mas adelante vayan en el fichero PXE.
[ $WHOLE -eq 1 ] && export ogrsyncw=true || export ogrsyncw=false
[ $DELFILE -eq 1 ] && export ogrsyncdel=true || export ogrsyncdel=false
[ $COMPRESS -eq 1 ] && export ogrsyncz=true || export ogrsyncz=false
# Origen de la imagen.
[ $9 -eq 0 ] && DEST="CACHE" || DEST="REPO"
# Protocolo de clonacion y opciones
PROTO=${6%_*}
OPT=${6#*_}
restoreDiffImage $DEST "$3" "$5" $1 $2 $PROTO $OPT
RETVAL=$?
fi
# Registro de fin de ejecución
ogEcho log session "$MSG_INTERFACE_END $RETVAL"
exit $RETVAL

View File

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

View File

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

View File

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