source: installer/opengnsys_installer.sh @ 13ccdf5

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 13ccdf5 was 13a01a7, checked in by lguillen <lguillen@…>, 16 years ago
  • Agregada funcion backupFile
  • Agregadas comprobaciones compilacion
  • Agregadas comprobaciones y funciones de configuración del nfs

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

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