source: installer/opengnsys_update.sh @ c680f93

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 c680f93 was b1735a7, checked in by ramon <ramongomez@…>, 9 years ago

#718 #730: Incluir rutas REST que atienden las peticiones push del nuevo OGAgent y actualización de la ubicación del fichero para registrarlas.

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

  • Property mode set to 100755
File size: 33.0 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 realpath php5-curl )
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        local APIKEY=$(php -r 'echo md5(uniqid(rand(), true));')
286
287        if [ ! -r $sqlfile ]; then
288                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
289                return 1
290        fi
291
292        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
293        chmod 600 $tmpfile
294        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
295            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
296            -e "s/APIKEY/$APIKEY/g" $sqlfile > $tmpfile
297        # Componer fichero con credenciales de conexión. 
298        touch $mycnf
299        chmod 600 $mycnf
300        cat << EOT > $mycnf
301[client]
302user=$dbuser
303password=$dbpassword
304EOT
305        # Ejecutar actualización y borrar fichero de credenciales.
306        mysql --defaults-extra-file=$mycnf --default-character-set=utf8 -D "$database" < $tmpfile
307        status=$?
308        rm -f $mycnf $tmpfile
309        if [ $status -ne 0 ]; then
310                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
311                return 1
312        fi
313        echoAndLog "${FUNCNAME}(): file imported to database $database"
314        return 0
315}
316
317
318#####################################################################
319####### Funciones de instalación de paquetes
320#####################################################################
321
322# Instalar las deependencias necesarias para el actualizador.
323function installDependencies()
324{
325        local package
326
327        if [ $# = 0 ]; then
328                echoAndLog "${FUNCNAME}(): no deps needed."
329        else
330                while [ $# -gt 0 ]; do
331                        package="$1"
332                        eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $1"
333                        shift
334                done
335                if [ -n "$INSTALLDEPS" ]; then
336                        $UPDATEPKGLIST
337                        $INSTALLPKGS $INSTALLDEPS
338                        if [ $? -ne 0 ]; then
339                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS."
340                                return 1
341                        fi
342                fi
343        fi
344}
345
346
347#####################################################################
348####### Funciones para el manejo de Subversion
349#####################################################################
350
351function svnExportCode()
352{
353        if [ $# -ne 1 ]; then
354                errorAndLog "${FUNCNAME}(): invalid number of parameters"
355                exit 1
356        fi
357
358        local url="$1"
359
360        echoAndLog "${FUNCNAME}(): downloading subversion code..."
361
362        svn checkout "${url}" opengnsys
363        if [ $? -ne 0 ]; then
364                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
365                return 1
366        fi
367        echoAndLog "${FUNCNAME}(): subversion code downloaded"
368        return 0
369}
370
371
372############################################################
373###  Detectar red
374############################################################
375
376# Comprobar si existe conexión.
377function checkNetworkConnection()
378{
379        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
380        wget --spider -q $OPENGNSYS_SERVER
381}
382
383# Obtener los parámetros de red del servidor.
384function getNetworkSettings()
385{
386        # Variables globales definidas:
387        # - SERVERIP:   IP local de la interfaz por defecto.
388
389        local DEVICES
390        local dev
391
392        echoAndLog "${FUNCNAME}(): Detecting network parameters."
393        SERVERIP="$ServidorAdm"
394        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
395        for dev in $DEVICES; do
396                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
397        done
398}
399
400
401#####################################################################
402####### Funciones específicas de la instalación de Opengnsys
403#####################################################################
404
405# Actualizar cliente OpenGnsys.
406function updateClientFiles()
407{
408        # Actualizar ficheros del cliente.
409        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Client files."
410        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
411        if [ $? -ne 0 ]; then
412                errorAndLog "${FUNCNAME}(): error while updating client structure"
413                exit 1
414        fi
415        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
416
417        # Actualizar librerías del motor de clonación.
418        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Cloning Engine files."
419        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
420        if [ $? -ne 0 ]; then
421                errorAndLog "${FUNCNAME}(): error while updating engine files"
422                exit 1
423        fi
424        # Actualizar fichero de configuración del motor de clonación.
425        if ! grep -q "^TZ" $INSTALL_TARGET/client/etc/engine.cfg; then
426                TZ=$(timedatectl status | awk -F"[:()]" '/Time.*zone/ {print $2}')
427                cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
428# OpenGnsys Server timezone.
429TZ="${TZ// /}"
430EOT
431        fi
432
433        echoAndLog "${FUNCNAME}(): client files update success."
434}
435
436# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
437function apacheConfiguration ()
438{
439        # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2) y
440        #    activar módulo Rewrite (solo actualizaciones desde 1.0.x a 1.1.x).
441        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
442                echoAndLog "${FUNCNAME}(): Configuring Apache modules."
443                mv $APACHECFGDIR/sites-available/opengnsys.conf $APACHECFGDIR/sites-available/opengnsys
444                a2ensite default-ssl
445                a2enmod ssl
446                a2enmod rewrite
447                a2dissite opengnsys.conf
448                a2ensite opengnsys
449        elif [ -e $APACHECFGDIR/conf.modules.d ]; then
450                echoAndLog "${FUNCNAME}(): Configuring Apache modules."
451                sed -i '/rewrite/s/^#//' $APACHECFGDIR/*.conf
452        fi
453
454        # Actualizar configuración para acceso a API REST
455        #    (solo actualizaciones de 1.0.x a 1.1.x).
456        for config in $APACHECFGDIR/{,sites-available/}opengnsys.conf ]; do
457                if [ -e $config ] && ! grep -q "/rest" $config; then
458                        cat << EOT >> $config
459<Directory $INSTALL_TARGET/www/rest>
460        RewriteEngine On
461        RewriteBase /opengnsys/rest/
462        RewriteCond %{REQUEST_FILENAME} !-f
463        RewriteRule ^ index.php [QSA,L]
464</Directory>
465EOT
466                fi
467        done
468
469        # Reiniciar Apache.
470        $APACHESERV restart
471
472        # Variables de ejecución de Apache.
473        # - APACHE_RUN_USER
474        # - APACHE_RUN_GROUP
475        if [ -f $APACHECFGDIR/envvars ]; then
476                source $APACHECFGDIR/envvars
477        fi
478        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
479        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
480}
481
482# Configurar servicio Rsync.
483function rsyncConfigure()
484{
485        local service
486
487        # Configurar acceso a Rsync.
488        if [ ! -f /etc/rsyncd.conf ]; then
489                echoAndLog "${FUNCNAME}(): Configuring Rsync service."
490                NEWFILES="$NEWFILES /etc/rsyncd.conf"
491                sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \
492                    $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf
493                # Habilitar Rsync.
494                if [ -f /etc/default/rsync ]; then
495                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
496                fi
497                if [ -f $INETDCFGDIR/rsync ]; then
498                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
499                else
500                        cat << EOT > $INETDCFGDIR/rsync
501service rsync
502{
503        disable = no
504        socket_type = stream
505        wait = no
506        user = root
507        server = $(which rsync)
508        server_args = --daemon
509        log_on_failure += USERID
510        flags = IPv6
511}
512EOT
513                fi
514                # Activar e iniciar Rsync.
515                service="rsync"  $ENABLESERVICE
516                service="xinetd"
517                $ENABLESERVICE; $STARTSERVICE
518        fi
519}
520
521# Copiar ficheros del OpenGnsys Web Console.
522function updateWebFiles()
523{
524        local ERRCODE COMPATDIR f
525
526        echoAndLog "${FUNCNAME}(): Updating web files..."
527
528        # Copiar los ficheros nuevos conservando el archivo de configuración de acceso.
529        backupFile $INSTALL_TARGET/www/controlacceso.php
530        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
531        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
532        ERRCODE=$?
533        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
534        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
535        unzip -o $WORKDIR/opengnsys/admin/slim-2.6.1.zip -d $INSTALL_TARGET/www/rest
536        if [ $ERRCODE != 0 ]; then
537                errorAndLog "${FUNCNAME}(): Error updating web files."
538                exit 1
539        fi
540        restoreFile $INSTALL_TARGET/www/controlacceso.php
541
542        # Cambiar acceso a protocolo HTTPS.
543        if grep -q "http://" $INSTALL_TARGET/www/controlacceso.php 2>/dev/null; then
544                echoAndLog "${FUNCNAME}(): updating web access file"
545                perl -pi -e 's!http://!https://!g' $INSTALL_TARGET/www/controlacceso.php
546                NEWFILES="$NEWFILES $INSTALL_TARGET/www/controlacceso.php"
547        fi
548
549        # Compatibilidad con dispositivos móviles.
550        COMPATDIR="$INSTALL_TARGET/www/principal"
551        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
552                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
553        done
554        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
555
556        # Cambiar permisos para ficheros especiales.
557        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
558        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
559        # Fichero de logs del agente OGAgent.
560        touch $INSTALL_TARGET/log/ogagent.log
561        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/ogagent.log
562
563        echoAndLog "${FUNCNAME}(): Web files updated successfully."
564}
565
566# Copiar carpeta de Interface
567function updateInterfaceAdm()
568{
569        local errcode=0
570
571        # Crear carpeta y copiar Interface
572        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
573        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
574        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
575        errcoce=$?
576        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
577        if [ $errcode -ne 0 ]; then
578                echoAndLog "${FUNCNAME}(): error while updating admin interface"
579                exit 1
580        fi
581        chmod -R +x $INSTALL_TARGET/client/interfaceAdm
582        chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
583        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
584        echoAndLog "${FUNCNAME}(): Admin interface updated successfully."
585}
586
587# Crear documentación Doxygen para la consola web.
588function makeDoxygenFiles()
589{
590        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
591        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
592                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
593        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
594                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
595                return 1
596        fi
597        rm -fr "$INSTALL_TARGET/www/api"
598        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
599        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
600        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
601        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
602}
603
604
605# Crea la estructura base de la instalación de opengnsys
606function createDirs()
607{
608        # Crear estructura de directorios.
609        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
610        local dir
611
612        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
613        mkdir -p ${INSTALL_TARGET}/{client,images}
614        mkdir -p ${INSTALL_TARGET}/log/clients
615        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
616        # Detectar directorio de instalación de TFTP.
617        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
618                for dir in /var/lib/tftpboot /srv/tftp; do
619                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
620                done
621        fi
622        mkdir -p ${INSTALL_TARGET}/tftpboot/menu.lst
623        if [ $? -ne 0 ]; then
624                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
625                return 1
626        fi
627
628        # Crear usuario ficticio.
629        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
630                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
631        else
632                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
633                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
634                if [ $? -ne 0 ]; then
635                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
636                        return 1
637                fi
638        fi
639
640        # Establecer los permisos básicos.
641        echoAndLog "${FUNCNAME}(): setting directory permissions"
642        chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/menu.lst}
643        mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples
644        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
645        chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/menu.lst}
646        if [ $? -ne 0 ]; then
647                errorAndLog "${FUNCNAME}(): error while setting permissions"
648                return 1
649        fi
650
651        # Mover el fichero de registro al directorio de logs.
652        echoAndLog "${FUNCNAME}(): moving update log file"
653        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
654        chmod 600 $LOG_FILE
655
656        echoAndLog "${FUNCNAME}(): directory paths created"
657        return 0
658}
659
660# Copia ficheros de configuración y ejecutables genéricos del servidor.
661function updateServerFiles()
662{
663        # No copiar ficheros del antiguo cliente Initrd
664        local SOURCES=( repoman/bin \
665                        server/bin \
666                        admin/Sources/Services/ogAdmServerAux \
667                        admin/Sources/Services/ogAdmRepoAux \
668                        server/tftpboot \
669                        installer/opengnsys_uninstall.sh \
670                        doc )
671        local TARGETS=( bin \
672                        bin \
673                        sbin/ogAdmServerAux \
674                        sbin/ogAdmRepoAux \
675                        tftpboot \
676                        lib/opengnsys_uninstall.sh \
677                        doc )
678
679        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
680                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
681                exit 1
682        fi
683
684        echoAndLog "${FUNCNAME}(): updating files in server directories"
685        pushd $WORKDIR/opengnsys >/dev/null
686        local i
687        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
688                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
689                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
690                else
691                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
692                fi
693        done
694        popd >/dev/null
695        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
696        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
697                echoAndLog "${FUNCNAME}(): updating DHCP files"
698                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
699                $DHCPSERV restart
700                NEWFILES="/etc/dhcp*/dhcpd*.conf"
701        fi
702        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
703                echoAndLog "${FUNCNAME}(): updating new init file"
704                backupFile /etc/init.d/opengnsys
705                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
706                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
707        fi
708        if egrep -q "(UrlMsg=.*msgbrowser.php)|(UrlMenu=http://)" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
709                echoAndLog "${FUNCNAME}(): updating new client config file"
710                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
711                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
712                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
713        fi
714
715        echoAndLog "${FUNCNAME}(): updating cron files"
716        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
717        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
718        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
719        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
720        echoAndLog "${FUNCNAME}(): server files updated successfully."
721}
722
723####################################################################
724### Funciones de compilación de código fuente de servicios
725####################################################################
726
727# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
728function moveNewService()
729{
730        local service
731
732        # Recibe 2 parámetros: fichero origen y directorio destino.
733        [ $# == 2 ] || return 1
734        [ -f  $1 -a -d $2 ] || return 1
735
736        # Comparar los ficheros.
737        if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
738                # Parar los servicios si fuese necesario.
739                [ -z "$NEWSERVICES" ] && service="opengnsys" $STOPSERVICE
740                # Nuevo servicio.
741                NEWSERVICES="$NEWSERVICES $(basename $1)"
742                # Mover el nuevo fichero de servicio
743                mv $1 $2
744        fi
745}
746
747
748# Recompilar y actualiza los serivicios y clientes.
749function compileServices()
750{
751        local hayErrores=0
752
753        # Compilar OpenGnsys Server
754        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Admin Server"
755        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
756        make && moveNewService ogAdmServer $INSTALL_TARGET/sbin
757        if [ $? -ne 0 ]; then
758                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
759                hayErrores=1
760        fi
761        popd
762        # Compilar OpenGnsys Repository Manager
763        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Repository Manager"
764        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
765        make && moveNewService ogAdmRepo $INSTALL_TARGET/sbin
766        if [ $? -ne 0 ]; then
767                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager"
768                hayErrores=1
769        fi
770        popd
771        # Compilar OpenGnsys Agent
772        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Agent"
773        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
774        make && moveNewService ogAdmAgent $INSTALL_TARGET/sbin
775        if [ $? -ne 0 ]; then
776                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
777                hayErrores=1
778        fi
779        popd
780
781        # Compilar OpenGnsys Client
782        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Client"
783        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
784        make && mv ogAdmClient $INSTALL_TARGET/client/bin
785        if [ $? -ne 0 ]; then
786                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Client"
787                hayErrores=1
788        fi
789        popd
790
791        return $hayErrores
792}
793
794
795####################################################################
796### Funciones instalacion cliente OpenGnsys
797####################################################################
798
799# Actualizar cliente OpenGnsys
800function updateClient()
801{
802        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
803        local FILENAME=ogLive-vivid-3.19.0-49-generic-r4795.iso         # 1.1.0-rc2
804        local SOURCEFILE=$DOWNLOADURL/$FILENAME
805        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
806        local SOURCELENGTH
807        local TARGETLENGTH
808        local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img
809        local OGVMLINUZ=$INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz
810        local SAMBAPASS
811        local KERNELVERSION
812
813        # Comprobar si debe actualizarse el cliente.
814        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
815        TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}')
816        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
817        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
818                echoAndLog "${FUNCNAME}(): Loading Client"
819                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
820                if [ ! -s $TARGETFILE ]; then
821                        errorAndLog "${FUNCNAME}(): Error loading OpenGnsys Client"
822                        return 1
823                fi
824                # Actaulizar la imagen ISO del ogclient.
825                echoAndLog "${FUNCNAME}(): Updatting ogclient files"
826                $INSTALL_TARGET/bin/installoglive
827               
828                # Obtiene versión del Kernel del cliente (con 2 decimales).
829                KERNELVERSION=$(file -bkr $OGVMLINUZ 2>/dev/null | \
830                                awk '/Linux/ { for (i=1; i<=NF; i++)
831                                                   if ($i~/version/) {
832                                                      v=$(i+1);
833                                                      printf ("%d",v);
834                                                      sub (/[0-9]*\./,"",v);
835                                                      printf (".%02d",v)
836                                             } }')
837                # Actaulizar la base de datos adaptada al Kernel del cliente.
838                OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-postinst.sql"
839                if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
840                        perl -pi -e "s/KERNELVERSION/$KERNELVERSION/g" $OPENGNSYS_DBUPDATEFILE
841                        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
842                fi
843
844                echoAndLog "${FUNCNAME}(): Client update successfully"
845        else
846                # Si no existe, crear el fichero de claves de Rsync.
847                if [ ! -f /etc/rsyncd.secrets ]; then
848                        echoAndLog "${FUNCNAME}(): Restoring client access key"
849                        SAMBAPASS=$(gzip -dc $OGINITRD | \
850                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
851                                    grep "^[    ].*OPTIONS=" | \
852                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
853                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
854                                        $INSTALL_TARGET/bin/setsmbpass
855                else
856                        echoAndLog "${FUNCNAME}(): Client is already updated"
857                fi
858        fi
859}
860
861# Comprobar permisos y ficheros.
862function checkFiles()
863{
864        # Comprobar permisos adecuados.
865        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
866                echoAndLog "${FUNCNAME}(): Checking permissions."
867                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
868        fi
869
870        # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
871        if [ -f /tmp/dstate ]; then
872                echoAndLog "${FUNCNAME}(): Delete unused files."
873                rm -f /tmp/dstate
874        fi
875}
876
877# Resumen de actualización.
878function updateSummary()
879{
880        # Actualizar fichero de versión y revisión.
881        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
882        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
883
884        [ -f $VERSIONFILE ] || echo "OpenGnsys" >$VERSIONFILE
885        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
886
887        echo
888        echoAndLog "OpenGnsys Update Summary"
889        echo       "========================"
890        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
891        echoAndLog "Update log file:                  $LOG_FILE"
892        if [ -n "$NEWFILES" ]; then
893                echoAndLog "Check new config files:           $(echo $NEWFILES)"
894        fi
895        if [ -n "$NEWSERVICES" ]; then
896                echoAndLog "New compiled services:            $(echo $NEWSERVICES)"
897                # Indicar si se debe reiniciar servicios manualmente o usando el Cron.
898                [ -f /etc/default/opengnsys ] && source /etc/default/opengnsys
899                if [ "$RUN_CRONJOB" == "no" ]; then
900                        echoAndLog "        WARNING: you must restart OpenGnsys services manually."
901                else
902                        echoAndLog "        New OpenGnsys services will be restarted by the cronjob."
903                fi
904        fi
905        echoAndLog "Warning: You must to clear web browser cache before loading OpenGnSys page."
906        echo
907}
908
909
910
911#####################################################################
912####### Proceso de actualización de OpenGnsys
913#####################################################################
914
915
916echoAndLog "OpenGnsys update begins at $(date)"
917
918pushd $WORKDIR
919
920# Comprobar si hay conexión y detectar parámetros de red por defecto.
921checkNetworkConnection
922if [ $? -ne 0 ]; then
923        errorAndLog "Error connecting to server. Causes:"
924        errorAndLog " - Network is unreachable, review devices parameters."
925        errorAndLog " - You are inside a private network, configure the proxy service."
926        errorAndLog " - Server is temporally down, try agian later."
927        exit 1
928fi
929getNetworkSettings
930
931# Comprobar auto-actualización del programa.
932if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
933        checkAutoUpdate
934        if [ $? -ne 0 ]; then
935                echoAndLog "OpenGnsys updater has been overwritten."
936                echoAndLog "Please, re-execute this script."
937                exit
938        fi
939fi
940
941# Detectar datos de auto-configuración del instalador.
942autoConfigure
943
944# Instalar dependencias.
945installDependencies ${DEPENDENCIES[*]}
946if [ $? -ne 0 ]; then
947        errorAndLog "Error: you may install all needed dependencies."
948        exit 1
949fi
950
951# Arbol de directorios de OpenGnsys.
952createDirs ${INSTALL_TARGET}
953if [ $? -ne 0 ]; then
954        errorAndLog "Error while creating directory paths!"
955        exit 1
956fi
957
958# Si es necesario, descarga el repositorio de código en directorio temporal
959if [ $USESVN -eq 1 ]; then
960        svnExportCode $SVN_URL
961        if [ $? -ne 0 ]; then
962                errorAndLog "Error while getting code from svn"
963                exit 1
964        fi
965else
966        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
967fi
968
969# Si existe fichero de actualización de la base de datos; aplicar cambios.
970INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
971REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
972if [ "$INSTVERSION" == "$REPOVERSION" ]; then
973        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION.sql"
974else
975        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
976fi
977if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
978        echoAndLog "Updating tables from file: $(basename $OPENGNSYS_DBUPDATEFILE)"
979        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
980else
981        echoAndLog "Database unchanged."
982fi
983
984# Actualizar ficheros complementarios del servidor
985updateServerFiles
986if [ $? -ne 0 ]; then
987        errorAndLog "Error updating OpenGnsys Server files"
988        exit 1
989fi
990
991# Configurar Rsync.
992rsyncConfigure
993
994# Actualizar ficheros del cliente
995updateClientFiles
996updateInterfaceAdm
997
998# Actualizar páqinas web
999apacheConfiguration
1000updateWebFiles
1001if [ $? -ne 0 ]; then
1002        errorAndLog "Error updating OpenGnsys Web Admin files"
1003        exit 1
1004fi
1005# Generar páginas Doxygen para instalar en el web
1006makeDoxygenFiles
1007
1008# Recompilar y actualizar los servicios del sistema
1009compileServices
1010
1011# Actaulizar ficheros auxiliares del cliente
1012updateClient
1013if [ $? -ne 0 ]; then
1014        errorAndLog "Error updating clients"
1015        exit 1
1016fi
1017
1018# Comprobar permisos y ficheros.
1019checkFiles
1020
1021# Mostrar resumen de actualización.
1022updateSummary
1023
1024#rm -rf $WORKDIR
1025echoAndLog "OpenGnsys update finished at $(date)"
1026
1027popd
1028
Note: See TracBrowser for help on using the repository browser.