source: installer/opengnsys_installer.sh @ 49c6891

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 49c6891 was 49c6891, checked in by ramon <ramongomez@…>, 15 years ago

Mejora en detección de modo de ejecución del instalador, copia documentación y limpieza de código; creado fichero de versión del proyecto.

git-svn-id: https://opengnsys.es/svn/trunk@713 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 32.6 KB
Line 
1#!/bin/bash
2
3#####################################################################
4####### Script instalador OpenGnsys
5####### autor: Luis Guillén <lguillen@unizar.es>
6#####################################################################
7
8
9
10# Sólo ejecutable por usuario root
11if [ "$(whoami)" != 'root' ]
12then
13        echo "ERROR: this program must run under root privileges!!"
14        exit 1
15fi
16
17# Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1).
18PROGRAMDIR=$(readlink -e $(dirname "$0"))
19if [ -d "$PROGRAMDIR/../installer" ]; then
20    USESVN=0
21else
22    USESVN=1
23    SVN_URL=svn://www.informatica.us.es:3690/opengnsys/trunk
24fi
25        echo $0.$PROGRAMDIR.$USESVN.
26        exit
27
28WORKDIR=/tmp/opengnsys_installer
29mkdir -p $WORKDIR
30pushd $WORKDIR
31
32INSTALL_TARGET=/opt/opengnsys
33LOG_FILE=/tmp/opengnsys_installation.log
34
35# Array con las dependencias
36DEPENDENCIES=( subversion apache2 php5 mysql-server php5-mysql nfs-kernel-server dhcp3-server udpcast bittorrent tftp-hpa tftpd-hpa syslinux openbsd-inetd update-inetd build-essential libmysqlclient15-dev wget doxygen graphviz)
37
38MYSQL_ROOT_PASSWORD="passwordroot"
39
40# Datos de base de datos
41OPENGNSYS_DATABASE=ogBDAdmin
42OPENGNSYS_DB_USER=usuog
43OPENGNSYS_DB_PASSWD=passusuog
44OPENGNSYS_DB_DEFAULTUSER=opengnsys
45OPENGNSYS_DB_DEFAULTPASSWD=opengnsys
46OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/ogBDAdmin.sql
47
48
49
50#####################################################################
51####### Algunas funciones útiles de propósito general:
52#####################################################################
53function getDateTime()
54{
55        echo `date +%Y%m%d-%H%M%S`
56}
57
58# Escribe a fichero y muestra por pantalla
59function echoAndLog()
60{
61        echo $1
62        FECHAHORA=`getDateTime`
63        echo "$FECHAHORA;$SSH_CLIENT;$1" >> $LOG_FILE
64}
65
66function errorAndLog()
67{
68        echo "ERROR: $1"
69        FECHAHORA=`getDateTime`
70        echo "$FECHAHORA;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
71}
72
73# comprueba si el elemento pasado en $2 esta en el array $1
74function isInArray()
75{
76        if [ $# -ne 2 ]; then
77                errorAndLog "${FUNCNAME}(): invalid number of parameters"
78                exit 1
79        fi
80
81        echoAndLog "${FUNCNAME}(): checking if $2 is in $1"
82        local deps
83        eval "deps=( \"\${$1[@]}\" )"
84        elemento=$2
85
86        local is_in_array=1
87        # copia local del array del parametro 1
88        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
89        do
90                if [ "${deps[$i]}" = "${elemento}" ]; then
91                        echoAndLog "isInArray(): $elemento found in array"
92                        is_in_array=0
93                fi
94        done
95
96        if [ $is_in_array -ne 0 ]; then
97                echoAndLog "${FUNCNAME}(): $elemento NOT found in array"
98        fi
99
100        return $is_in_array
101
102}
103
104#####################################################################
105####### Funciones de manejo de paquetes Debian
106#####################################################################
107
108function checkPackage()
109{
110        package=$1
111        if [ -z $package ]; then
112                errorAndLog "checkPackage(): parameter required"
113                exit 1
114        fi
115        echoAndLog "checkPackage(): checking if package $package exists"
116        dpkg -L $package &>/dev/null
117        if [ $? -eq 0 ]; then
118                echoAndLog "checkPackage(): package $package exists"
119                return 0
120        else
121                echoAndLog "checkPackage(): package $package doesn't exists"
122                return 1
123        fi
124}
125
126# recibe array con dependencias
127# por referencia deja un array con las dependencias no resueltas
128# devuelve 1 si hay alguna dependencia no resuelta
129function checkDependencies()
130{
131        if [ $# -ne 2 ]; then
132                errorAndLog "checkDependencies(): invalid number of parameters"
133                exit 1
134        fi
135
136        echoAndLog "checkDependencies(): checking dependences"
137        uncompletedeps=0
138
139        # copia local del array del parametro 1
140        local deps
141        eval "deps=( \"\${$1[@]}\" )"
142
143        declare -a local_notinstalled
144
145        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
146        do
147                checkPackage ${deps[$i]}
148                if [ $? -ne 0 ]; then
149                        local_notinstalled[$uncompletedeps]=$package
150                        let uncompletedeps=uncompletedeps+1
151                fi
152        done
153
154        # relleno el array especificado en $2 por referencia
155        for (( i = 0 ; i < ${#local_notinstalled[@]} ; i++ ))
156        do
157                eval "${2}[$i]=${local_notinstalled[$i]}"
158        done
159
160        # retorna el numero de paquetes no resueltos
161        echoAndLog "checkDependencies(): dependencies uncompleted: $uncompletedeps"
162        return $uncompletedeps
163}
164
165# Recibe un array con las dependencias y lo instala
166function installDependencies()
167{
168        if [ $# -ne 1 ]; then
169                errorAndLog "installDependencies(): invalid number of parameters"
170                exit 1
171        fi
172        echoAndLog "installDependencies(): installing uncompleted dependencies"
173
174        # copia local del array del parametro 1
175        local deps
176        eval "deps=( \"\${$1[@]}\" )"
177
178        local string_deps=""
179        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
180        do
181                string_deps="$string_deps ${deps[$i]}"
182        done
183
184        if [ -z "${string_deps}" ]; then
185                errorAndLog "installDependencies(): array of dependeces is empty"
186                exit 1
187        fi
188
189        OLD_DEBIAN_FRONTEND=$DEBIAN_FRONTEND
190        export DEBIAN_FRONTEND=noninteractive
191
192        echoAndLog "installDependencies(): now ${string_deps} will be installed"
193        apt-get -y install --force-yes ${string_deps}
194        if [ $? -ne 0 ]; then
195                errorAndLog "installDependencies(): error installing dependencies"
196                return 1
197        fi
198
199        DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND
200        echoAndLog "installDependencies(): dependencies installed"
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}(): realizando backup de $fichero"
221
222        # realiza una copia de la última configuración como last
223        cp -p $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 -p $fichero "${fichero}-${fecha}"
228        fi
229
230        echoAndLog "${FUNCNAME}(): backup realizado"
231}
232
233#####################################################################
234####### Funciones para el manejo de bases de datos
235#####################################################################
236
237# This function set password to root
238function mysqlSetRootPassword()
239{
240        if [ $# -ne 1 ]; then
241                errorAndLog "mysqlSetRootPassword(): invalid number of parameters"
242                exit 1
243        fi
244
245        local root_mysql=$1
246        echoAndLog "mysqlSetRootPassword(): setting root password in MySQL server"
247        /usr/bin/mysqladmin -u root password ${root_mysql}
248        if [ $? -ne 0 ]; then
249                errorAndLog "mysqlSetRootPassword(): error while setting root password in MySQL server"
250                return 1
251        fi
252        echoAndLog "mysqlSetRootPassword(): root password saved!"
253        return 0
254}
255
256# Si el servicio mysql esta ya instalado cambia la variable de la clave del root por la ya existente
257function mysqlGetRootPassword(){
258        local pass_mysql
259        local pass_mysql2
260        stty -echo
261        echo "Existe un servicio mysql ya instalado"
262        read -p  "Insertar clave de root de Mysql: " pass_mysql
263        echo ""
264        read -p "Confirmar clave:" pass_mysql2
265        echo ""
266        stty echo
267        if [ "$pass_mysql" == "$pass_mysql2" ] ;then
268                MYSQL_ROOT_PASSWORD=$pass_mysql
269                echo "La clave es: ${MYSQL_ROOT_PASSWORD}"
270                return 0
271        else
272                echo "Las claves no coinciden no se configura la clave del servidor de base de datos."
273                echo "las operaciones con la base de datos daran error"
274                return 1
275        fi
276
277
278}
279
280# comprueba si puede conectar con mysql con el usuario root
281function mysqlTestConnection()
282{
283        if [ $# -ne 1 ]; then
284                errorAndLog "mysqlTestConnection(): invalid number of parameters"
285                exit 1
286        fi
287
288        local root_password="${1}"
289        echoAndLog "mysqlTestConnection(): checking connection to mysql..."
290        echo "" | mysql -uroot -p"${root_password}"
291        if [ $? -ne 0 ]; then
292                errorAndLog "mysqlTestConnection(): connection to mysql failed, check root password and if daemon is running!"
293                return 1
294        else
295                echoAndLog "mysqlTestConnection(): connection success"
296                return 0
297        fi
298}
299
300# comprueba si la base de datos existe
301function mysqlDbExists()
302{
303        if [ $# -ne 2 ]; then
304                errorAndLog "mysqlDbExists(): invalid number of parameters"
305                exit 1
306        fi
307
308        local root_password="${1}"
309        local database=$2
310        echoAndLog "mysqlDbExists(): checking if $database exists..."
311        echo "show databases" | mysql -uroot -p"${root_password}" | grep "^${database}$"
312        if [ $? -ne 0 ]; then
313                echoAndLog "mysqlDbExists():database $database doesn't exists"
314                return 1
315        else
316                echoAndLog "mysqlDbExists():database $database exists"
317                return 0
318        fi
319}
320
321function mysqlCheckDbIsEmpty()
322{
323        if [ $# -ne 2 ]; then
324                errorAndLog "mysqlCheckDbIsEmpty(): invalid number of parameters"
325                exit 1
326        fi
327
328        local root_password="${1}"
329        local database=$2
330        echoAndLog "mysqlCheckDbIsEmpty(): checking if $database is empty..."
331        num_tablas=`echo "show tables" | mysql -uroot -p"${root_password}" "${database}" | wc -l`
332        if [ $? -ne 0 ]; then
333                errorAndLog "mysqlCheckDbIsEmpty(): error executing query, check database and root password"
334                exit 1
335        fi
336
337        if [ $num_tablas -eq 0 ]; then
338                echoAndLog "mysqlCheckDbIsEmpty():database $database is empty"
339                return 0
340        else
341                echoAndLog "mysqlCheckDbIsEmpty():database $database has tables"
342                return 1
343        fi
344
345}
346
347
348function mysqlImportSqlFileToDb()
349{
350        if [ $# -ne 3 ]; then
351                errorAndLog "${FNCNAME}(): invalid number of parameters"
352                exit 1
353        fi
354
355        local root_password="${1}"
356        local database=$2
357        local sqlfile=$3
358
359        if [ ! -f $sqlfile ]; then
360                errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
361                return 1
362        fi
363
364        echoAndLog "${FUNCNAME}(): importing sql file to ${database}..."
365        perl -pi -e "s/SERVERIP/$SERVERIP/g; s/DEFAULTUSER/$OPENGNSYS_DB_DEFAULTUSER/g; s/DEFAULTPASSWD/$OPENGNSYS_DB_DEFAULTPASSWD/g" $sqlfile
366        mysql -uroot -p"${root_password}" "${database}" < $sqlfile
367        if [ $? -ne 0 ]; then
368                errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
369                return 1
370        fi
371        echoAndLog "${FUNCNAME}(): file imported to database $database"
372        return 0
373}
374
375# Crea la base de datos
376function mysqlCreateDb()
377{
378        if [ $# -ne 2 ]; then
379                errorAndLog "${FUNCNAME}(): invalid number of parameters"
380                exit 1
381        fi
382
383        local root_password="${1}"
384        local database=$2
385
386        echoAndLog "${FUNCNAME}(): creating database..."
387        mysqladmin -u root --password="${root_password}" create $database
388        if [ $? -ne 0 ]; then
389                errorAndLog "${FUNCNAME}(): error while creating database $database"
390                return 1
391        fi
392        echoAndLog "${FUNCNAME}(): database $database created"
393        return 0
394}
395
396
397function mysqlCheckUserExists()
398{
399        if [ $# -ne 2 ]; then
400                errorAndLog "mysqlCheckUserExists(): invalid number of parameters"
401                exit 1
402        fi
403
404        local root_password="${1}"
405        local userdb=$2
406
407        echoAndLog "mysqlCheckUserExists(): checking if $userdb exists..."
408        echo "select user from user where user='${userdb}'\\G" |mysql -uroot -p"${root_password}" mysql | grep user
409        if [ $? -ne 0 ]; then
410                echoAndLog "mysqlCheckUserExists(): user doesn't exists"
411                return 1
412        else
413                echoAndLog "mysqlCheckUserExists(): user already exists"
414                return 0
415        fi
416
417}
418
419# Crea un usuario administrativo para la base de datos
420function mysqlCreateAdminUserToDb()
421{
422        if [ $# -ne 4 ]; then
423                errorAndLog "mysqlCreateAdminUserToDb(): invalid number of parameters"
424                exit 1
425        fi
426
427        local root_password=$1
428        local database=$2
429        local userdb=$3
430        local passdb=$4
431
432        echoAndLog "mysqlCreateAdminUserToDb(): creating admin user ${userdb} to database ${database}"
433
434        cat > $WORKDIR/create_${database}.sql <<EOF
435GRANT USAGE ON *.* TO '${userdb}'@'localhost' IDENTIFIED BY '${passdb}' ;
436GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION ;
437FLUSH PRIVILEGES ;
438EOF
439        mysql -u root --password=${root_password} < $WORKDIR/create_${database}.sql
440        if [ $? -ne 0 ]; then
441                errorAndLog "mysqlCreateAdminUserToDb(): error while creating user in mysql"
442                rm -f $WORKDIR/create_${database}.sql
443                return 1
444        else
445                echoAndLog "mysqlCreateAdminUserToDb(): user created ok"
446                rm -f $WORKDIR/create_${database}.sql
447                return 0
448        fi
449}
450
451
452#####################################################################
453####### Funciones para el manejo de Subversion
454#####################################################################
455
456function svnExportCode()
457{
458        if [ $# -ne 1 ]; then
459                errorAndLog "${FUNCNAME}(): invalid number of parameters"
460                exit 1
461        fi
462
463        local url=$1
464
465        echoAndLog "${FUNCNAME}(): downloading subversion code..."
466
467        svn export "${url}" opengnsys
468        if [ $? -ne 0 ]; then
469                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
470                return 1
471        fi
472        echoAndLog "${FUNCNAME}(): subversion code downloaded"
473        return 0
474}
475
476
477############################################################
478###  Detectar red
479############################################################
480
481function getNetworkSettings()
482{
483        # Variables globales definidas:
484        # - SERVERIP: IP local del servidor.
485        # - NETIP:    IP de la red.
486        # - NETMASK:  máscara de red.
487        # - NETBROAD: IP de difusión de la red.
488        # - ROUTERIP: IP del router.
489        # - DNSIP:    IP del servidor DNS.
490
491        echoAndLog "getNetworkSettings(): Detecting default network parameters."
492        SERVERIP=$(LANG=C ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | head -n1 | awk '{print $1}')
493        NETMASK=$(LANG=C ifconfig | grep 'Mask:'| grep -v '127.0.0.1' | cut -d: -f4 | head -n1 | awk '{print $1}')
494        NETBROAD=$(LANG=C ifconfig | grep 'Bcast:'| grep -v '127.0.0.1' | cut -d: -f3 | head -n1 | awk '{print $1}')
495        NETIP=$(netstat -r | grep $NETMASK | head -n1 | awk '{print $1}')
496        ROUTERIP=$(netstat -nr | awk '$1~/0\.0\.0\.0/ {print $2}')
497        DNSIP=$(awk '/nameserver/ {print $2}' /etc/resolv.conf | head -n1)
498        if [ -z "$NETIP" -o -z "$NETMASK" ]; then
499                errorAndLog "getNetworkSettings(): Network not detected."
500                exit 1
501        fi
502
503        # Variables de ejecución de Apache
504        # - APACHE_RUN_USER
505        # - APACHE_RUN_GROUP
506        if [ -f /etc/apache2/envvars ]; then
507                source /etc/apache2/envvars
508        fi
509        APACHE_RUN_USER=${APACHE_RUN_USER:-"www-data"}
510        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"www-data"}
511}
512
513
514############################################################
515### Esqueleto para el Servicio pxe y contenedor tftpboot ###
516############################################################
517
518function tftpConfigure() {
519        echo "Configurando el servicio tftp"
520        basetftp=/var/lib/tftpboot
521
522        # reiniciamos demonio internet ????? porque ????
523        /etc/init.d/openbsd-inetd start
524
525        # preparacion contenedor tftpboot
526        cp -pr /usr/lib/syslinux/ ${basetftp}/syslinux
527        cp /usr/lib/syslinux/pxelinux.0 ${basetftp}
528        # prepamos el directorio de la configuracion de pxe
529        mkdir -p ${basetftp}/pxelinux.cfg
530        cat > ${basetftp}/pxelinux.cfg/default <<EOF
531DEFAULT pxe
532
533LABEL pxe
534KERNEL linux
535APPEND initrd=initrd.gz ip=dhcp ro vga=788 irqpoll acpi=on
536EOF
537        # comprobamos el servicio tftp
538        sleep 1
539        testPxe
540        ## damos perfimos de lectura a usuario web.
541        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP ${basetftp}
542}
543
544function testPxe () {
545        cd /tmp
546        echo "comprobando servicio pxe ..... Espere"
547        tftp -v localhost -c get pxelinux.0 /tmp/pxelinux.0 && echo "servidor tftp OK" || echo "servidor tftp KO"
548        cd /
549}
550
551########################################################################
552## Configuracion servicio NFS
553########################################################################
554
555# ADVERTENCIA: usa variables globales NETIP y NETMASK!
556function nfsConfigure()
557{
558        echoAndLog "${FUNCNAME}(): Config nfs server."
559
560        backupFile /etc/exports
561
562        nfsAddExport /opt/opengnsys/client ${NETIP}/${NETMASK}:ro,no_subtree_check,no_root_squash,sync
563        if [ $? -ne 0 ]; then
564                errorAndLog "${FUNCNAME}(): error while adding nfs client config"
565                return 1
566        fi
567
568        nfsAddExport /opt/opengnsys/images ${NETIP}/${NETMASK}:rw,no_subtree_check,no_root_squash,sync,crossmnt
569        if [ $? -ne 0 ]; then
570                errorAndLog "${FUNCNAME}(): error while adding nfs images config"
571                return 1
572        fi
573
574        nfsAddExport /opt/opengnsys/log/clients ${NETIP}/${NETMASK}:rw,no_subtree_check,no_root_squash,sync
575        if [ $? -ne 0 ]; then
576                errorAndLog "${FUNCNAME}(): error while adding logging client config"
577                return 1
578        fi
579
580        /etc/init.d/nfs-kernel-server restart
581
582        exportfs -va
583        if [ $? -ne 0 ]; then
584                errorAndLog "${FUNCNAME}(): error while configure exports"
585                return 1
586        fi
587
588        echoAndLog "${FUNCNAME}(): Added NFS configuration to file \"/etc/exports\"."
589        return 0
590}
591
592
593# ejemplos:
594#nfsAddExport /opt/opengnsys 192.168.0.0/255.255.255.0:ro,no_subtree_check,no_root_squash,sync
595#nfsAddExport /opt/opengnsys 192.168.0.0/255.255.255.0
596#nfsAddExport /opt/opengnsys 80.20.2.1:ro 192.123.32.2:rw
597function nfsAddExport()
598{
599        if [ $# -lt 2 ]; then
600                errorAndLog "${FUNCNAME}(): invalid number of parameters"
601                exit 1
602        fi
603
604        if [ ! -f /etc/exports ]; then
605                errorAndLog "${FUNCNAME}(): /etc/exports don't exists"
606                return 1
607        fi
608
609        local export="${1}"
610        local contador=0
611        local cadenaexport
612
613        grep "^${export}" /etc/exports > /dev/null
614        if [ $? -eq 0 ]; then
615                echoAndLog "${FUNCNAME}(): $export exists in /etc/exports, omiting"
616                return 0
617        fi
618
619        cadenaexport="${export}"
620        for parametro in $*
621        do
622                if [ $contador -gt 0 ]
623                then
624                        host=`echo $parametro | awk -F: '{print $1}'`
625                        options=`echo $parametro | awk -F: '{print $2}'`
626                        if [ "${host}" == "" ]; then
627                                errorAndLog "${FUNCNAME}(): host can't be empty"
628                                return 1
629                        fi
630                        cadenaexport="${cadenaexport}\t${host}"
631
632                        if [ "${options}" != "" ]; then
633                                cadenaexport="${cadenaexport}(${options})"
634                        fi
635                fi
636                let contador=contador+1
637        done
638
639        echo -en "$cadenaexport\n" >> /etc/exports
640
641        echoAndLog "${FUNCNAME}(): add $export to /etc/exports"
642
643        return 0
644}
645
646########################################################################
647## Configuracion servicio DHCP
648########################################################################
649
650function dhcpConfigure()
651{
652        echoAndLog "${FUNCNAME}(): Sample DHCP Configuration."
653
654        backupFile /etc/dhcp3/dhcpd.conf
655
656        sed -e "s/SERVERIP/$SERVERIP/g" \
657            -e "s/NETIP/$NETIP/g" \
658            -e "s/NETMASK/$NETMASK/g" \
659            -e "s/NETBROAD/$NETBROAD/g" \
660            -e "s/ROUTERIP/$ROUTERIP/g" \
661            -e "s/DNSIP/$DNSIP/g" \
662            $WORKDIR/opengnsys/server/DHCP/dhcpd.conf > /etc/dhcp3/dhcpd.conf
663        if [ $? -ne 0 ]; then
664                errorAndLog "${FUNCNAME}(): error while configuring dhcp server"
665                return 1
666        fi
667
668        /etc/init.d/dhcp3-server restart
669        echoAndLog "${FUNCNAME}(): Sample DHCP Configured in file \"/etc/dhcp3/dhcpd.conf\"."
670        return 0
671}
672
673
674#####################################################################
675####### Funciones específicas de la instalación de Opengnsys
676#####################################################################
677
678# Copiar ficheros del OpenGnSys Web Console.
679function installWebFiles()
680{
681        echoAndLog "${FUNCNAME}(): Installing web files..."
682        cp -ar $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para doxigen
683        if [ $? != 0 ]; then
684                errorAndLog "${FUNCNAME}(): Error copying web files."
685                exit 1
686        fi
687        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
688        # Cambiar permisos para ficheros especiales.
689        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP \
690                        $INSTALL_TARGET/www/includes \
691                        $INSTALL_TARGET/www/comandos/gestores/filescripts \
692                        $INSTALL_TARGET/www/images/iconos
693        echoAndLog "${FUNCNAME}(): Web files installed successfully."
694}
695
696# Configuración específica de Apache.
697function openGnsysInstallWebConsoleApacheConf()
698{
699        if [ $# -ne 2 ]; then
700                errorAndLog "${FUNCNAME}(): invalid number of parameters"
701                exit 1
702        fi
703
704        local path_opengnsys_base=$1
705        local path_apache2_confd=$2
706        local path_web_console=${path_opengnsys_base}/www
707
708        if [ ! -d $path_apache2_confd ]; then
709                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
710                return 1
711        fi
712
713        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
714
715        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
716
717        # genera configuración
718        cat > $path_opengnsys_base/etc/apache.conf <<EOF
719# OpenGnSys Web Console configuration for Apache
720
721Alias /opengnsys ${path_web_console}
722
723<Directory ${path_web_console}>
724        Options -Indexes FollowSymLinks
725        DirectoryIndex acceso.php
726</Directory>
727EOF
728
729        ln -fs $path_opengnsys_base/etc/apache.conf $path_apache2_confd/sites-available/opengnsys.conf
730        ln -fs $path_apache2_confd/sites-available/opengnsys.conf $path_apache2_confd/sites-enabled/opengnsys.conf
731        if [ $? -ne 0 ]; then
732                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
733                return 1
734        else
735                echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
736                /etc/init.d/apache2 restart
737                return 0
738        fi
739}
740
741# Crea la estructura base de la instalación de opengnsys
742function openGnsysInstallCreateDirs()
743{
744        if [ $# -ne 1 ]; then
745                errorAndLog "${FUNCNAME}(): invalid number of parameters"
746                exit 1
747        fi
748
749        local path_opengnsys_base=$1
750
751        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
752
753        mkdir -p $path_opengnsys_base
754        mkdir -p $path_opengnsys_base/admin/{autoexec,comandos,menus,usuarios}
755        mkdir -p $path_opengnsys_base/bin
756        mkdir -p $path_opengnsys_base/client
757        mkdir -p $path_opengnsys_base/doc
758        mkdir -p $path_opengnsys_base/etc
759        mkdir -p $path_opengnsys_base/lib
760        mkdir -p $path_opengnsys_base/log/clients
761        mkdir -p $path_opengnsys_base/sbin
762        mkdir -p $path_opengnsys_base/www
763        mkdir -p $path_opengnsys_base/images
764        ln -fs /var/lib/tftpboot $path_opengnsys_base
765        ln -fs $path_opengnsys_base/log /var/log/opengnsys
766
767        if [ $? -ne 0 ]; then
768                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
769                return 1
770        fi
771
772        echoAndLog "${FUNCNAME}(): directory paths created"
773        return 0
774}
775
776# Copia ficheros de configuración y ejecutables genéricos del servidor.
777function openGnsysCopyServerFiles () {
778        if [ $# -ne 1 ]; then
779                errorAndLog "${FUNCNAME}(): invalid number of parameters"
780                exit 1
781        fi
782
783        local path_opengnsys_base=$1
784
785        local SOURCES=( client/boot/initrd-generator \
786                        client/boot/upgrade-clients-udeb.sh \
787                        client/boot/udeblist.conf  \
788                        client/boot/udeblist-jaunty.conf  \
789                        client/boot/udeblist-karmic.conf \
790                        server/PXE/pxelinux.cfg/default \
791                        doc )
792        local TARGETS=( bin/initrd-generator \
793                        bin/upgrade-clients-udeb.sh \
794                        etc/udeblist.conf \
795                        etc/udeblist-jaunty.conf  \
796                        etc/udeblist-karmic.conf \
797                        tftpboot/pxelinux.cfg/default \
798                        doc )
799
800        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
801                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
802                exit 1
803        fi
804
805        echoAndLog "${FUNCNAME}(): copying files to server directories"
806
807        [ $USESVN -eq 1 ] && pushd $WORKDIR/opengnsys
808        local i
809        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
810                if [ -f "${SOURCES[$i]}" ]; then
811                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
812                        cp -p "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
813                fi
814                if [ -d "${SOURCES[$i]}" ]; then
815                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
816                        cp -ar "${SOURCES[$i]}/*" "${path_opengnsys_base}/${TARGETS[$i]}"
817                fi
818        done
819        popd
820}
821
822####################################################################
823### Funciones de compilación de códifo fuente de servicios
824####################################################################
825
826# Compilar los servicios de OpenGNsys
827function servicesCompilation ()
828{
829        local hayErrores=0
830
831        # Compilar OpenGnSys Server
832        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Server"
833        pushd $WORKDIR/opengnsys/admin/Services/ogAdmServer
834        make && make install
835        if [ $? -ne 0 ]; then
836                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
837                hayErrores=1
838        fi
839        popd
840        # Compilar OpenGnSys Repository Manager
841        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Repository Manager"
842        pushd $WORKDIR/opengnsys/admin/Services/ogAdmRepo
843        make && make install
844        if [ $? -ne 0 ]; then
845                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
846                hayErrores=1
847        fi
848        popd
849        # Compilar OpenGnSys Client
850        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Client"
851        pushd $WORKDIR/opengnsys/admin/Services/ogAdmClient
852        make && mv ogAdmClient ../../../client/nfsexport/bin
853        if [ $? -ne 0 ]; then
854                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Client"
855                hayErrores=1
856        fi
857        popd
858
859        return $hayErrores
860}
861
862
863####################################################################
864### Funciones instalacion cliente opengnsys
865####################################################################
866
867function openGnsysClientCreate()
868{
869        local OSDISTRIB OSCODENAME
870
871        local hayErrores=0
872
873        echoAndLog "${FUNCNAME}(): Copying OpenGnSys Client files."
874        cp -ar $WORKDIR/opengnsys/client/nfsexport/* $INSTALL_TARGET/client
875        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
876        echoAndLog "${FUNCNAME}(): Copying OpenGnSys Cloning Engine files."
877        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
878        cp -ar $WORKDIR/opengnsys/client/engine/*.lib $INSTALL_TARGET/client/lib/engine/bin
879        if [ $? -ne 0 ]; then
880                errorAndLog "${FUNCNAME}(): error while copying engine files"
881                hayErrores=1
882        fi
883
884        # Cargar Kernel, Initrd y paquetes udeb para la distribución del servidor (o por defecto).
885        OSDISTRIB=$(lsb_release -i | awk -F: '{sub(/\t/,""); print $2}') 2>/dev/null
886        OSCODENAME=$(lsb_release -c | awk -F: '{sub(/\t/,""); print $2}') 2>/dev/null
887        if [ "$OSDISTRIB" = "Ubuntu" -a -n "$OSCODENAME" ]; then
888                echoAndLog "${FUNCNAME}(): Loading Kernel and Initrd files for $OSDISTRIB $OSCODENAME."
889                $INSTALL_TARGET/bin/initrd-generator -t $INSTALL_TARGET/tftpboot -v "$OSCODENAME"
890                if [ $? -ne 0 ]; then
891                        errorAndLog "${FUNCNAME}(): error while generating initrd OpenGnSys Admin Client"
892                        hayErrores=1
893                fi
894                echoAndLog "${FUNCNAME}(): Loading udeb files for $OSDISTRIB $OSCODENAME."
895                $INSTALL_TARGET/bin/upgrade-clients-udeb.sh "$OSCODENAME"
896                if [ $? -ne 0 ]; then
897                        errorAndLog "${FUNCNAME}(): error while upgrading udeb files OpenGnSys Admin Client"
898                        hayErrores=1
899                fi
900        else
901                echoAndLog "${FUNCNAME}(): Loading default Kernel and Initrd files."
902                $INSTALL_TARGET/bin/initrd-generator -t $INSTALL_TARGET/tftpboot/
903                if [ $? -ne 0 ]; then
904                        errorAndLog "${FUNCNAME}(): error while generating initrd OpenGnSys Admin Client"
905                        hayErrores=1
906                fi
907                echoAndLog "${FUNCNAME}(): Loading default udeb files."
908                $INSTALL_TARGET/bin/upgrade-clients-udeb.sh
909                if [ $? -ne 0 ]; then
910                        errorAndLog "${FUNCNAME}(): error while upgrading udeb files OpenGnSys Admin Client"
911                        hayErrores=1
912                fi
913        fi
914
915        if [ $hayErrores -eq 0 ]; then
916                echoAndLog "${FUNCNAME}(): Client generation success."
917        else
918                errorAndLog "${FUNCNAME}(): Client generation with errors"
919        fi
920
921        return $hayErrores
922}
923
924
925# Configuración básica de servicios de OpenGnSys
926function openGnsysConfigure()
927{
928        echoAndLog "openGnsysConfigure(): Copying init files."
929        cp -p $WORKDIR/opengnsys/admin/Services/opengnsys.init /etc/init.d/opengnsys
930        cp -p $WORKDIR/opengnsys/admin/Services/opengnsys.default /etc/default/opengnsys
931        update-rc.d opengnsys defaults
932        echoAndLog "openGnsysConfigure(): Creating OpenGnSys config file in \"$INSTALL_TARGET/etc\"."
933        perl -pi -e "s/SERVERIP/$SERVERIP/g" $INSTALL_TARGET/etc/ogAdmServer.cfg
934        perl -pi -e "s/SERVERIP/$SERVERIP/g" $INSTALL_TARGET/etc/ogAdmRepo.cfg
935        echoAndLog "${FUNCNAME}(): Creating Web Console config file"
936        OPENGNSYS_CONSOLEURL="http://$SERVERIP/opengnsys"
937        perl -pi -e "s/SERVERIP/$SERVERIP/g; s/OPENGNSYSURL/${OPENGNSYS_CONSOLEURL//\//\\/}/g" $INSTALL_TARGET/www/controlacceso.php
938        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/OPENGNSYSURL/${OPENGNSYS_CONSOLEURL//\//\\/}/g" $WORKDIR/opengnsys/admin/Services/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient.cfg
939        echoAndLog "openGnsysConfiguration(): Starting OpenGnSys services."
940        /etc/init.d/opengnsys start
941}
942
943
944#####################################################################
945#######  Función de resumen informativo de la instalación
946#####################################################################
947
948function installationSummary(){
949        echo
950        echoAndLog "OpenGnSys Installation Summary"
951        echo       "=============================="
952        echoAndLog "Project version:                  $(cat $INSTALL_TARGET/doc/VERSION.txt)" 2>/dev/null
953        echoAndLog "Installation directory:           $INSTALL_TARGET"
954        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
955        echoAndLog "TFTP configuracion directory:     /var/lib/tftpboot"
956        echoAndLog "DHCP configuracion file:          /etc/dhcp3/dhcpd.conf"
957        echoAndLog "NFS configuracion file:           /etc/exports"
958        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
959        echoAndLog "Web Console admin user:           $OPENGNSYS_DB_USER"
960        echoAndLog "Web Console admin password:       $OPENGNSYS_DB_PASSWD"
961        echoAndLog "Web Console default user:         $OPENGNSYS_DB_DEFAULTUSER"
962        echoAndLog "Web Console default password:     $OPENGNSYS_DB_DEFAULTPASSWD"
963        echo
964        echoAndLog "Post-Installation Instructions:"
965        echo       "==============================="
966        echoAndLog "Review or edit all configuration files."
967        echoAndLog "Insert DHCP configuration data and restart service."
968        echoAndLog "Log-in as Web Console admin user."
969        echoAndLog " - Review default Organization data and default user."
970        echoAndLog "Log-in as Web Console organization user."
971        echoAndLog " - Insert OpenGnSys data (rooms, computers, etc)."
972echo
973}
974
975
976
977#####################################################################
978####### Proceso de instalación de OpenGnSys
979#####################################################################
980
981
982echoAndLog "OpenGnSys installation begins at $(date)"
983
984# Detectar parámetros de red por defecto
985getNetworkSettings
986if [ $? -ne 0 ]; then
987        errorAndLog "Error reading default network settings."
988        exit 1
989fi
990
991# Actualizar repositorios
992apt-get update
993
994# Instalación de dependencias (paquetes de sistema operativo).
995declare -a notinstalled
996checkDependencies DEPENDENCIES notinstalled
997if [ $? -ne 0 ]; then
998        installDependencies notinstalled
999        if [ $? -ne 0 ]; then
1000                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1001                exit 1
1002        fi
1003fi
1004
1005# Arbol de directorios de OpenGnSys.
1006openGnsysInstallCreateDirs ${INSTALL_TARGET}
1007if [ $? -ne 0 ]; then
1008        errorAndLog "Error while creating directory paths!"
1009        exit 1
1010fi
1011
1012# Si es necesario, descarga el repositorio de código en directorio temporal
1013if [ $USESVN -eq 1 ]; then
1014        svnExportCode $SVN_URL
1015        if [ $? -ne 0 ]; then
1016                errorAndLog "Error while getting code from svn"
1017                exit 1
1018        fi
1019else
1020        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1021fi
1022
1023# Compilar código fuente de los servicios de OpenGnSys.
1024servicesCompilation
1025if [ $? -ne 0 ]; then
1026        errorAndLog "Error while compiling OpenGnsys services"
1027        exit 1
1028fi
1029
1030# Configurando tftp
1031tftpConfigure
1032
1033# Configuración NFS
1034nfsConfigure
1035if [ $? -ne 0 ]; then
1036        errorAndLog "Error while configuring nfs server!"
1037        exit 1
1038fi
1039
1040# Configuración ejemplo DHCP
1041dhcpConfigure
1042if [ $? -ne 0 ]; then
1043        errorAndLog "Error while copying your dhcp server files!"
1044        exit 1
1045fi
1046
1047# Copiar ficheros de servicios OpenGnSys Server.
1048openGnsysCopyServerFiles ${INSTALL_TARGET}
1049if [ $? -ne 0 ]; then
1050        errorAndLog "Error while copying the server files!"
1051        exit 1
1052fi
1053
1054# Instalar Base de datos de OpenGnSys Admin.
1055isInArray notinstalled "mysql-server"
1056if [ $? -eq 0 ]; then
1057        mysqlSetRootPassword ${MYSQL_ROOT_PASSWORD}
1058else
1059        mysqlGetRootPassword
1060
1061fi
1062
1063mysqlTestConnection ${MYSQL_ROOT_PASSWORD}
1064if [ $? -ne 0 ]; then
1065        errorAndLog "Error while connection to mysql"
1066        exit 1
1067fi
1068mysqlDbExists ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1069if [ $? -ne 0 ]; then
1070        echoAndLog "Creating Web Console database"
1071        mysqlCreateDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1072        if [ $? -ne 0 ]; then
1073                errorAndLog "Error while creating Web Console database"
1074                exit 1
1075        fi
1076else
1077        echoAndLog "Web Console database exists, ommiting creation"
1078fi
1079
1080mysqlCheckUserExists ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DB_USER}
1081if [ $? -ne 0 ]; then
1082        echoAndLog "Creating user in database"
1083        mysqlCreateAdminUserToDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
1084        if [ $? -ne 0 ]; then
1085                errorAndLog "Error while creating database user"
1086                exit 1
1087        fi
1088
1089fi
1090
1091mysqlCheckDbIsEmpty ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1092if [ $? -eq 0 ]; then
1093        echoAndLog "Creating tables..."
1094        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
1095                mysqlImportSqlFileToDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
1096        else
1097                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
1098                exit 1
1099        fi
1100fi
1101
1102# copiando paqinas web
1103installWebFiles
1104
1105# creando configuracion de apache2
1106openGnsysInstallWebConsoleApacheConf $INSTALL_TARGET /etc/apache2
1107if [ $? -ne 0 ]; then
1108        errorAndLog "Error configuring Apache for OpenGnSYS Admin"
1109        exit 1
1110fi
1111
1112popd
1113
1114# Creando la estructura del cliente
1115openGnsysClientCreate
1116if [ $? -ne 0 ]; then
1117        errorAndLog "Error creating clients"
1118        exit 1
1119fi
1120
1121# Configuración de servicios de OpenGnSys
1122openGnsysConfigure
1123
1124# Mostrar sumario de la instalación e instrucciones de post-instalación.
1125installationSummary
1126
1127#rm -rf $WORKDIR
1128echoAndLog "OpenGnSys installation finished at $(date)"
1129
Note: See TracBrowser for help on using the repository browser.