source: installer/opengnsys_update.sh @ c6130f4

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

#648: Actualizador ejecuta al final el script checkperms para asignar correctamente permisos y deja de copiar ficheros que ya no existen.

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

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