source: installer/opengnsys_update.sh @ ea7314e

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 ea7314e was a43e90d, checked in by ramon <ramongomez@…>, 10 years ago

#659: Instalador y actualizador comprueban si tienen que renombrar Rsync para evitar la incompativilidad de versiones entre servidor y cliente.

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

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