source: installer/opengnsys_update.sh @ 957d1a1

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 957d1a1 was dc762088, checked in by albertogp <albertogp@…>, 12 years ago

branches-version1.0
Corrigiendo error en los ficheros de instalación y actualización
en la línea de /etc/cron.d fichero deletepreimage 1369 y 629 respectivamente

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

  • Property mode set to 100755
File size: 28.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 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
457        echoAndLog "${FUNCNAME}(): Updating web files..."
458        backupFile $INSTALL_TARGET/www/controlacceso.php
459        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
460        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
461        ERRCODE=$?
462        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
463        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
464        if [ $ERRCODE != 0 ]; then
465                errorAndLog "${FUNCNAME}(): Error updating web files."
466                exit 1
467        fi
468        restoreFile $INSTALL_TARGET/www/controlacceso.php
469        # Cambiar permisos para ficheros especiales.
470        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
471        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
472        echoAndLog "${FUNCNAME}(): Web files updated successfully."
473}
474
475# Copiar carpeta de Interface
476function updateInterfaceAdm()
477{
478        local errcode=0
479         
480        # Crear carpeta y copiar Interface
481        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
482        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
483        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
484        errcoce=$?
485        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
486        if [ $errcode -ne 0 ]; then
487                echoAndLog "${FUNCNAME}(): error while updating admin interface"
488                exit 1
489        fi
490        chmod -R +x $INSTALL_TARGET/client/interfaceAdm
491        chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
492        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
493        echoAndLog "${FUNCNAME}(): Admin interface updated successfully."
494}
495
496# Crear documentación Doxygen para la consola web.
497function makeDoxygenFiles()
498{
499        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
500        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
501                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
502        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
503                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
504                return 1
505        fi
506        rm -fr "$INSTALL_TARGET/www/api"
507        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
508        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
509        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
510        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
511}
512
513
514# Crea la estructura base de la instalación de opengnsys
515function createDirs()
516{
517        # Crear estructura de directorios.
518        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
519        local dir
520
521        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
522        mkdir -p ${INSTALL_TARGET}/{client,images}
523        mkdir -p ${INSTALL_TARGET}/log/clients
524        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
525        # Detectar directorio de instalación de TFTP.
526        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
527                for dir in /var/lib/tftpboot /srv/tftp; do
528                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
529                done
530        fi
531        mkdir -p ${INSTALL_TARGET}/tftpboot/{pxelinux.cfg,menu.lst}
532        if [ $? -ne 0 ]; then
533                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
534                return 1
535        fi
536
537        # Crear usuario ficticio.
538        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
539                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
540        else
541                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
542                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
543                if [ $? -ne 0 ]; then
544                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
545                        return 1
546                fi
547        fi
548
549        # Establecer los permisos básicos.
550        echoAndLog "${FUNCNAME}(): setting directory permissions"
551        chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
552        mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples
553        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
554        chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
555        if [ $? -ne 0 ]; then
556                errorAndLog "${FUNCNAME}(): error while setting permissions"
557                return 1
558        fi
559
560        # Mover el fichero de registro al directorio de logs.
561        echoAndLog "${FUNCNAME}(): moving update log file"
562        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
563        chmod 600 $LOG_FILE
564
565        echoAndLog "${FUNCNAME}(): directory paths created"
566        return 0
567}
568
569# Copia ficheros de configuración y ejecutables genéricos del servidor.
570function updateServerFiles()
571{
572        # No copiar ficheros del antiguo cliente Initrd
573        local SOURCES=( repoman/bin \
574                        server/bin \
575                        admin/Sources/Services/ogAdmServerAux \
576                        admin/Sources/Services/ogAdmRepoAux \
577                        server/tftpboot \
578                        installer/opengnsys_uninstall.sh \
579                        installer/install_ticket_wolunicast.sh \
580                        doc )
581        local TARGETS=( bin \
582                        bin \
583                        sbin \
584                        sbin \
585                        tftpboot \
586                        lib/opengnsys_uninstall.sh \
587                        lib/install_ticket_wolunicast.sh \
588                        doc )
589
590        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
591                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
592                exit 1
593        fi
594
595        echoAndLog "${FUNCNAME}(): updating files in server directories"
596        pushd $WORKDIR/opengnsys >/dev/null
597        local i
598        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
599                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
600                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
601                else
602                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
603                fi
604        done
605        popd >/dev/null
606        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
607        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
608                echoAndLog "${FUNCNAME}(): updating DHCP files"
609                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
610                $DHCPSERV restart
611                NEWFILES="/etc/dhcp*/dhcpd*.conf"
612        fi
613        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
614                echoAndLog "${FUNCNAME}(): updating new init file"
615                backupFile /etc/init.d/opengnsys
616                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
617                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
618        fi
619        if grep -q "UrlMsg=.*msgbrowser.php" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
620                echoAndLog "${FUNCNAME}(): updating new client config file"
621                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
622                perl -pi -e 's!UrlMsg=.*msgbrowser\.php!UrlMsg=http://localhost/cgi-bin/httpd-log\.sh!g' $INSTALL_TARGET/client/etc/ogAdmClient.cfg
623                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
624        fi
625        echoAndLog "${FUNCNAME}(): updating cron files"
626        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
627        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
628        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
629        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
630        echoAndLog "${FUNCNAME}(): server files updated successfully."
631}
632
633####################################################################
634### Funciones de compilación de código fuente de servicios
635####################################################################
636
637# Recompilar y actualiza los serivicios y clientes.
638function compileServices()
639{
640        local hayErrores=0
641
642        # Compilar OpenGnSys Server
643        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Admin Server"
644        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
645        make && mv ogAdmServer $INSTALL_TARGET/sbin
646        if [ $? -ne 0 ]; then
647                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
648                hayErrores=1
649        fi
650        popd
651        # Compilar OpenGnSys Repository Manager
652        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Repository Manager"
653        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
654        make && mv ogAdmRepo $INSTALL_TARGET/sbin
655        if [ $? -ne 0 ]; then
656                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
657                hayErrores=1
658        fi
659        popd
660        # Compilar OpenGnSys Agent
661        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Agent"
662        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
663        make && mv ogAdmAgent $INSTALL_TARGET/sbin
664        if [ $? -ne 0 ]; then
665                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
666                hayErrores=1
667        fi
668        popd
669
670        # Compilar OpenGnSys Client
671        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Client"
672        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
673        make && mv ogAdmClient $INSTALL_TARGET/client/bin
674        if [ $? -ne 0 ]; then
675                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Client"
676                hayErrores=1
677        fi
678        popd
679
680        return $hayErrores
681}
682
683
684####################################################################
685### Funciones instalacion cliente OpenGnSys
686####################################################################
687
688# Actualizar cliente OpenGnSys
689function updateClient()
690{
691        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
692        #local FILENAME=ogLive-quantal-3.7.6-030706-generic-r3619.iso   # 1.0.5-rc2
693        local FILENAME=ogLive-raring-3.8.0-22-generic-r3836.iso         # 1.0.5-rc3
694        local SOURCEFILE=$DOWNLOADURL/$FILENAME
695        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
696        local SOURCELENGTH
697        local TARGETLENGTH
698        local TMPDIR=/tmp/${FILENAME%.iso}
699        local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img
700        local SAMBAPASS
701
702        # Comprobar si debe actualizarse el cliente.
703        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
704        TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}')
705        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
706        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
707                echoAndLog "${FUNCNAME}(): Loading Client"
708                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
709                if [ ! -s $TARGETFILE ]; then
710                        errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
711                        return 1
712                fi
713                # Obtener la clave actual de acceso a Samba para restaurarla.
714                if [ -f $OGINITRD ]; then
715                        SAMBAPASS=$(gzip -dc $OGINITRD | \
716                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
717                                    grep "^[    ]*OPTIONS=" | \
718                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
719                fi
720                # Montar la imagen ISO del ogclient, actualizar ficheros y desmontar.
721                echoAndLog "${FUNCNAME}(): Updatting ogclient files"
722                mkdir -p $TMPDIR
723                mount -o loop,ro $TARGETFILE $TMPDIR
724                rsync -irlt $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
725                umount $TMPDIR
726                rmdir $TMPDIR
727                # Recuperar la clave de acceso a Samba.
728                if [ -n "$SAMBAPASS" ]; then
729                        echoAndLog "${FUNCNAME}(): Restoring client access key"
730                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
731                                        $INSTALL_TARGET/bin/setsmbpass
732                fi
733                # Establecer los permisos.
734                find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
735                find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
736                chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/tftpboot/ogclient
737                chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/{menu.lst,pxelinux.cfg}
738               
739                # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache
740                cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot
741                cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot
742               
743                echoAndLog "${FUNCNAME}(): Client update successfully"
744        else
745                echoAndLog "${FUNCNAME}(): Client is already updated"
746        fi
747}
748
749# Resumen de actualización.
750function updateSummary()
751{
752        # Actualizar fichero de versión y revisión.
753        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
754        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
755
756        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
757        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
758
759        echo
760        echoAndLog "OpenGnSys Update Summary"
761        echo       "========================"
762        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
763        echoAndLog "Update log file:                  $LOG_FILE"
764        if [ -n "$NEWFILES" ]; then
765                echoAndLog "Check the new config files:       $(echo $NEWFILES)"
766        fi
767        echo
768}
769
770
771
772#####################################################################
773####### Proceso de actualización de OpenGnSys
774#####################################################################
775
776
777echoAndLog "OpenGnSys update begins at $(date)"
778
779pushd $WORKDIR
780
781# Comprobar si hay conexión y detectar parámetros de red por defecto.
782checkNetworkConnection
783if [ $? -ne 0 ]; then
784        errorAndLog "Error connecting to server. Causes:"
785        errorAndLog " - Network is unreachable, review devices parameters."
786        errorAndLog " - You are inside a private network, configure the proxy service."
787        errorAndLog " - Server is temporally down, try agian later."
788        exit 1
789fi
790getNetworkSettings
791
792# Comprobar auto-actualización del programa.
793if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
794        checkAutoUpdate
795        if [ $? -ne 0 ]; then
796                echoAndLog "OpenGnSys updater has been overwritten."
797                echoAndLog "Please, re-execute this script."
798                exit
799        fi
800fi
801
802# Detectar datos de auto-configuración del instalador.
803autoConfigure
804
805# Instalar dependencias.
806installDependencies $DEPENDENCIES
807if [ $? -ne 0 ]; then
808        errorAndLog "Error: you may install all needed dependencies."
809        exit 1
810fi
811
812# Arbol de directorios de OpenGnSys.
813createDirs ${INSTALL_TARGET}
814if [ $? -ne 0 ]; then
815        errorAndLog "Error while creating directory paths!"
816        exit 1
817fi
818
819# Si es necesario, descarga el repositorio de código en directorio temporal
820if [ $USESVN -eq 1 ]; then
821        svnExportCode $SVN_URL
822        if [ $? -ne 0 ]; then
823                errorAndLog "Error while getting code from svn"
824                exit 1
825        fi
826else
827        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
828fi
829
830# Si existe fichero de actualización de la base de datos; aplicar cambios.
831INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
832REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
833if [ "$INSTVERSION" == "$REPOVERSION" ]; then
834        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION.sql"
835else
836        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
837fi
838if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
839        echoAndLog "Updating tables from file: $(basename $OPENGNSYS_DBUPDATEFILE)"
840        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
841else
842        echoAndLog "Database unchanged."
843fi
844
845# Actualizar ficheros complementarios del servidor
846updateServerFiles
847if [ $? -ne 0 ]; then
848        errorAndLog "Error updating OpenGnSys Server files"
849        exit 1
850fi
851
852# Configurar Rsync.
853rsyncConfigure
854
855# Actualizar ficheros del cliente
856updateClientFiles
857updateInterfaceAdm
858
859# Actualizar páqinas web
860apacheConfiguration
861updateWebFiles
862if [ $? -ne 0 ]; then
863        errorAndLog "Error updating OpenGnSys Web Admin files"
864        exit 1
865fi
866# Generar páginas Doxygen para instalar en el web
867makeDoxygenFiles
868
869# Recompilar y actualizar los servicios del sistema
870compileServices
871
872# Actaulizar ficheros auxiliares del cliente
873updateClient
874if [ $? -ne 0 ]; then
875        errorAndLog "Error updating clients"
876        exit 1
877fi
878
879# Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
880if [ -f /tmp/dstate ]; then
881        rm -f /tmp/dstate
882fi
883
884# Mostrar resumen de actualización.
885updateSummary
886
887#rm -rf $WORKDIR
888echoAndLog "OpenGnSys update finished at $(date)"
889
890popd
891
Note: See TracBrowser for help on using the repository browser.