source: installer/opengnsys_update.sh @ ce40d43

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since ce40d43 was 11b812d, checked in by ramon <ramongomez@…>, 12 years ago

#565 Instalardor y actualizador incluyen paquete para crear sistema de fichero para imagen diferencial.

git-svn-id: https://opengnsys.es/svn/branches/version1.0@3710 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 26.4 KB
RevLine 
[a0867b37]1#!/bin/bash
2#/**
3#@file    opengnsys_update.sh
4#@brief   Script actualización de OpenGnSys
5#@warning No se actualiza BD, ni ficheros de configuración.
6#@version 0.9 - basado en opengnsys_installer.sh
7#@author  Ramón Gómez - ETSII Univ. Sevilla
8#@date    2010/01/27
[c1e00e4]9#@version 1.0 - adaptación a OpenGnSys 1.0
10#@author  Ramón Gómez - ETSII Univ. Sevilla
11#@date    2011/03/02
[64dd765]12#@version 1.0.1 - control de auto actualización del script
13#@author  Ramón Gómez - ETSII Univ. Sevilla
14#@date    2011/05/17
[739fb00]15#@version 1.0.2a - obtiene valor de dirección IP por defecto
16#@author  Ramón Gómez - ETSII Univ. Sevilla
17#@date    2012/01/18
[1175096]18#@version 1.0.3 - Compatibilidad con Debian y auto configuración de acceso a BD.
[7bb72f7]19#@author  Ramón Gómez - ETSII Univ. Sevilla
[1175096]20#@date    2012/03/12
[db9e706]21#@version 1.0.4 - Detector de distribución y compatibilidad con CentOS.
22#@author  Ramón Gómez - ETSII Univ. Sevilla
23#@date    2012/05/04
[dc103b6]24#@version 1.0.5 - Actualizar BD en la misma versión y compatibilidad con Fedora (systemd).
[0b8a1f1]25#@author  Ramón Gómez - ETSII Univ. Sevilla
26#@date    2012/12/14
[a0867b37]27#*/
28
29
[1175096]30####  AVISO: NO EDITAR variables de configuración.
31####  WARNING: DO NOT EDIT configuration variables.
32INSTALL_TARGET=/opt/opengnsys           # Directorio de instalación
[295b4ab]33OPENGNSYS_CLIENTUSER="opengnsys"        # Usuario Samba
34
35
[a0867b37]36# Sólo ejecutable por usuario root
[6ef01d9]37if [ "$(whoami)" != 'root' ]; then
[a0867b37]38        echo "ERROR: this program must run under root privileges!!"
39        exit 1
40fi
[4e51cb0]41# Error si OpenGnSys no está instalado (no existe el directorio del proyecto)
42if [ ! -d $INSTALL_TARGET ]; then
43        echo "ERROR: OpenGnSys is not installed, cannot update!!"
44        exit 1
45fi
[1175096]46# Cargar configuración de acceso a la base de datos.
47if [ -r $INSTALL_TARGET/etc/ogAdmServer.cfg ]; then
48        source $INSTALL_TARGET/etc/ogAdmServer.cfg
49elif [ -r $INSTALL_TARGET/etc/ogAdmAgent.cfg ]; then
50        source $INSTALL_TARGET/etc/ogAdmAgent.cfg
51fi
52OPENGNSYS_DATABASE=${OPENGNSYS_DATABASE:-"$CATALOG"}            # Base datos
53OPENGNSYS_DBUSER=${OPENGNSYS_DBUSER:-"$USUARIO"}                # Usuario de acceso
54OPENGNSYS_DBPASSWORD=${OPENGNSYS_DBPASSWORD:-"$PASSWORD"}       # Clave del usuario
55if [ -z "$OPENGNSYS_DATABASE" -o -z "$OPENGNSYS_DBUSER" -o -z "$OPENGNSYS_DBPASSWORD" ]; then
56        echo "ERROR: set OPENGNSYS_DATABASE, OPENGNSYS_DBUSER and OPENGNSYS_DBPASSWORD"
57        echo "       variables, and run this script again."
58fi
[a0867b37]59
60# Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1).
61PROGRAMDIR=$(readlink -e $(dirname "$0"))
[64dd765]62PROGRAMNAME=$(basename "$0")
[07c3a59]63OPENGNSYS_SERVER="www.opengnsys.es"
[a0867b37]64if [ -d "$PROGRAMDIR/../installer" ]; then
[6ef01d9]65        USESVN=0
[a0867b37]66else
[6ef01d9]67        USESVN=1
[a0867b37]68fi
[eb9424f]69SVN_URL="http://$OPENGNSYS_SERVER/svn/branches/version1.0/"
[a0867b37]70
71WORKDIR=/tmp/opengnsys_update
72mkdir -p $WORKDIR
73
[57f7e9c]74OGLOGFILE=$INSTALL_TARGET/log/opengnsys_installation.log
75LOG_FILE=/tmp/$(basename $OGLOGFILE)
[a0867b37]76
77
78
79#####################################################################
80####### Algunas funciones útiles de propósito general:
81#####################################################################
[295b4ab]82
[db9e706]83# Generar variables de configuración del actualizador
84# Variables globales:
[2e38f60]85# - OSDISTRIB - distribución Linux
[db9e706]86# - DEPENDENCIES - array de dependencias que deben estar instaladas
87# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKG - comandos para gestión de paquetes
[2e38f60]88# - APACHECFGDIR, APACHESERV, DHCPSERV - configuración y servicios
[db9e706]89function autoConfigure()
90{
[2e38f60]91local i
92
[db9e706]93# Detectar sistema operativo del servidor (debe soportar LSB).
94OSDISTRIB=$(lsb_release -is 2>/dev/null)
95
96# Configuración según la distribución de Linux.
97case "$OSDISTRIB" in
98        Ubuntu|Debian|LinuxMint)
[11b812d]99                DEPENDENCIES=( php5-ldap btrfs-tools )
[db9e706]100                UPDATEPKGLIST="apt-get update"
101                INSTALLPKGS="apt-get -y install --force-yes"
102                CHECKPKG="dpkg -s \$package 2>/dev/null | grep -q \"Status: install ok\""
[2e38f60]103                APACHEUSER="www-data"
104                APACHEGROUP="www-data"
[db9e706]105                ;;
106        Fedora|CentOS)
[11b812d]107                DEPENDENCIES=( php-ldap btrfs-progs )
[db9e706]108                INSTALLPKGS="yum install -y"
109                CHECKPKG="rpm -q --quiet \$package"
[2a5c1a4]110                APACHEUSER="apache"
111                APACHEGROUP="apache"
[db9e706]112                ;;
[de8bbb1]113        *)      # Otras distribuciones.
[0b6304e]114                ;;
[db9e706]115esac
[2e38f60]116for i in apache2 httpd; do
117        [ -f /etc/$i ] && APACHECFGDIR="/etc/$i"
118        [ -f /etc/init.d/$i ] && APACHESERV="/etc/init.d/$i"
119done
120for i in dhcpd dhcpd3-server isc-dhcp-server; do
121        [ -f /etc/init.d/$i ] && DHCPSERV="/etc/init.d/$i"
122done
[db9e706]123}
124
125
[64dd765]126# Comprobar auto-actualización.
127function checkAutoUpdate()
128{
129        local update=0
130
131        # Actaulizar el script si ha cambiado o no existe el original.
132        if [ $USESVN -eq 1 ]; then
[7b0c6ff]133                svn export $SVN_URL/installer/$PROGRAMNAME
[d372e6e]134                if ! diff -q $PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
[64dd765]135                        mv $PROGRAMNAME $INSTALL_TARGET/lib
136                        update=1
137                else
138                        rm -f $PROGRAMNAME
139                fi
140        else
[d372e6e]141                if ! diff -q $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
[64dd765]142                        cp -a $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib
143                        update=1
144                fi
145        fi
146
147        return $update
148}
149
150
[a0867b37]151function getDateTime()
152{
[5eb61a6]153        date "+%Y%m%d-%H%M%S"
[a0867b37]154}
155
156# Escribe a fichero y muestra por pantalla
157function echoAndLog()
158{
[5eb61a6]159        echo $1
[6ef01d9]160        DATETIME=`getDateTime`
161        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
[a0867b37]162}
163
164function errorAndLog()
165{
[5eb61a6]166        echo "ERROR: $1"
167        DATETIME=`getDateTime`
[6ef01d9]168        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
[a0867b37]169}
170
171
172#####################################################################
173####### Funciones de copia de seguridad y restauración de ficheros
174#####################################################################
175
176# Hace un backup del fichero pasado por parámetro
177# deja un -last y uno para el día
178function backupFile()
179{
180        if [ $# -ne 1 ]; then
181                errorAndLog "${FUNCNAME}(): invalid number of parameters"
182                exit 1
183        fi
184
185        local fichero=$1
186        local fecha=`date +%Y%m%d`
187
188        if [ ! -f $fichero ]; then
189                errorAndLog "${FUNCNAME}(): file $fichero doesn't exists"
190                return 1
191        fi
192
[ebbbfc01]193        echoAndLog "${FUNCNAME}(): Making $fichero back-up"
[a0867b37]194
195        # realiza una copia de la última configuración como last
[6ef01d9]196        cp -a $fichero "${fichero}-LAST"
[a0867b37]197
198        # si para el día no hay backup lo hace, sino no
199        if [ ! -f "${fichero}-${fecha}" ]; then
[6ef01d9]200                cp -a $fichero "${fichero}-${fecha}"
[a0867b37]201        fi
202}
203
204# Restaura un fichero desde su copia de seguridad
205function restoreFile()
206{
207        if [ $# -ne 1 ]; then
208                errorAndLog "${FUNCNAME}(): invalid number of parameters"
209                exit 1
210        fi
211
212        local fichero=$1
213
[ebbbfc01]214        echoAndLog "${FUNCNAME}(): restoring file $fichero"
[a0867b37]215        if [ -f "${fichero}-LAST" ]; then
[6ef01d9]216                cp -a "$fichero-LAST" "$fichero"
[a0867b37]217        fi
218}
219
220
221#####################################################################
[295b4ab]222####### Funciones de acceso a base de datos
223#####################################################################
224
225# Actualizar la base datos
226function importSqlFile()
227{
228        if [ $# -ne 4 ]; then
229                errorAndLog "${FNCNAME}(): invalid number of parameters"
230                exit 1
231        fi
232
233        local dbuser="$1"
234        local dbpassword="$2"
235        local database="$3"
236        local sqlfile="$4"
237        local tmpfile=$(mktemp)
[632bd45]238        local mycnf=/tmp/.my.cnf.$$
[295b4ab]239        local status
240
241        if [ ! -r $sqlfile ]; then
242                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
243                return 1
244        fi
245
246        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
247        chmod 600 $tmpfile
248        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
249            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile
[632bd45]250        # Componer fichero con credenciales de conexión. 
251        touch $mycnf
252        chmod 600 $mycnf
253        cat << EOT > $mycnf
[c073224]254[client]
[09bf701]255user=$dbuser
256password=$dbpassword
[632bd45]257EOT
258        # Ejecutar actualización y borrar fichero de credenciales.
[09bf701]259        mysql --defaults-extra-file=$mycnf --default-character-set=utf8 -D "$database" < $tmpfile
[295b4ab]260        status=$?
[632bd45]261        rm -f $mycnf $tmpfile
[295b4ab]262        if [ $status -ne 0 ]; then
263                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
264                return 1
265        fi
266        echoAndLog "${FUNCNAME}(): file imported to database $database"
267        return 0
268}
269
270
271#####################################################################
[a0867b37]272####### Funciones de instalación de paquetes
273#####################################################################
274
275# Instalar las deependencias necesarias para el actualizador.
[64dd765]276function installDependencies()
[a0867b37]277{
[db9e706]278        local package
279
[a0867b37]280        if [ $# = 0 ]; then
281                echoAndLog "${FUNCNAME}(): no deps needed."
[c1e00e4]282        else
283                while [ $# -gt 0 ]; do
[db9e706]284                        package="$1"
285                        eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $1"
[c1e00e4]286                        shift
287                done
288                if [ -n "$INSTALLDEPS" ]; then
[db9e706]289                        $UPDATEPKGLIST
290                        $INSTALLPKGS $INSTALLDEPS
[c1e00e4]291                        if [ $? -ne 0 ]; then
292                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS."
293                                return 1
294                        fi
295                fi
296        fi
[a0867b37]297}
298
299
300#####################################################################
301####### Funciones para el manejo de Subversion
302#####################################################################
303
304function svnExportCode()
305{
306        if [ $# -ne 1 ]; then
307                errorAndLog "${FUNCNAME}(): invalid number of parameters"
308                exit 1
309        fi
310
[27dc5ff]311        local url="$1"
[a0867b37]312
313        echoAndLog "${FUNCNAME}(): downloading subversion code..."
314
[7ad4465]315        svn checkout "${url}" opengnsys
[a0867b37]316        if [ $? -ne 0 ]; then
317                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
318                return 1
319        fi
320        echoAndLog "${FUNCNAME}(): subversion code downloaded"
321        return 0
322}
323
324
325############################################################
326###  Detectar red
327############################################################
328
[07c3a59]329# Comprobar si existe conexión.
330function checkNetworkConnection()
331{
332        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
333        wget --spider -q $OPENGNSYS_SERVER
334}
335
[739fb00]336# Obtener los parámetros de red del servidor.
337function getNetworkSettings()
338{
339        # Variables globales definidas:
340        # - SERVERIP:   IP local de la interfaz por defecto.
341
342        local DEVICES
343        local dev
344
345        echoAndLog "${FUNCNAME}(): Detecting network parameters."
346        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
347        for dev in $DEVICES; do
348                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
349        done
350}
351
[a0867b37]352
353#####################################################################
354####### Funciones específicas de la instalación de Opengnsys
355#####################################################################
356
[45f1fe8]357# Actualizar cliente OpenGnSys
[295b4ab]358function updateClientFiles()
[45f1fe8]359{
360        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Client files."
361        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
362        if [ $? -ne 0 ]; then
363                errorAndLog "${FUNCNAME}(): error while updating client structure"
[51b179a]364                exit 1
[45f1fe8]365        fi
366        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
367       
368        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Cloning Engine files."
[51b179a]369        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
[45f1fe8]370        if [ $? -ne 0 ]; then
371                errorAndLog "${FUNCNAME}(): error while updating engine files"
[51b179a]372                exit 1
[45f1fe8]373        fi
374       
[51b179a]375        echoAndLog "${FUNCNAME}(): client files update success."
[45f1fe8]376}
[4e51cb0]377
[3ce53a7]378# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
379function apacheConfiguration ()
[4e51cb0]380{
[2e38f60]381        # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2).
382        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
[3ce53a7]383                echoAndLog "${FUNCNAME}(): Configuring HTTPS access..."
[2e38f60]384                mv $APACHECFGDIR/sites-available/opengnsys.conf $APACHECFGDIR/sites-available/opengnsys
[3ce53a7]385                a2ensite default-ssl
386                a2enmod ssl
[3e24aa5]387                a2dissite opengnsys.conf
[3ce53a7]388                a2ensite opengnsys
[2e38f60]389                $APACHESERV restart
[3ce53a7]390        fi
391
392        # Variables de ejecución de Apache.
[4e51cb0]393        # - APACHE_RUN_USER
394        # - APACHE_RUN_GROUP
[2e38f60]395        if [ -f $APACHECFGDIR/envvars ]; then
396                source $APACHECFGDIR/envvars
[4e51cb0]397        fi
[2e38f60]398        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
[de8bbb1]399        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
[4e51cb0]400}
401
[a0867b37]402# Copiar ficheros del OpenGnSys Web Console.
403function updateWebFiles()
404{
[d655cc4]405        local ERRCODE
[a0867b37]406        echoAndLog "${FUNCNAME}(): Updating web files..."
[d655cc4]407        backupFile $INSTALL_TARGET/www/controlacceso.php
408        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
[1db2ed8]409        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
[d655cc4]410        ERRCODE=$?
411        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
[c1e00e4]412        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
[d655cc4]413        if [ $ERRCODE != 0 ]; then
[a0867b37]414                errorAndLog "${FUNCNAME}(): Error updating web files."
415                exit 1
416        fi
[d655cc4]417        restoreFile $INSTALL_TARGET/www/controlacceso.php
[a0867b37]418        # Cambiar permisos para ficheros especiales.
[e6d22c6]419        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
[a0867b37]420        echoAndLog "${FUNCNAME}(): Web files updated successfully."
421}
422
[72134d5]423# Copiar carpeta de Interface
[64dd765]424function updateInterfaceAdm()
[72134d5]425{
[27dc5ff]426        local errcode=0
[72134d5]427         
428        # Crear carpeta y copiar Interface
429        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
430        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
431        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
[27dc5ff]432        errcoce=$?
[72134d5]433        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
[27dc5ff]434        if [ $errcode -ne 0 ]; then
[72134d5]435                echoAndLog "${FUNCNAME}(): error while updating admin interface"
436                exit 1
437        fi
438        chmod -R +x $INSTALL_TARGET/client/interfaceAdm
[b6f1726]439        chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
[f6c1d2b]440        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
[72134d5]441        echoAndLog "${FUNCNAME}(): Admin interface updated successfully."
442}
[a0867b37]443
[5d6bf97]444# Crear documentación Doxygen para la consola web.
445function makeDoxygenFiles()
446{
447        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
448        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
449                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
450        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
451                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
452                return 1
453        fi
[45f1fe8]454        rm -fr "$INSTALL_TARGET/www/api"
[15b2a4e]455        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
456        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
[5d6bf97]457        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
458        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
459}
460
461
[a0867b37]462# Crea la estructura base de la instalación de opengnsys
463function createDirs()
464{
[eb9424f]465        # Crear estructura de directorios.
[a0867b37]466        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
[7bb72f7]467        local dir
468
[cfad47b]469        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
470        mkdir -p ${INSTALL_TARGET}/{client,images}
[a0867b37]471        mkdir -p ${INSTALL_TARGET}/log/clients
[eb9424f]472        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
[7bb72f7]473        # Detectar directorio de instalación de TFTP.
474        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
475                for dir in /var/lib/tftpboot /srv/tftp; do
476                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
477                done
478        fi
[cfad47b]479        mkdir -p ${INSTALL_TARGET}/tftpboot/{pxelinux.cfg,menu.lst}
[a0867b37]480        if [ $? -ne 0 ]; then
481                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
482                return 1
483        fi
484
[eb9424f]485        # Crear usuario ficticio.
486        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
487                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
488        else
489                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
490                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
491                if [ $? -ne 0 ]; then
492                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
493                        return 1
494                fi
495        fi
496
497        # Establecer los permisos básicos.
498        echoAndLog "${FUNCNAME}(): setting directory permissions"
[cfad47b]499        chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
[dc103b6]500        mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples
[e979faf]501        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
[cfad47b]502        chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
[eb9424f]503        if [ $? -ne 0 ]; then
504                errorAndLog "${FUNCNAME}(): error while setting permissions"
505                return 1
506        fi
507
[57f7e9c]508        # Mover el fichero de registro al directorio de logs.
509        echoAndLog "${FUNCNAME}(): moving update log file"
510        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
[7669bca]511        chmod 600 $LOG_FILE
[57f7e9c]512
[a0867b37]513        echoAndLog "${FUNCNAME}(): directory paths created"
514        return 0
515}
516
517# Copia ficheros de configuración y ejecutables genéricos del servidor.
[64dd765]518function updateServerFiles()
[bb30a50]519{
[c1e00e4]520        # No copiar ficheros del antiguo cliente Initrd
[873cf1e]521        local SOURCES=( repoman/bin \
[c1e00e4]522                        server/bin \
[873cf1e]523                        server/tftpboot \
[bb30a50]524                        installer/opengnsys_uninstall.sh \
[a8bb7641]525                        installer/install_ticket_wolunicast.sh \
[873cf1e]526                        doc )
527        local TARGETS=( bin \
528                        bin \
529                        tftpboot \
[9a2c0f9d]530                        lib/opengnsys_uninstall.sh \
531                        lib/install_ticket_wolunicast.sh \
[873cf1e]532                        doc )
[a0867b37]533
534        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
535                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
536                exit 1
537        fi
538
539        echoAndLog "${FUNCNAME}(): updating files in server directories"
540        pushd $WORKDIR/opengnsys >/dev/null
541        local i
542        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
[27dc5ff]543                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
[4057c5d]544                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
[aa36857]545                else
[56f100f]546                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
[aa36857]547                fi
[a0867b37]548        done
549        popd >/dev/null
[df3cd7f]550        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
[f80f839]551        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
[df3cd7f]552                echoAndLog "${FUNCNAME}(): updating DHCP files"
[f80f839]553                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
[2e38f60]554                $DHCPSERV restart
[df3cd7f]555                NEWFILES="/etc/dhcp*/dhcpd*.conf"
556        fi
[d372e6e]557        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
[df3cd7f]558                echoAndLog "${FUNCNAME}(): updating new init file"
559                backupFile /etc/init.d/opengnsys
560                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
561                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
562        fi
[984093e]563        if grep -q "UrlMsg=.*msgbrowser.php" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
[df3cd7f]564                echoAndLog "${FUNCNAME}(): updating new client config file"
565                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
566                perl -pi -e 's!UrlMsg=.*msgbrowser\.php!UrlMsg=http://localhost/cgi-bin/httpd-log\.sh!g' $INSTALL_TARGET/client/etc/ogAdmClient.cfg
567                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
[f80f839]568        fi
[9ee62ad]569        echoAndLog "${FUNCNAME}(): updating cron files"
[db9e706]570        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
571        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
572        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
[da8db11]573        echoAndLog "${FUNCNAME}(): server files updated successfully."
[a0867b37]574}
575
576####################################################################
577### Funciones de compilación de código fuente de servicios
578####################################################################
579
[bb30a50]580# Recompilar y actualiza los serivicios y clientes.
[64dd765]581function compileServices()
[a0867b37]582{
[bb30a50]583        local hayErrores=0
584
585        # Compilar OpenGnSys Server
586        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Admin Server"
587        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
588        make && mv ogAdmServer $INSTALL_TARGET/sbin
589        if [ $? -ne 0 ]; then
590                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
591                hayErrores=1
592        fi
593        popd
594        # Compilar OpenGnSys Repository Manager
595        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Repository Manager"
596        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
597        make && mv ogAdmRepo $INSTALL_TARGET/sbin
598        if [ $? -ne 0 ]; then
599                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
600                hayErrores=1
601        fi
602        popd
603        # Compilar OpenGnSys Agent
604        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Agent"
605        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
606        make && mv ogAdmAgent $INSTALL_TARGET/sbin
607        if [ $? -ne 0 ]; then
608                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
609                hayErrores=1
610        fi
611        popd
612
[a0867b37]613        # Compilar OpenGnSys Client
[bb30a50]614        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Client"
[72134d5]615        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
[e473667]616        make && mv ogAdmClient $INSTALL_TARGET/client/bin
[a0867b37]617        if [ $? -ne 0 ]; then
618                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Client"
619                hayErrores=1
620        fi
621        popd
622
623        return $hayErrores
624}
625
626
627####################################################################
[4e51cb0]628### Funciones instalacion cliente OpenGnSys
[a0867b37]629####################################################################
630
[595f397]631# Actualizar cliente OpenGnSys
[c1e00e4]632function updateClient()
633{
[df3cd7f]634        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
[dc103b6]635        #local FILENAME=ogLive-precise-3.2.0-23-generic-r3257.iso       # 1.0.4-rc2
636        local FILENAME=ogLive-quantal-3.7.6-030706-generic-r3619.iso    # 1.0.5-rc2
[0b85cc93]637        local SOURCEFILE=$DOWNLOADURL/$FILENAME
638        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
639        local SOURCELENGTH
640        local TARGETLENGTH
641        local TMPDIR=/tmp/${FILENAME%.iso}
[a63345ac]642        local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img
643        local SAMBAPASS
[0b85cc93]644
645        # Comprobar si debe actualizarse el cliente.
[c3cc6b0]646        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
[d168a46]647        TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}')
[d4e90c1]648        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
[0b85cc93]649        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
650                echoAndLog "${FUNCNAME}(): Loading Client"
651                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
652                if [ ! -s $TARGETFILE ]; then
653                        errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
654                        return 1
655                fi
[a63345ac]656                # Obtener la clave actual de acceso a Samba para restaurarla.
657                if [ -f $OGINITRD ]; then
658                        SAMBAPASS=$(gzip -dc $OGINITRD | \
659                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
[c3cc6b0]660                                    grep "^[    ]*OPTIONS=" | \
[a63345ac]661                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
662                fi
663                # Montar la imagen ISO del ogclient, actualizar ficheros y desmontar.
664                echoAndLog "${FUNCNAME}(): Updatting ogclient files"
665                mkdir -p $TMPDIR
666                mount -o loop,ro $TARGETFILE $TMPDIR
667                rsync -irlt $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
668                umount $TMPDIR
669                rmdir $TMPDIR
670                # Recuperar la clave de acceso a Samba.
671                if [ -n "$SAMBAPASS" ]; then
672                        echoAndLog "${FUNCNAME}(): Restoring client access key"
673                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
674                                        $INSTALL_TARGET/bin/setsmbpass
675                fi
676                # Establecer los permisos.
677                find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
678                find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
679                chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/tftpboot/ogclient
680                chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/{menu.lst,pxelinux.cfg}
[e1c01217]681               
[e8963d0]682                # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache
[7bb72f7]683                cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot
684                cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot
[e1c01217]685               
[a63345ac]686                echoAndLog "${FUNCNAME}(): Client update successfully"
[0b85cc93]687        else
[a63345ac]688                echoAndLog "${FUNCNAME}(): Client is already updated"
[c1e00e4]689        fi
690}
[a0867b37]691
[eb9424f]692# Resumen de actualización.
693function updateSummary()
694{
695        # Actualizar fichero de versión y revisión.
696        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
[57f7e9c]697        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
[eb9424f]698
699        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
700        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
701
702        echo
703        echoAndLog "OpenGnSys Update Summary"
[df3cd7f]704        echo       "========================"
705        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
[57f7e9c]706        echoAndLog "Update log file:                  $LOG_FILE"
[df3cd7f]707        if [ -n "$NEWFILES" ]; then
708                echoAndLog "Check the new config files:       $(echo $NEWFILES)"
709        fi
[eb9424f]710        echo
711}
712
713
[a0867b37]714
715#####################################################################
[3320409]716####### Proceso de actualización de OpenGnSys
[a0867b37]717#####################################################################
718
719
720echoAndLog "OpenGnSys update begins at $(date)"
721
[bb30a50]722pushd $WORKDIR
723
[27dc5ff]724# Comprobar si hay conexión y detectar parámetros de red por defecto.
725checkNetworkConnection
726if [ $? -ne 0 ]; then
727        errorAndLog "Error connecting to server. Causes:"
728        errorAndLog " - Network is unreachable, review devices parameters."
729        errorAndLog " - You are inside a private network, configure the proxy service."
730        errorAndLog " - Server is temporally down, try agian later."
731        exit 1
732fi
[739fb00]733getNetworkSettings
[27dc5ff]734
[64dd765]735# Comprobar auto-actualización del programa.
736if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
737        checkAutoUpdate
738        if [ $? -ne 0 ]; then
[f580c51]739                echoAndLog "OpenGnSys updater has been overwritten."
740                echoAndLog "Please, re-execute this script."
[64dd765]741                exit
742        fi
743fi
744
[db9e706]745# Detectar datos de auto-configuración del instalador.
746autoConfigure
747
[bb30a50]748# Instalar dependencias.
[db9e706]749installDependencies $DEPENDENCIES
[a0867b37]750if [ $? -ne 0 ]; then
751        errorAndLog "Error: you may install all needed dependencies."
752        exit 1
753fi
754
755# Arbol de directorios de OpenGnSys.
756createDirs ${INSTALL_TARGET}
757if [ $? -ne 0 ]; then
758        errorAndLog "Error while creating directory paths!"
759        exit 1
760fi
761
762# Si es necesario, descarga el repositorio de código en directorio temporal
763if [ $USESVN -eq 1 ]; then
764        svnExportCode $SVN_URL
765        if [ $? -ne 0 ]; then
766                errorAndLog "Error while getting code from svn"
767                exit 1
768        fi
769else
770        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
771fi
772
[295b4ab]773# Si existe fichero de actualización de la base de datos; aplicar cambios.
774INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
775REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
[0b8a1f1]776if [ "$INSTVERSION" == "$REPOVERSION" ]; then
777        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION.sql"
778else
779        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
780fi
[295b4ab]781if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
[0b8a1f1]782        echoAndLog "Updating tables from file: $(basename $OPENGNSYS_DBUPDATEFILE)"
[295b4ab]783        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
784else
785        echoAndLog "Database unchanged."
786fi
787
788# Actualizar ficheros complementarios del servidor
[a0867b37]789updateServerFiles
790if [ $? -ne 0 ]; then
[da8db11]791        errorAndLog "Error updating OpenGnSys Server files"
[a0867b37]792        exit 1
793fi
794
[295b4ab]795# Actualizar ficheros del cliente
796updateClientFiles
797updateInterfaceAdm
[45f1fe8]798
[295b4ab]799# Actualizar páqinas web
[3ce53a7]800apacheConfiguration
[a0867b37]801updateWebFiles
802if [ $? -ne 0 ]; then
[da8db11]803        errorAndLog "Error updating OpenGnSys Web Admin files"
[a0867b37]804        exit 1
805fi
[5d6bf97]806# Generar páginas Doxygen para instalar en el web
807makeDoxygenFiles
[a0867b37]808
[bb30a50]809# Recompilar y actualizar los servicios del sistema
810compileServices
811
812# Actaulizar ficheros auxiliares del cliente
[a0867b37]813updateClient
814if [ $? -ne 0 ]; then
815        errorAndLog "Error updating clients"
816        exit 1
817fi
818
[3320409]819# Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
[ebbbfc01]820if [ -f /tmp/dstate ]; then
821        rm -f /tmp/dstate
[3320409]822fi
823
[eb9424f]824# Mostrar resumen de actualización.
825updateSummary
826
[a0867b37]827#rm -rf $WORKDIR
828echoAndLog "OpenGnSys update finished at $(date)"
829
830popd
831
Note: See TracBrowser for help on using the repository browser.