source: installer/opengnsys_update.sh @ 9dba4c18

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 9dba4c18 was 42a0e41, checked in by ramon <ramongomez@…>, 12 years ago

#493: Instalador y actualizador copian servicio auxiliar ogAdmServerAux; separar los logs de ambos scripts.

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

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