source: installer/opengnsys_update.sh @ 17640b6

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 17640b6 was 1893b9d, checked in by ramon <ramongomez@…>, 9 years ago

#729: Usar script installoglive en los procesos de instalación y actualización.

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

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