source: installer/opengnsys_update.sh @ 0703783

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 0703783 was 0efb835, checked in by albertogp <albertogp@…>, 11 years ago

Corrección de errores

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

  • Property mode set to 100755
File size: 31.1 KB
Line 
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
9#@version 1.0 - adaptación a OpenGnSys 1.0
10#@author  Ramón Gómez - ETSII Univ. Sevilla
11#@date    2011/03/02
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
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
18#@version 1.0.3 - Compatibilidad con Debian y auto configuración de acceso a BD.
19#@author  Ramón Gómez - ETSII Univ. Sevilla
20#@date    2012/03/12
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
24#@version 1.0.5 - Actualizar BD en la misma versión, compatibilidad con Fedora (systemd) y configuración de Rsync.
25#@author  Ramón Gómez - ETSII Univ. Sevilla
26#@date    2014/04/03
27#*/
28
29
30####  AVISO: NO EDITAR variables de configuración.
31####  WARNING: DO NOT EDIT configuration variables.
32INSTALL_TARGET=/opt/opengnsys           # Directorio de instalación
33OPENGNSYS_CLIENTUSER="opengnsys"        # Usuario Samba
34
35
36# Sólo ejecutable por usuario root
37if [ "$(whoami)" != 'root' ]; then
38        echo "ERROR: this program must run under root privileges!!"
39        exit 1
40fi
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
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 de 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
59
60# Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1).
61PROGRAMDIR=$(readlink -e $(dirname "$0"))
62PROGRAMNAME=$(basename "$0")
63OPENGNSYS_SERVER="www.opengnsys.es"
64if [ -d "$PROGRAMDIR/../installer" ]; then
65        USESVN=0
66else
67        USESVN=1
68fi
69SVN_URL="http://$OPENGNSYS_SERVER/svn/branches/version1.0/"
70
71WORKDIR=/tmp/opengnsys_update
72mkdir -p $WORKDIR
73
74# Registro de incidencias.
75OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
76LOG_FILE=/tmp/$(basename $OGLOGFILE)
77
78
79
80#####################################################################
81####### Algunas funciones útiles de propósito general:
82#####################################################################
83
84# Generar variables de configuración del actualizador
85# Variables globales:
86# - OSDISTRIB - distribución Linux
87# - DEPENDENCIES - array de dependencias que deben estar instaladas
88# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKG - comandos para gestión de paquetes
89# - APACHECFGDIR, APACHESERV, DHCPSERV, INETDCFGDIR - configuración y servicios
90function autoConfigure()
91{
92local i
93
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)
100                DEPENDENCIES=( php5-ldap xinetd rsync btrfs-tools procps)
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\""
104                if which service &>/dev/null; then
105                        STARTSERVICE="eval service \$service restart"
106                        STOPSERVICE="eval service \$service stop"
107                else
108                        STARTSERVICE="eval /etc/init.d/\$service restart"
109                        STOPSERVICE="eval /etc/init.d/\$service stop"
110                fi
111                ENABLESERVICE="eval update-rc.d \$service defaults"
112                APACHEUSER="www-data"
113                APACHEGROUP="www-data"
114                INETDCFGDIR=/etc/xinetd.d
115                ;;
116        Fedora|CentOS)
117                DEPENDENCIES=( php-ldap xinetd rsync btrfs-progs procps-ng )
118                INSTALLPKGS="yum install -y"
119                CHECKPKG="rpm -q --quiet \$package"
120                if which systemctl &>/dev/null; then
121                        STARTSERVICE="eval systemctl start \$service.service"
122                        STOPSERVICE="eval systemctl stop \$service.service"
123                        ENABLESERVICE="eval systemctl enable \$service.service"
124                else
125                        STARTSERVICE="eval service \$service start"
126                        STOPSERVICE="eval service \$service stop"
127                        ENABLESERVICE="eval chkconfig \$service on"
128                fi
129                APACHEUSER="apache"
130                APACHEGROUP="apache"
131                INETDCFGDIR=/etc/xinetd.d
132                ;;
133        *)      # Otras distribuciones.
134                ;;
135esac
136for i in apache2 httpd; do
137        [ -f /etc/$i ] && APACHECFGDIR="/etc/$i"
138        [ -f /etc/init.d/$i ] && APACHESERV="/etc/init.d/$i"
139done
140for i in dhcpd dhcpd3-server isc-dhcp-server; do
141        [ -f /etc/init.d/$i ] && DHCPSERV="/etc/init.d/$i"
142done
143}
144
145
146# Comprobar auto-actualización.
147function checkAutoUpdate()
148{
149        local update=0
150
151        # Actaulizar el script si ha cambiado o no existe el original.
152        if [ $USESVN -eq 1 ]; then
153                svn export $SVN_URL/installer/$PROGRAMNAME
154                if ! diff -q $PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
155                        mv $PROGRAMNAME $INSTALL_TARGET/lib
156                        update=1
157                else
158                        rm -f $PROGRAMNAME
159                fi
160        else
161                if ! diff -q $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
162                        cp -a $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib
163                        update=1
164                fi
165        fi
166
167        return $update
168}
169
170
171function getDateTime()
172{
173        date "+%Y%m%d-%H%M%S"
174}
175
176# Escribe a fichero y muestra por pantalla
177function echoAndLog()
178{
179        echo $1
180        DATETIME=`getDateTime`
181        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
182}
183
184function errorAndLog()
185{
186        echo "ERROR: $1"
187        DATETIME=`getDateTime`
188        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
189}
190
191
192#####################################################################
193####### Funciones de copia de seguridad y restauración de ficheros
194#####################################################################
195
196# Hace un backup del fichero pasado por parámetro
197# deja un -last y uno para el día
198function backupFile()
199{
200        if [ $# -ne 1 ]; then
201                errorAndLog "${FUNCNAME}(): invalid number of parameters"
202                exit 1
203        fi
204
205        local fichero=$1
206        local fecha=`date +%Y%m%d`
207
208        if [ ! -f $fichero ]; then
209                errorAndLog "${FUNCNAME}(): file $fichero doesn't exists"
210                return 1
211        fi
212
213        echoAndLog "${FUNCNAME}(): Making $fichero back-up"
214
215        # realiza una copia de la última configuración como last
216        cp -a $fichero "${fichero}-LAST"
217
218        # si para el día no hay backup lo hace, sino no
219        if [ ! -f "${fichero}-${fecha}" ]; then
220                cp -a $fichero "${fichero}-${fecha}"
221        fi
222}
223
224# Restaura un fichero desde su copia de seguridad
225function restoreFile()
226{
227        if [ $# -ne 1 ]; then
228                errorAndLog "${FUNCNAME}(): invalid number of parameters"
229                exit 1
230        fi
231
232        local fichero=$1
233
234        echoAndLog "${FUNCNAME}(): restoring file $fichero"
235        if [ -f "${fichero}-LAST" ]; then
236                cp -a "$fichero-LAST" "$fichero"
237        fi
238}
239
240
241#####################################################################
242####### Funciones de acceso a base de datos
243#####################################################################
244
245# Actualizar la base datos
246function importSqlFile()
247{
248        if [ $# -ne 4 ]; then
249                errorAndLog "${FNCNAME}(): invalid number of parameters"
250                exit 1
251        fi
252
253        local dbuser="$1"
254        local dbpassword="$2"
255        local database="$3"
256        local sqlfile="$4"
257        local tmpfile=$(mktemp)
258        local mycnf=/tmp/.my.cnf.$$
259        local status
260
261        if [ ! -r $sqlfile ]; then
262                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
263                return 1
264        fi
265
266        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
267        chmod 600 $tmpfile
268        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
269            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile
270        # Componer fichero con credenciales de conexión. 
271        touch $mycnf
272        chmod 600 $mycnf
273        cat << EOT > $mycnf
274[client]
275user=$dbuser
276password=$dbpassword
277EOT
278        # Ejecutar actualización y borrar fichero de credenciales.
279        mysql --defaults-extra-file=$mycnf --default-character-set=utf8 -D "$database" < $tmpfile
280        status=$?
281        rm -f $mycnf $tmpfile
282        if [ $status -ne 0 ]; then
283                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
284                return 1
285        fi
286        echoAndLog "${FUNCNAME}(): file imported to database $database"
287        return 0
288}
289
290
291#####################################################################
292####### Funciones de instalación de paquetes
293#####################################################################
294
295# Instalar las deependencias necesarias para el actualizador.
296function installDependencies()
297{
298        local package
299
300        if [ $# = 0 ]; then
301                echoAndLog "${FUNCNAME}(): no deps needed."
302        else
303                while [ $# -gt 0 ]; do
304                        package="$1"
305                        eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $1"
306                        shift
307                done
308                if [ -n "$INSTALLDEPS" ]; then
309                        $UPDATEPKGLIST
310                        $INSTALLPKGS $INSTALLDEPS
311                        if [ $? -ne 0 ]; then
312                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS."
313                                return 1
314                        fi
315                fi
316        fi
317}
318
319
320#####################################################################
321####### Funciones para el manejo de Subversion
322#####################################################################
323
324function svnExportCode()
325{
326        if [ $# -ne 1 ]; then
327                errorAndLog "${FUNCNAME}(): invalid number of parameters"
328                exit 1
329        fi
330
331        local url="$1"
332
333        echoAndLog "${FUNCNAME}(): downloading subversion code..."
334
335        svn checkout "${url}" opengnsys
336        if [ $? -ne 0 ]; then
337                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
338                return 1
339        fi
340        echoAndLog "${FUNCNAME}(): subversion code downloaded"
341        return 0
342}
343
344
345############################################################
346###  Detectar red
347############################################################
348
349# Comprobar si existe conexión.
350function checkNetworkConnection()
351{
352        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
353        wget --spider -q $OPENGNSYS_SERVER
354}
355
356# Obtener los parámetros de red del servidor.
357function getNetworkSettings()
358{
359        # Variables globales definidas:
360        # - SERVERIP:   IP local de la interfaz por defecto.
361
362        local DEVICES
363        local dev
364
365        echoAndLog "${FUNCNAME}(): Detecting network parameters."
366        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
367        for dev in $DEVICES; do
368                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
369        done
370}
371
372
373#####################################################################
374####### Funciones específicas de la instalación de Opengnsys
375#####################################################################
376
377# Actualizar cliente OpenGnSys
378function updateClientFiles()
379{
380        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Client files."
381        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
382        if [ $? -ne 0 ]; then
383                errorAndLog "${FUNCNAME}(): error while updating client structure"
384                exit 1
385        fi
386        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
387       
388        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Cloning Engine files."
389        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
390        if [ $? -ne 0 ]; then
391                errorAndLog "${FUNCNAME}(): error while updating engine files"
392                exit 1
393        fi
394       
395        echoAndLog "${FUNCNAME}(): client files update success."
396}
397
398# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
399function apacheConfiguration ()
400{
401        # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2).
402        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
403                echoAndLog "${FUNCNAME}(): Configuring HTTPS access..."
404                mv $APACHECFGDIR/sites-available/opengnsys.conf $APACHECFGDIR/sites-available/opengnsys
405                a2ensite default-ssl
406                a2enmod ssl
407                a2dissite opengnsys.conf
408                a2ensite opengnsys
409                $APACHESERV restart
410        fi
411
412        # Variables de ejecución de Apache.
413        # - APACHE_RUN_USER
414        # - APACHE_RUN_GROUP
415        if [ -f $APACHECFGDIR/envvars ]; then
416                source $APACHECFGDIR/envvars
417        fi
418        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
419        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
420}
421
422# Configurar servicio Rsync.
423function rsyncConfigure()
424{
425        local service
426
427        # Configurar acceso a Rsync.
428        if [ ! -f /etc/rsyncd.conf ]; then
429                echoAndLog "${FUNCNAME}(): Configuring Rsync service."
430                NEWFILES="$NEWFILES /etc/rsyncd.conf"
431                sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \
432                    $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf
433                # Habilitar Rsync.
434                if [ -f /etc/default/rsync ]; then
435                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
436                fi
437                if [ -f $INETDCFGDIR/rsync ]; then
438                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
439                else
440                        cat << EOT > $INETDCFGDIR/rsync
441service rsync
442{
443        disable = no
444        socket_type = stream
445        wait = no
446        user = root
447        server = $(which rsync)
448        server_args = --daemon
449        log_on_failure += USERID
450        flags = IPv6
451}
452EOT
453                fi
454                # Activar e iniciar Rsync.
455                service="rsync"  $ENABLESERVICE
456                service="xinetd"
457                $ENABLESERVICE; $STARTSERVICE
458        fi
459}
460
461# Copiar ficheros del OpenGnSys Web Console.
462function updateWebFiles()
463{
464        local ERRCODE COMPATDIR f
465
466        echoAndLog "${FUNCNAME}(): Updating web files..."
467
468        # Copiar los ficheros nuevos conservando el archivo de configuración de acceso.
469        backupFile $INSTALL_TARGET/www/controlacceso.php
470        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
471        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
472        ERRCODE=$?
473        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
474        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
475        if [ $ERRCODE != 0 ]; then
476                errorAndLog "${FUNCNAME}(): Error updating web files."
477                exit 1
478        fi
479        restoreFile $INSTALL_TARGET/www/controlacceso.php
480
481        # Compatibilidad con dispositivos móviles.
482        COMPATDIR="$INSTALL_TARGET/www/principal"
483        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
484                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
485        done
486        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
487
488        # Cambiar permisos para ficheros especiales.
489        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
490        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
491
492        echoAndLog "${FUNCNAME}(): Web files updated successfully."
493}
494
495# Copiar carpeta de Interface
496function updateInterfaceAdm()
497{
498        local errcode=0
499
500        # Crear carpeta y copiar Interface
501        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
502        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
503        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
504        errcoce=$?
505        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
506        if [ $errcode -ne 0 ]; then
507                echoAndLog "${FUNCNAME}(): error while updating admin interface"
508                exit 1
509        fi
510        chmod -R +x $INSTALL_TARGET/client/interfaceAdm
511        chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
512        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
513        echoAndLog "${FUNCNAME}(): Admin interface updated successfully."
514}
515
516# Crear documentación Doxygen para la consola web.
517function makeDoxygenFiles()
518{
519        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
520        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
521                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
522        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
523                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
524                return 1
525        fi
526        rm -fr "$INSTALL_TARGET/www/api"
527        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
528        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
529        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
530        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
531}
532
533
534# Crea la estructura base de la instalación de opengnsys
535function createDirs()
536{
537        # Crear estructura de directorios.
538        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
539        local dir
540
541        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
542        mkdir -p ${INSTALL_TARGET}/{client,images}
543        mkdir -p ${INSTALL_TARGET}/log/clients
544        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
545        # Detectar directorio de instalación de TFTP.
546        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
547                for dir in /var/lib/tftpboot /srv/tftp; do
548                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
549                done
550        fi
551        mkdir -p ${INSTALL_TARGET}/tftpboot/{pxelinux.cfg,menu.lst}
552        if [ $? -ne 0 ]; then
553                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
554                return 1
555        fi
556
557        # Crear usuario ficticio.
558        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
559                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
560        else
561                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
562                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
563                if [ $? -ne 0 ]; then
564                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
565                        return 1
566                fi
567        fi
568
569        # Establecer los permisos básicos.
570        echoAndLog "${FUNCNAME}(): setting directory permissions"
571        chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
572        mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples
573        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
574        chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
575        if [ $? -ne 0 ]; then
576                errorAndLog "${FUNCNAME}(): error while setting permissions"
577                return 1
578        fi
579
580        # Mover el fichero de registro al directorio de logs.
581        echoAndLog "${FUNCNAME}(): moving update log file"
582        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
583        chmod 600 $LOG_FILE
584
585        echoAndLog "${FUNCNAME}(): directory paths created"
586        return 0
587}
588
589# Copia ficheros de configuración y ejecutables genéricos del servidor.
590function updateServerFiles()
591{
592        # No copiar ficheros del antiguo cliente Initrd
593        local SOURCES=( repoman/bin \
594                        server/bin \
595                        admin/Sources/Services/ogAdmServerAux \
596                        admin/Sources/Services/ogAdmRepoAux \
597                        server/tftpboot \
598                        installer/opengnsys_uninstall.sh \
599                        installer/install_ticket_wolunicast.sh \
600                        doc )
601        local TARGETS=( bin \
602                        bin \
603                        sbin/ogAdmServerAux \
604                        sbin/ogAdmRepoAux \
605                        tftpboot \
606                        lib/opengnsys_uninstall.sh \
607                        lib/install_ticket_wolunicast.sh \
608                        doc )
609
610        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
611                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
612                exit 1
613        fi
614
615        echoAndLog "${FUNCNAME}(): updating files in server directories"
616        pushd $WORKDIR/opengnsys >/dev/null
617        local i
618        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
619                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
620                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
621                else
622                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
623                fi
624        done
625        popd >/dev/null
626        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
627        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
628                echoAndLog "${FUNCNAME}(): updating DHCP files"
629                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
630                $DHCPSERV restart
631                NEWFILES="/etc/dhcp*/dhcpd*.conf"
632        fi
633        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
634                echoAndLog "${FUNCNAME}(): updating new init file"
635                backupFile /etc/init.d/opengnsys
636                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
637                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
638        fi
639        if grep -q "UrlMsg=.*msgbrowser.php" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
640                echoAndLog "${FUNCNAME}(): updating new client config file"
641                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
642                perl -pi -e 's!UrlMsg=.*msgbrowser\.php!UrlMsg=http://localhost/cgi-bin/httpd-log\.sh!g' $INSTALL_TARGET/client/etc/ogAdmClient.cfg
643                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
644        fi
645        echoAndLog "${FUNCNAME}(): updating cron files"
646        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
647        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
648        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
649        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
650        echoAndLog "${FUNCNAME}(): server files updated successfully."
651}
652
653####################################################################
654### Funciones de compilación de código fuente de servicios
655####################################################################
656
657# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
658function moveNewService()
659{
660        local service
661
662        # Recibe 2 parámetros: fichero origen y directorio destino.
663        [ $# == 2 ] || return 1
664        [ -f  $1 -a -d $2 ] || return 1
665
666        # Comparar los ficheros.
667        if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
668                # Parar los servicios si fuese necesario.
669                [ -z "$NEWSERVICES" ] && service="opengnsys" $STOPSERVICE
670                # Nuevo servicio.
671                NEWSERVICES="$NEWSERVICES $(basename $1)"
672                # Mover el nuevo fichero de servicio
673                mv $1 $2
674        fi
675}
676
677
678# Recompilar y actualiza los serivicios y clientes.
679function compileServices()
680{
681        local hayErrores=0
682
683        # Compilar OpenGnSys Server
684        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Admin Server"
685        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
686        make && moveNewService ogAdmServer $INSTALL_TARGET/sbin
687        if [ $? -ne 0 ]; then
688                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
689                hayErrores=1
690        fi
691        popd
692        # Compilar OpenGnSys Repository Manager
693        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Repository Manager"
694        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
695        make && moveNewService ogAdmRepo $INSTALL_TARGET/sbin
696        if [ $? -ne 0 ]; then
697                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
698                hayErrores=1
699        fi
700        popd
701        # Compilar OpenGnSys Agent
702        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Agent"
703        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
704        make && moveNewService ogAdmAgent $INSTALL_TARGET/sbin
705        if [ $? -ne 0 ]; then
706                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
707                hayErrores=1
708        fi
709        popd
710
711        # Compilar OpenGnSys Client
712        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Client"
713        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
714        make && mv ogAdmClient $INSTALL_TARGET/client/bin
715        if [ $? -ne 0 ]; then
716                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Client"
717                hayErrores=1
718        fi
719        popd
720
721        return $hayErrores
722}
723
724
725####################################################################
726### Funciones instalacion cliente OpenGnSys
727####################################################################
728
729# Actualizar cliente OpenGnSys
730function updateClient()
731{
732        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
733        local FILENAME=ogLive-precise-3.2.0-23-generic-r3257.iso        # 1.0.4-rc2
734        #local FILENAME=ogLive-raring-3.8.0-22-generic-r3836.iso        # 1.0.5-rc3
735        local SOURCEFILE=$DOWNLOADURL/$FILENAME
736        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
737        local SOURCELENGTH
738        local TARGETLENGTH
739        local TMPDIR=/tmp/${FILENAME%.iso}
740        local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img
741        local OGVMLINUZ=$INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz
742        local SAMBAPASS
743        local KERNELVERSION
744
745        # Comprobar si debe actualizarse el cliente.
746        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
747        TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}')
748        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
749        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
750                echoAndLog "${FUNCNAME}(): Loading Client"
751                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
752                if [ ! -s $TARGETFILE ]; then
753                        errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
754                        return 1
755                fi
756                # Obtener la clave actual de acceso a Samba para restaurarla.
757                if [ -f $OGINITRD ]; then
758                        SAMBAPASS=$(gzip -dc $OGINITRD | \
759                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
760                                    grep "^[    ].*OPTIONS=" | \
761                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
762                fi
763                # Montar la imagen ISO del ogclient, actualizar ficheros y desmontar.
764                echoAndLog "${FUNCNAME}(): Updatting ogclient files"
765                mkdir -p $TMPDIR
766                mount -o loop,ro $TARGETFILE $TMPDIR
767                rsync -irlt $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
768                umount $TMPDIR
769                rmdir $TMPDIR
770                # Recuperar la clave de acceso a Samba.
771                if [ -n "$SAMBAPASS" ]; then
772                        echoAndLog "${FUNCNAME}(): Restoring client access key"
773                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
774                                        $INSTALL_TARGET/bin/setsmbpass
775                fi
776                # Establecer los permisos.
777                find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
778                find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
779                chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/tftpboot/ogclient
780                chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/{menu.lst,pxelinux.cfg}
781               
782                # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache
783                cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot
784                cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot
785               
786                # Obtiene versión del Kernel del cliente (con 2 decimales).
787                KERNELVERSION=$(file -bkr $OGVMLINUZ 2>/dev/null | \
788                                awk '/Linux/ { for (i=1; i<=NF; i++)
789                                                   if ($i~/version/) {
790                                                      v=$(i+1);
791                                                      printf ("%d",v);
792                                                      sub (/[0-9]*\./,"",v);
793                                                      printf (".%02d",v)
794                                             } }')
795                # Actaulizar la base de datos adaptada al Kernel del cliente.
796                OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-postinst.sql"
797                if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
798                        perl -pi -e "s/KERNELVERSION/$KERNELVERSION/g" $OPENGNSYS_DBUPDATEFILE
799                        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
800                fi
801
802                echoAndLog "${FUNCNAME}(): Client update successfully"
803        else
804                # Si no existe, crear el fichero de claves de Rsync.
805                if [ ! -f /etc/rsyncd.secrets ]; then
806                        echoAndLog "${FUNCNAME}(): Restoring client access key"
807                        SAMBAPASS=$(gzip -dc $OGINITRD | \
808                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
809                                    grep "^[    ].*OPTIONS=" | \
810                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
811                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
812                                        $INSTALL_TARGET/bin/setsmbpass
813                else
814                        echoAndLog "${FUNCNAME}(): Client is already updated"
815                fi
816        fi
817}
818
819# Resumen de actualización.
820function updateSummary()
821{
822        # Actualizar fichero de versión y revisión.
823        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
824        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
825
826        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
827        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
828
829        echo
830        echoAndLog "OpenGnSys Update Summary"
831        echo       "========================"
832        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
833        echoAndLog "Update log file:                  $LOG_FILE"
834        if [ -n "$NEWFILES" ]; then
835                echoAndLog "Check the new config files:       $(echo $NEWFILES)"
836        fi
837        if [ -n "$NEWSERVICES" ]; then
838                echoAndLog "New compiled services:            $(echo $NEWSERVICES)"
839                # Indicar si se debe reiniciar servicios manualmente o usando el Cron.
840                [ -f /etc/default/opengnsys ] && source /etc/default/opengnsys
841                if [ "$RUN_CRONJOB" == "no" ]; then
842                        echoAndLog "        WARNING: you must restart OpenGnSys services manually."
843                else
844                        echoAndLog "        New OpenGnSys services will be restarted by the cronjob."
845                fi
846        fi
847        echo
848}
849
850
851
852#####################################################################
853####### Proceso de actualización de OpenGnSys
854#####################################################################
855
856
857echoAndLog "OpenGnSys update begins at $(date)"
858
859pushd $WORKDIR
860
861# Comprobar si hay conexión y detectar parámetros de red por defecto.
862checkNetworkConnection
863if [ $? -ne 0 ]; then
864        errorAndLog "Error connecting to server. Causes:"
865        errorAndLog " - Network is unreachable, review devices parameters."
866        errorAndLog " - You are inside a private network, configure the proxy service."
867        errorAndLog " - Server is temporally down, try agian later."
868        exit 1
869fi
870getNetworkSettings
871
872# Comprobar auto-actualización del programa.
873if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
874        checkAutoUpdate
875        if [ $? -ne 0 ]; then
876                echoAndLog "OpenGnSys updater has been overwritten."
877                echoAndLog "Please, re-execute this script."
878                exit
879        fi
880fi
881
882# Detectar datos de auto-configuración del instalador.
883autoConfigure
884
885# Instalar dependencias.
886installDependencies ${DEPENDENCIES[*]}
887if [ $? -ne 0 ]; then
888        errorAndLog "Error: you may install all needed dependencies."
889        exit 1
890fi
891
892# Arbol de directorios de OpenGnSys.
893createDirs ${INSTALL_TARGET}
894if [ $? -ne 0 ]; then
895        errorAndLog "Error while creating directory paths!"
896        exit 1
897fi
898
899# Si es necesario, descarga el repositorio de código en directorio temporal
900if [ $USESVN -eq 1 ]; then
901        svnExportCode $SVN_URL
902        if [ $? -ne 0 ]; then
903                errorAndLog "Error while getting code from svn"
904                exit 1
905        fi
906else
907        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
908fi
909
910# Si existe fichero de actualización de la base de datos; aplicar cambios.
911INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
912REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
913if [ "$INSTVERSION" == "$REPOVERSION" ]; then
914        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION.sql"
915else
916        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
917fi
918if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
919        echoAndLog "Updating tables from file: $(basename $OPENGNSYS_DBUPDATEFILE)"
920        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
921else
922        echoAndLog "Database unchanged."
923fi
924
925# Actualizar ficheros complementarios del servidor
926updateServerFiles
927if [ $? -ne 0 ]; then
928        errorAndLog "Error updating OpenGnSys Server files"
929        exit 1
930fi
931
932# Configurar Rsync.
933rsyncConfigure
934
935# Actualizar ficheros del cliente
936updateClientFiles
937updateInterfaceAdm
938
939# Actualizar páqinas web
940apacheConfiguration
941updateWebFiles
942if [ $? -ne 0 ]; then
943        errorAndLog "Error updating OpenGnSys Web Admin files"
944        exit 1
945fi
946# Generar páginas Doxygen para instalar en el web
947makeDoxygenFiles
948
949# Recompilar y actualizar los servicios del sistema
950compileServices
951
952# Actaulizar ficheros auxiliares del cliente
953updateClient
954if [ $? -ne 0 ]; then
955        errorAndLog "Error updating clients"
956        exit 1
957fi
958
959# Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
960if [ -f /tmp/dstate ]; then
961        rm -f /tmp/dstate
962fi
963
964# Mostrar resumen de actualización.
965updateSummary
966
967#rm -rf $WORKDIR
968echoAndLog "OpenGnSys update finished at $(date)"
969
970popd
971
Note: See TracBrowser for help on using the repository browser.