source: installer/opengnsys_installer.sh @ bf1840e9

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

Instalador detecta correctamente dependencias no instaladas; mejora en rendimiento descarga de paquetes udeb.

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

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