source: installer/opengnsys_update.sh @ aed65e0

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 aed65e0 was ab7f563, checked in by ramon <ramongomez@…>, 11 years ago

#616: Solucionar problema a la hora de activar el metaservicio xinetd, usado para iniciar Rsync.

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