source: installer/opengnsys_installer.sh @ 09a65ca

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 09a65ca was 4984660, checked in by alonso <alonso@…>, 15 years ago

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

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