source: installer/opengnsys_installer.sh @ 9f5f004

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 9f5f004 was 28c96b3, checked in by ramon <ramongomez@…>, 15 years ago

Usando Ubuntu 10.04 LTS Lucid como distribución por defecto; soporte básico para Ubuntu 10.10 Maverick.
Close #242

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

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