source: installer/opengnsys_update.sh @ 251c9e4

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 251c9e4 was 993c328, checked in by ramon <ramongomez@…>, 11 years ago

#616: Actualizar usando ogLive 1.0.4.

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

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