source: ogLive-Builder-Git/includes/etc/initramfs-tools/scripts/ogfunctions

filebeat-installer
Last change on this file was 86a5c81, checked in by lgromero <lgromero@…>, 5 days ago

refs #1719 adds filebeat installation and includes filebeat configuration and certs

  • Property mode set to 100644
File size: 25.4 KB
Line 
1#/**
2#@file    ogfunctions.lib
3#@brief   Librería o clase para la gestion del sistema operativo de los clientes OpenGnsys.
4#@class   client
5#@version 1.1.0
6#@warning License: GNU GPLv3+
7#*/ ##
8
9
10#/**
11#         ogGetNetworkDevice
12#@brief   Devuelve el nombre de dispositivo de red correpondiente al índice indicado.
13#@param   int_devindex   índice de dispositivo de red.
14#@return  str_devname    nombre de dispositivo de red.
15#@note    Índice 0 debe corresponder a interfaz "lo" y a partir de 1 para las reales.
16#@version 1.1.0 - Primera versión de la función.
17#@author  Ramón Gómez, ETSII Universidad de Sevilla
18#@date    2016/04/20
19#*/ ##
20ogGetNetworkDevice ()
21{
22# Mantener retrocompatibilidad con interfaces antiguas tipo eth.
23case "$1" in
24        eth0)   ind=1 ;;
25        eth1)   ind=2 ;;
26        eth2)   ind=3 ;;
27        *)      ind="$1" ;;
28esac
29# Buscar el dispositivo del índice.
30dev=""
31for f in /sys/class/net/*/uevent; do
32        source $f
33        let aux=$IFINDEX-1
34        [ "$ind" = "$INTERFACE" -o "$ind" = $aux ] && dev="$INTERFACE"
35done
36[ -n "$dev" ] && echo "$dev"
37}
38
39
40#/**
41#         ogExportKernelParameters
42#@brief   Exporta los parametros pasados al kernel
43#@exception OG_ERR_FORMAT    Formato incorrecto.
44#@version 0.7 - Primera versión de la función.
45#@author  Antonio J. Doblas. Universidad de Malaga.
46#@date    2010/05/24
47#@version 1.1.0 - Sustituir índice de interfaz de red por su dispositivo.
48#@author  Ramón Gómez, ETSII Universidad de Sevilla
49#@date    2016/04/20
50#*/ ##
51ogExportKernelParameters ()
52{
53        GLOBAL="cat /proc/cmdline"
54        for i in `${GLOBAL}`
55        do
56                echo $i | grep "=" > /dev/null && export $i
57        done
58        # Sustituir índice de interfaz de red por su dispositivo.
59        DEVIND=$(echo "$ip" | cut -f6 -d:)
60        if [ -n "$DEVIND" ]; then
61                PRE=$(echo "$ip" | cut -f1-5 -d:)
62                POST=$(echo "$ip" | cut -f7- -d:)
63                DEVICE=$(ogGetNetworkDevice $DEVIND)
64                [ -n "$DEVICE" ] && export ip="$PRE:$DEVICE:${POST:-none}"
65        fi
66        return 0
67}
68
69
70#/**
71#         ogChangeVideoResolution
72#@brief   Cambia la resolución de vídeo utilizando el parámetro "video" del Kernel
73#         (sustituye al parámetro "vga").
74#@note    Formato del parámetro vídeo:    video=DRIVER:RESXxRESY-BITS
75#@note    El valor por defecto es:        video=uvesafb:640x480-16
76#@todo    Control de errores en el foramto de la variable "video".
77#@version 1.0.5 - Primera versión de la función.
78#@author  Ramón Gómez, ETSII Universidad de Sevilla
79#@date    2013/02/18
80#*/ ##
81ogChangeVideoResolution ()
82{
83# Variables locales.
84local DRIVER MODE
85# Mostrar resolución y driver por defecto si solo hay una opción disponible.
86if [ $(grep -c "" /sys/class/graphics/fb0/modes) -eq 1 ]; then
87        echo "Default screen mode: $(cat /sys/class/graphics/fb0/modes),$(cat /sys/class/graphics/fb0/bits_per_pixel)bpp$(lsmod|awk '$1=="video" && $3>0 {printf " (%s)",$4}')."
88else
89        # Obtener driver y resolución.
90        DRIVER="$(echo $video|cut -f1 -d:)"
91        MODE="$(echo $video|cut -f2 -d:)"
92        case "$DRIVER" in
93                # Cambiar resolución para driver "uvesafb".
94                uvesafb)
95                        # Obtener modo por defecto si parámetro "video=uvesafb:D".
96                        [ "$MODE" == "D" ] && MODE=$(awk -F: '$1=="D" {print $2; nextfile}' /sys/class/graphics/fb0/modes)
97                        # Cambiar resolución según valor del parámetro "video".
98                        grep ":$(echo ${MODE/p/}|cut -f1 -d-)p" /sys/class/graphics/fb0/modes | head -1 > /sys/class/graphics/fb0/mode 2>&1
99                        echo "$(echo $MODE|cut -f2 -d-)" > /sys/class/graphics/fb0/bits_per_pixel 2>&1
100                        echo "Screen mode: $(cat /sys/class/graphics/fb0/mode),$(cat /sys/class/graphics/fb0/bits_per_pixel)bpp."
101                        ;;
102                # Resolución por defecto para el resto de casos.
103                *)      echo "Unknown video driver, using default mode."
104                        ;;
105        esac
106fi
107}
108
109
110#/**
111#       ogExportVarEnvironment
112#@brief   Exporta las variables usadas en el proceso de inicio OpenGnsys y las almacena en /tmp
113#@param   
114#@return 
115#@exception OG_ERR_FORMAT    Formato incorrecto.
116#@version 0.9
117#@author Antonio J. Doblas. Universidad de Malaga.
118#@date    2011/05/24
119#*/ ##
120ogExportVarEnvironment ()
121{
122        export CFGINITRD="/tmp/initrd.cfg"     
123        OGPROTOCOL="${ogprotocol:-smb}"
124        [ "$ogunit" != "" ] && OGUNIT="/$ogunit"
125        # OPTIONS Para samba y local (a nfs no le afecta)
126        export OPTIONS=" -o user=opengnsys,pass=og"
127        DEFOGLIVE="ogclient"
128        export OGLIVEDIR="${oglivedir:-$DEFOGLIVE}" && echo "OGLIVEDIR=$OGLIVEDIR" >> $CFGINITRD
129        case "$OGPROTOCOL" in
130                nfs|NFS)                       
131                        export SRCOGLIVE="/var/lib/tftpboot" && echo "SRCOGLIVE=$SRCOGLIVE" >> $CFGINITRD       
132                        export SRCOGSHARE="/opt/opengnsys/client" && echo "SRCOGSHARE=$SRCOGSHARE" >> $CFGINITRD
133                        export SRCOGLOG="/opt/opengnsys/log/clients" && echo "SRCOGLOG=$SRCOGLOG" >> $CFGINITRD
134                        export SRCOGIMAGES="/opt/opengnsys/images$OGUNIT" && echo "SRCOGIMAGES=$SRCOGIMAGES" >> $CFGINITRD     
135                ;;
136                smb|SMB|cifs|CIFS|samba|SAMBA)
137                        export SRCOGLIVE="tftpboot"  && echo "SRCOGLIVE=$SRCOGLIVE" >> $CFGINITRD
138                        export SRCOGSHARE="ogclient" && echo "SRCOGSHARE=$SRCOGSHARE" >> $CFGINITRD
139                        export SRCOGLOG="oglog" && echo "SRCOGLOG=$SRCOGLOG" >> $CFGINITRD     
140                        export SRCOGIMAGES="ogimages$OGUNIT" && echo "SRCOGIMAGES=$SRCOGIMAGES" >> $CFGINITRD
141                ;;
142                local|LOCAL)
143                        # Ponemos variables SRC compatibles con smb y nfs.
144                        export SRCOGLIVE="local"
145                        export SRCOGSHARE="client" && echo "SRCOGSHARE=$SRCOGSHARE" >> $CFGINITRD
146                        export SRCOGLOG="log" && echo "SRCOGLOG=$SRCOGLOG" >> $CFGINITRD
147                        export SRCOGIMAGES="images" && echo "SRCOGIMAGES=$SRCOGIMAGES" >> $CFGINITRD
148                ;;
149        esac
150        #punto de acceso al boot-tools live
151        export DSTOGLIVE="/opt/oglive/tftpboot"
152        #punto de montaje para unionfs
153        export OGLIVERAMFS="/opt/oglive/ramfs" && echo "OGLIVERAMFS=$OGLIVERAMFS" >> $CFGINITRD
154        #punto de montaje donde se accede al 2nd FS mediante loop
155        export OGLIVEROOTFS="/opt/oglive/rootfs" && echo "OGLIVEROOTFS=$OGLIVEROOTFS" >> $CFGINITRD
156        #punto de union entre LOCALROOTIMG y LOCALROOTRAM
157        export OGLIVEUNIONFS="/opt/oglive/unionfs" && echo "OGLIVEUNIONFS=$OGLIVEUNIONFS" >> $CFGINITRD
158        #etiquta para los dispositivos offline
159        export OGLIVELABEL="ogClient"
160       
161        #echo "puntos de montajes para los demas accesos"
162        #echo "acceso al client, engine, scritps, interfaz"
163        export DSTOGSHARE="/opt/opengnsys" && echo "DSTOGSHARE=$DSTOGSHARE" >> $CFGINITRD               
164        export DSTOGLOG="/opt/opengnsys/log" && echo "DSTOGLOG=$DSTOGLOG" >> $CFGINITRD
165        export DSTOGIMAGES="/opt/opengnsys/images" && echo "DSTOGIMAGES=$DSTOGIMAGES" >> $CFGINITRD
166               
167        ##INFORMACION DE OTRAS VARIABLES OBTENDIAS EN OTRAS FUNCIONES ogConfigureNetwork.
168                #DEVICE
169                #IPV4DDR
170                #IPV4BROADCAST
171                #IPV4NETMASK
172                #IPV4GATEWAY
173                #HOSTNAME
174    #INFORMACION de otras variasbles obteneidas desde ogGetROOTSERVER
175                #ROOTSERVER  si ip=dhcp -> ROOTSERVER=NEXT-SERVER; si ip=host:rootserver:gw:mask:hostname:interfaz -> ROOTSERVER=rootserver
176                #BOOTIF -> si el gestor remoto es pxelinux.0 y se añade una linea más tipo "IPAPPEND 2" esta variable tendrá la mac de la interfaz.
177                #$OGSERVERLIVE
178                #$OGSERVERSHARE
179                #$OGSERVERLOG
180                #$OGSERVERIMAGES
181        return 0
182}
183
184
185#/**
186#       ogConfigureRamfs
187#@brief   Configura el initrd para adaptarlo al sistema raiz.
188#@param   
189#@return 
190#@exception OG_ERR_FORMAT    Formato incorrecto.
191#@version 0.9
192#@author Antonio J. Doblas. Universidad de Malaga.
193#@date    2010/05/24
194#*/ ##
195ogConfigureRamfs ()
196{
197        mkdir -p $DSTOGLIVE     
198        mkdir -p $OGLIVERAMFS   
199        mkdir -p $OGLIVEROOTFS                           
200        mkdir -p $OGLIVEUNIONFS
201
202        touch /etc/fstab
203}
204
205
206#/**
207#       ogLoadNetModule
208#@brief   Carga en un demerminado modulo de red, requiere compilación previo del modulo
209#@param   
210#@return 
211#@exception OG_ERR_FORMAT    Formato incorrecto.
212#@version 0.9
213#@author Antonio J. Doblas. Universidad de Malaga.
214#@date    2010/05/24
215#*/ ##
216ogLoadNetModule ()
217{
218        if [ -n "$ognetmodule" ]
219        then
220                echo "Cargando modulo de red $ognetmodule"
221                modprobe ${ognetmodule}
222        fi
223}
224
225
226#/**
227#      ogPostConfigureFS
228#@brief   Configura el sistema raiz, para independizarlo entre los clientes.
229#@param   
230#@return 
231#@exception OG_ERR_FORMAT    Formato incorrecto.
232#@version 0.9
233#@author Antonio J. Doblas. Universidad de Malaga.
234#@date    2010/05/24
235#*/ ##
236ogPostConfigureFS()
237{
238        # configuramos el /etc/hostname.
239        echo $HOSTNAME > /etc/hostname
240       
241        #configuramos el /etc/hosts
242        echo "127.0.0.1 localhost" > /etc/hosts
243        echo "$IPV4ADDR $HOSTNAME" >> /etc/hosts
244        echo "${OGSERVERLOG} oglog-os.mytld" >> /etc/hosts
245       
246        #configuramos el host.conf
247        echo "order hosts,bind" > /etc/host.conf
248        echo "multi on" >> /etc/host.conf
249       
250        #configuramos el dns anterior ubuntu 12.04 (parámetro del Kernel "ogdns=IP_DNS")
251        if [ -n "$ogdns" ]; then
252                mkdir -p /run/resolvconf
253                echo "nameserver $ogdns" > /run/resolvconf/resolv.conf
254        fi
255       
256        #configuramos el uso del servicio http proxy (parámetro del Kernel "ogproxy=URL_Proxy")
257        if [ -n "${ogproxy}" ]; then
258                export http_proxy="$ogproxy"
259                export https_proxy="$ogproxy"
260                export ftp_proxy="$ogproxy"
261                export ftps_proxy="$ogproxy"   
262        fi     
263       
264        # configuramos el /etc/networks
265        #read -e NETIP NETDEFAULT <<<$(route -n | grep eth0 | awk -F" " '{print $1}')
266        NETIP=$(route -n | grep eth0 | awk -F" " '{print $1}') && NETIP=$(echo $NETIP | cut -f1 -d" ")
267        echo "default 0.0.0.0" > /etc/networks
268        echo "loopback 127.0.0.0" >> /etc/networks
269        echo "link-local 169.254.0.0" >> /etc/networks
270        echo "localnet $NETIP" >> /etc/networks
271        #route
272
273        #echo "ogLive1.0.2" > /etc/debian_chroot
274
275        #enlace si iniciamos desde ogprotocolo=local { cdrom, usb, cache } .
276        # monta el raiz del dispositivo local en /opt/og2fs/tftpboot  - acceso al fichero .sqfs
277        # y monta el sistema root sqfs en /opt/og2fs/2ndfs
278        #[ "$LOCALMEDIA" == "CACHE" ] && ln -s $DSTOGLIVE /opt/opengnsys/cache
279        #[ "$ogprotocol" == "local" ] &&  ln -s ${OGLIVEROOTFS}/opt/opengnsys/* /opt/opengnsys/
280        if [ "$ogprotocol" == "local" ]; then
281           # Creamos los subdirectorios de /opt/opengnsys/
282           [ "$ogstatus" == "offline" ] && ln -s ${OGLIVEROOTFS}/opt/opengnsys/* /opt/opengnsys/
283           # Montamos CACHE
284           # Si existe particion identificada como CACHE se monta.
285           DEVICECACHE=$(blkid -L "CACHE")
286           if [ "$DEVICECACHE" != "" ]; then
287                # Se monta diferente segun el dispositivo de cache igual o no al de ogclient.
288                DEVICEOGLIVE=$(df |grep $DSTOGLIVE|awk '{print $1}')
289                if [[ "$DEVICECACHE" == "*$DEVICEOGLIVE*" ]];then
290                   mount --bind $DSTOGLIVE /opt/opengnsys/cache
291                else
292                   mount $DEVICECACHE /opt/opengnsys/cache
293                fi
294                if [ "$ogstatus" == "offline" ]; then
295                   [ -d /opt/opengnsys/cache/log ] || mkdir /opt/opengnsys/cache/log
296                   mount --bind /opt/opengnsys/cache/log /opt/opengnsys/log
297                fi
298           fi
299           # Montamos REPO
300           if [ "$ogstatus" == "offline" ]; then
301                # Si estatus distinto de online buscamos un dispositivo con etiqueta repo
302                # y si no existe montamos la cache como repo (si existe).
303                TYPE=$(blkid | grep REPO | awk -F"TYPE=" '{print $2}' | tr -d \")
304                if [ "$TYPE" == "" ]; then
305                   [ -d "/opt/opengnsys/cache$DSTOGIMAGES" ] && mount --bind  /opt/opengnsys/cache$DSTOGIMAGES $DSTOGIMAGES
306                else
307                   mount -t $TYPE LABEL=REPO $DSTOGIMAGES &>/dev/null
308                fi
309           fi
310        fi
311
312        #Montamos un directorio temporal para permitir instalacion de softare desde el comando apt-get (parametor kernel "ogtmpfs=50" valor en megas
313    ogtmpfs="${ogtmpfs:-15}"
314    mount tmpfs /var/cache/apt/archives -t tmpfs -o size=${ogtmpfs}M
315    mkdir -p /var/cache/apt/archives/partial
316}
317
318
319#/**
320#     ogGetROOTSERVER
321#@brief   Determina los puntos de accesos a los distintos recursos.
322#Requiere ogConfigureNetworking.
323#Exporta ROOTSERVER
324# si la red ha sido configurada con dhcp el valor de ROOTSERVER será el valor de next-server del dhcp
325# si la red ha sido configurada con el parametro de kernel ip, será el segundo valor.
326## ip=iphost:ipnext-server:ipgateway:netmask:hostname:iface:none
327## ip=172.17.36.21:62.36.225.150:172.17.36.254:255.255.255.0:prueba1:eth0:none
328#@param   
329#@return 
330#@exception OG_ERR_FORMAT    Formato incorrecto.
331#@version 0.9
332#@author Antonio J. Doblas. Universidad de Malaga.
333#@date    2010/05/24
334#*/ ##
335ogGetROOTSERVER ()
336{
337        # get nfs root from dhcp
338        if [ "x${NFSROOT}" = "xauto" ]; then
339                # check if server ip is part of dhcp root-path
340                if [ "${ROOTPATH#*:}" = "${ROOTPATH}" ]; then
341                        NFSROOT=${ROOTSERVER}:${ROOTPATH}
342                else
343                        NFSROOT=${ROOTPATH}
344                fi
345
346        # nfsroot=[<server-ip>:]<root-dir>[,<nfs-options>]
347        elif [ -n "${NFSROOT}" ]; then
348                # nfs options are an optional arg
349                if [ "${NFSROOT#*,}" != "${NFSROOT}" ]; then
350                        NFSOPTS="-o ${NFSROOT#*,}"
351                fi
352                NFSROOT=${NFSROOT%%,*}
353                if [ "${NFSROOT#*:}" = "$NFSROOT" ]; then
354                        NFSROOT=${ROOTSERVER}:${NFSROOT}
355                fi
356        fi
357        export ROOTSERVER
358        echo "ROOTSERVER=$ROOTSERVER" >> $CFGINITRD
359       
360        #si oglive no oglive=R
361        export OGSERVERIMAGES="${ogrepo:-$ROOTSERVER}" && echo "OGSERVERIMAGES=$OGSERVERIMAGES" >> $CFGINITRD
362        export OGSERVERSHARE="${ogshare:-$ROOTSERVER}" && echo "OGSERVERSHARE=$OGSERVERSHARE" >> $CFGINITRD
363        export OGSERVERLOG="${oglog:-$ROOTSERVER}" && echo "OGSERVERLOG=$OGSERVERLOG" >> $CFGINITRD
364        export OGSERVERLIVE="${oglive:-$OGSERVERIMAGES}" && echo "OGSERVERLIVE=$OGSERVERLIVE" >> $CFGINITRD
365               
366        return 0
367}
368
369
370
371#       ogUpdateInitrd
372#@brief   Actualiza el initrd de la cache desde el servidor. Si el arranque ha sido desde cache, comprueba desde el servidor nueva version del initird.
373#@param1
374#@return 
375#@exception OG_ERR_FORMAT    Formato incorrecto.
376#@version 0.9
377#@author Antonio J. Doblas. Universidad de Malaga.
378#@date    2011/05/24
379#@version 1.1.0 - Permite varios ogLive dentro de subdirectorios
380#@author Irina Gómez. ETSII Universidad de Sevilla
381#@date    2017/04/27
382#@version 1.1.0 - Se permite varios ogLives en la CACHE
383#@author Antonio J. Doblas Viso. Universidad de Malaga
384#@date    2017/05/31
385#*/ ##
386
387ogUpdateInitrd ()
388{
389        local OGLIVEDIR
390        OGLIVEDIR=${oglivedir:-"ogclient"}
391        cd /tmp
392        mkdir /tmp/cache
393        TYPE=$(blkid -po export $(blkid -L CACHE) 2>/dev/null | awk -F= '$1=="TYPE" { print $2}')
394        # Salir si no se detecta caché.
395        [ -z "$TYPE" ] && return
396        mount -t $TYPE LABEL=CACHE /tmp/cache || return
397        mkdir -p /tmp/cache/boot/$OGLIVEDIR
398       
399       
400        # comparamos los del server
401        busybox tftp -g -r $OGLIVEDIR/ogvmlinuz.sum $ROOTSERVER
402        busybox tftp -g -r $OGLIVEDIR/oginitrd.img.sum $ROOTSERVER
403        SERVERVMLINUZ=`cat ogvmlinuz.sum`
404        SERVERINITRD=`cat oginitrd.img.sum`
405
406       
407        #comparamos los de la cache
408        CACHEVMLINUZ=`cat /tmp/cache/boot/$OGLIVEDIR/ogvmlinuz.sum`
409        CACHEINITRD=`cat /tmp/cache/boot/$OGLIVEDIR/oginitrd.img.sum`
410       
411        echo "MD5 on SERVER: $SERVERVMLINUZ $SERVERINITRD"
412        echo "MD5 on  CACHE: $CACHEVMLINUZ $CACHEINITRD"
413       
414        cd /tmp/cache/boot/$OGLIVEDIR || mkdir -p /tmp/cache/boot/$OGLIVEDIR
415       
416        if [ "$CACHEVMLINUZ" != "$SERVERVMLINUZ" ]
417        then           
418                echo "ogvmlinuz updating"
419                busybox tftp -g -r $OGLIVEDIR/ogvmlinuz $ROOTSERVER
420                busybox tftp -g -r $OGLIVEDIR/ogvmlinuz.sum $ROOTSERVER
421                DOREBOOT=true
422        fi
423        if [ "$CACHEINITRD" != "$SERVERINITRD" ]
424        then
425                echo "oginitrd updating"
426                busybox tftp -g -r $OGLIVEDIR/oginitrd.img $ROOTSERVER
427                busybox tftp -g -r $OGLIVEDIR/oginitrd.img.sum $ROOTSERVER
428                DOREBOOT=true
429        fi
430
431        cd /; umount /tmp/cache
432
433        [ "$DOREBOOT" == "true" ] && reboot -f
434
435}
436
437#/**
438#       ogConnect
439#@brief   Conecta con los recursos necesarios para opengnsys
440#@param1 ip del servidor TODO:dns
441#@param2 protocolo
442#@param3 punto de acceso remoto
443#@param4  punto de montaje local
444#@param5 acceso de lectura tipo ",ro"
445#@return 
446#@exception OG_ERR_FORMAT    Formato incorrecto.
447#@version 0.9
448#@author Antonio J. Doblas. Universidad de Malaga.
449#@date    2011/05/24
450#*/ ##
451   
452ogConnect ()
453{
454        SERVER=$1
455        PROTOCOL=$2
456        SRC=$3
457        DST=$4
458        READONLY=$5
459       
460        case "$PROTOCOL" in
461                nfs)
462                        nfsmount  ${SERVER}:${SRC} ${DST} -o nolock${READONLY} 2> /dev/null || mount.nfs ${SERVER}:${SRC} ${DST} -o nolock${READONLY}
463                ;;
464                smb)
465                        mount.cifs //${SERVER}/${SRC} ${DST} ${OPTIONS}${READONLY}             
466                ;;
467                local)
468                   # Comprobamos que estatus sea online y que la variable del server no esta vacia.
469                   if [ "$ogstatus" != "offline" -a "$SERVER" != "" -a "$SRC" != "" ]; then
470                        # Comprobamos que existe un servicio de samba.
471                        smbclient -L $SERVER -N &>/dev/null
472                        if [ $? -eq 0 ]; then
473                           mount.cifs //${SERVER}/og${SRC} ${DST} ${OPTIONS}${READONLY}
474                        fi
475                        # TODO: buscar condicion para NFS
476                   fi
477                ;;
478                *)
479                        return 1
480                ;;
481        esac
482        return $?
483}
484
485
486#/**
487#       ogConnectOgLive
488#@brief   Conecta con el recurso para usar el sistema raiz externo, remoto o local
489#@param1
490#@return 
491#@exception OG_ERR_FORMAT    Formato incorrecto.
492#@version 0.9
493#@author Antonio J. Doblas. Universidad de Malaga.
494#@date    2011/05/24   
495ogConnectOgLive ()
496{
497# Si ogprotocol=local, la funcion ogExportVar => SRCOGLIVE=local
498        if [ "$SRCOGLIVE" == "local" ]
499        then           
500                echo  "Montar imagen del sistema root desde dispositivo local"
501                for i in $(blkid /dev/s* | grep $OGLIVELABEL  | awk -F: '{print $2}' | tr -d \"); do export $i; done
502                # si local usb| cd con partcion es identificada como label $OGLIVELABEL         
503                mount -t $TYPE LABEL=$OGLIVELABEL $DSTOGLIVE 
504                if [ $? != 0 ]
505                then
506                        # Si local es particion CACHE es identificada como CACHE
507                        mount LABEL=CACHE $DSTOGLIVE
508                        #export LOCALMEDIA=CACHE
509                fi
510        else
511                # Si ogprotocol es remoto.    TODO en smb rw y en nfs ro??
512                ogConnect $OGSERVERLIVE $OGPROTOCOL $SRCOGLIVE $DSTOGLIVE               
513        fi             
514# Si el montaje ha sido correcto, tanto en local como en remoto. Procedemos con la union
515        ogMergeLive
516}
517
518
519#/**
520#       ogMergeLive
521#@brief   Metafuncion para fusionar el initrd con el sistema raiz.
522#@param1
523#@return 
524#@exception OG_ERR_FORMAT    Formato incorrecto.
525#@version 0.9
526#@author Antonio J. Doblas. Universidad de Malaga.
527#@date    2011/05/24   
528ogMergeLive()
529{
530#Si existe en el punto de acceso del del oglive el fichero ogclient.sqfs       
531if [ ! -d $DSTOGLIVE/$OGLIVEDIR ]; then
532        echo "Usando ogLive por defecto."
533        export OGLIVEDIR=$DEFOGLIVE
534fi
535if [ -f $DSTOGLIVE/$OGLIVEDIR/ogclient.sqfs ]
536then   
537        cat /proc/mounts > /tmp/mtab.preunion
538        if [ "$og2nd" == "img" ]
539        then
540                #Montamos el ROOTFS tipo  img, para desarrolladores
541                #TODO: comprobar que se tiene acceso de escritura
542                losetup /dev/loop0 $DSTOGLIVE/$OGLIVEDIR/ogclient.img -o 32256
543                mount /dev/loop0 $OGLIVEROOTFS
544        else
545                ## Montamos el ROOTFS tipo squashfs
546                mount $DSTOGLIVE/$OGLIVEDIR/ogclient.sqfs $OGLIVEROOTFS -t squashfs -o loop
547        fi
548# Realizamos la union entre el ogliveram(initrd) y el ogliverootfs(ogclient.sqfs)       
549# Nota: el orden es muy importante para evitar errores de montaje.
550        [ -d $OGLIVEROOTFS/lib32 ] && LIBS=lib32
551        for i in bin sbin lib $LIBS etc var usr root boot; do
552                ogUnionLiveDir $i
553        done
554        [ -L /etc/mtab ] || cat /tmp/mtab.preunion > /etc/mtab
555else
556        echo "Fichero imagen del cliente no encontrado"
557        return 1
558fi
559}
560
561
562
563#/**
564#       ogUnionLiveDir
565#@brief  fusiona dos directorios con unionfs
566#@param1
567#@return 
568#@exception OG_ERR_FORMAT    Formato incorrecto.
569#@version 0.9
570#@author Antonio J. Doblas. Universidad de Malaga.
571#@date    2011/05/24
572ogUnionLiveDir()
573{
574        TMPDIR=/$1              #dir
575        FUSE_OPT="-o default_permissions -o allow_other -o use_ino -o nonempty -o suid"
576        UNION_OPT="-o cow -o noinitgroups"
577        UBIN="unionfs-fuse"
578
579        mkdir -p $OGLIVERAMFS$TMPDIR
580        U1STDIR="${OGLIVERAMFS}${TMPDIR}=RW"
581        U2NDDIR="${OGLIVEROOTFS}${TMPDIR}=RO"
582        UNIONDIR=${OGLIVEUNIONFS}${TMPDIR}
583        mkdir -p $UNIONDIR $TMPDIR
584        $UBIN $FUSE_OPT $UNION_OPT ${U1STDIR}:${U2NDDIR} $UNIONDIR
585        mount --bind  $UNIONDIR $TMPDIR
586}
587
588
589
590#/**
591#     ogConfigureLoopback
592#@brief   Configura la interfaz loopback para cliente torrent
593#@param   
594#@return 
595#@exception OG_ERR_FORMAT    Formato incorrecto.
596#@version 0.9   Usando funciones generales de ubuntu
597#@author Antonio J. Doblas. Universidad de Malaga.
598#@date    2010/05/24
599#@version 1.0.1   Deteccion automatica de interfaz con enlace activo.
600#@author Antonio J. Doblas. Universidad de Malaga.
601#@date    2011/05/24
602#*/ ##
603ogConfigureLoopback()
604{
605        # for the portmapper we need localhost
606        ifconfig lo 127.0.0.1
607        #/etc/init.d/portmap start
608}
609
610#/**
611#    ogConfigureNetworking
612#@brief   Configura la interfaz de red usada en el pxe
613#@param   
614#@return 
615#@exception OG_ERR_FORMAT    Formato incorrecto.
616#@version 0.9
617#@author Antonio J. Doblas. Universidad de Malaga.
618#@date    2010/05/24
619#*/ ##
620ogConfigureNetworking()
621{
622#echo "ogConfigureNetworking: Buscando interfaz a configurar DEVICE"
623if [ -n "${BOOTIF}" ]
624then
625        #echo " variable BOOTIF exportada con pxelinux.0 con valor $BOOTIF"
626        IP=$IPOPTS
627        temp_mac=${BOOTIF#*-}
628        # convert to typical mac address format by replacing "-" with ":"
629        bootif_mac=""
630        IFS='-'
631        for x in $temp_mac ; do
632                if [ -z "$bootif_mac" ]; then
633        bootif_mac="$x"
634        else
635                bootif_mac="$x:$bootif_mac"
636        fi
637        done
638        unset IFS
639        # look for devices with matching mac address, and set DEVICE to
640        # appropriate value if match is found.
641        for device in /sys/class/net/* ; do
642                if [ -f "$device/address" ]; then
643                        current_mac=$(cat "$device/address")
644                        if [ "$bootif_mac" = "$current_mac" ]; then
645                                DEVICE=${device##*/}
646                                break
647                        fi
648                fi
649        done
650else
651        #echo "variable BOOTIF no exportada, intentamos detectar que interfaz se ha iniciado"
652        IP=$ip
653        #TODO Detectar que interfaz se ha iniciado
654        case "$IP" in
655                none|off)
656                        return 0
657                        ;;
658                ""|on|any)
659                        # Bring up device
660                        DEVICE=1
661                        ;;
662                dhcp|bootp|rarp|both)
663                        DEVICE=1
664                        ;;
665                *)
666                        DEVICE=`echo $IP | cut -f6 -d:`
667                        ;;
668        esac
669fi
670DEVICE=$(ogGetNetworkDevice $DEVICE)
671if [ -z "${DEVICE}" ]; then
672        echo "variable DEVICE con valor $DEVICE no encontrada, llamamos de nuevo a ogconfigure_networking"
673        ogConfigureNetworking
674fi
675
676[ -n "${DEVICE}" ] && [ -e /run/net-"${DEVICE}".conf ] && return 0
677#if [ -n "${DEVICE}" ] && [ -e /run/net-"${DEVICE}".conf ]; then
678#       echo "variable DEVICE con valor $DEVICE  y fichero /run/net-$DEVICE encontrados"
679#       return 0
680#else
681#       echo "variable DEVICE con valor $DEVICE encontrada, procedemos a configurala y a crear el fichero /run/net-$DEVICE"
682#fi
683
684# Activamos la interfaz antes de configurar.
685ip address flush $DEVICE
686ip link set dev $DEVICE up
687# Si no se detecta señal portadora volver a configurar.
688sleep 1
689CARRIER=$(cat /sys/class/net/${DEVICE}/carrier)
690if [ "$CARRIER" != "1" ]
691then
692        ogConfigureNetworking
693fi
694
695# support ip options see linux sources
696# Documentation/filesystems/nfsroot.txt
697# Documentation/frv/booting.txt
698for ROUNDTTT in 2 3 4 6 9 16 25 36 64 100; do
699        # The NIC is to be configured if this file does not exist.
700        # Ip-Config tries to create this file and when it succeds
701        # creating the file, ipconfig is not run again.
702        if [ -e /run/net-"${DEVICE}".conf ]; then
703                break;
704        fi
705        case "$IP" in
706                none|off)
707                        return 0
708                ;;
709                ""|on|any)
710                        # Bring up device
711                        echo "Setting $DEVICE  with option:on|any and Variable IP= $IP: ipconfig -t ${ROUNDTTT} ${DEVICE} "
712                        ipconfig -t ${ROUNDTTT} ${DEVICE}
713                ;;
714                dhcp|bootp|rarp|both)
715                        echo "Setting $DEVICE with option:dhcp|bootp|rarp|both and Variable IP=  $IP: ipconfig -t ${ROUNDTTT} -c ${IP} -d ${DEVICE} "
716                        ipconfig -t ${ROUNDTTT} -c ${IP} -d ${DEVICE}
717                ;;
718                *)
719                        echo "Setting $DEVICE with option *  and Variable IP= $IP: ipconfig -t ${ROUNDTTT} -d $IP  "
720                        ipconfig -t ${ROUNDTTT} -d $IP
721                        # grab device entry from ip option
722                        NEW_DEVICE=${IP#*:*:*:*:*:*}
723                        if [ "${NEW_DEVICE}" != "${IP}" ]; then
724                                NEW_DEVICE=${NEW_DEVICE%:*}
725                        else
726                                # wrong parse, possibly only a partial string
727                                NEW_DEVICE=
728                        fi
729                        if [ -n "${NEW_DEVICE}" ]; then
730                                DEVICE="${NEW_DEVICE}"
731                        fi
732                ;;
733        esac
734done
735
736# source ipconfig output
737if [ -n "${DEVICE}" ]; then     
738        export DEVICE
739        export DEVICECFG="/run/net-${DEVICE}.conf"
740        # En algunos casos, el fichero de configuración está en /tmp.
741        [ ! -f $DEVICECFG -a -f ${DEVICECFG/run/tmp} ] && mv ${DEVICECFG/run/tmp} $DEVICECFG
742        source $DEVICECFG
743        echo "DEVICE=$DEVICE" >> $CFGINITRD
744        echo "DEVICECFG=$DEVICECFG" >> $CFGINITRD
745        echo "exportando variable DEVICE con valor = $DEVICE y DEVICECFG con valor $DEVICECFG"
746        # Compatibilidad con versiones anteriores.
747        ln -fs $DEVICECFG /tmp
748else
749        # source any interface as not exaclty specified
750        source /run/net-*.conf
751fi
752}
753
754
755#/**
756#    ogYesNo
757#@brief   Gestion de peticiones de usuario en modo ogdebug=true
758#@param1  OPTIONS    --timeout N    --default ANSWER
759#@param1 Questions   
760#@return  1=yes 0=no
761#@exception OG_ERR_FORMAT    Formato incorrecto.
762#@version 0.9
763#@author: 
764#@date    2010/05/24
765#*/ ##
766ogYesNo()
767{
768    local ans
769    local ok=0
770    local timeout=0
771    local default
772    local t
773
774    while [[ "$1" ]]
775    do
776        case "$1" in
777        --default)
778            shift
779            default=$1
780            if [[ ! "$default" ]]; then error "Missing default value"; fi
781            t=$(echo $default | tr '[:upper:]' '[:lower:]')
782
783            if [[ "$t" != 'y'  &&  "$t" != 'yes'  &&  "$t" != 'n'  &&  "$t" != 'no' ]]; then
784                error "Illegal default answer: $default"
785            fi
786            default=$t
787            shift
788            ;;
789
790        --timeout)
791            shift
792            timeout=$1
793            if [[ ! "$timeout" ]]; then error "Missing timeout value"; fi
794            #if [[ ! "$timeout" =~ ^[0-9][0-9]*$ ]]; then error "Illegal timeout value: $timeout"; fi
795            shift
796            ;;
797
798        -*)
799            error "Unrecognized option: $1"
800            ;;
801
802        *)
803            break
804            ;;
805        esac
806    done
807
808    if [[ $timeout -ne 0  &&  ! "$default" ]]; then
809        error "Non-zero timeout requires a default answer"
810    fi
811
812    if [[ ! "$*" ]]; then error "Missing question"; fi
813
814    while [[ $ok -eq 0 ]]
815    do
816        if [[ $timeout -ne 0 ]]; then
817            if ! read -t $timeout -p "$*" ans; then
818                ans=$default
819            else
820                # Turn off timeout if answer entered.
821                timeout=0
822                if [[ ! "$ans" ]]; then ans=$default; fi
823            fi
824        else
825            read -p "$*" ans
826            if [[ ! "$ans" ]]; then
827                ans=$default
828            else
829                ans=$(echo $ans | tr '[:upper:]' '[:lower:]')
830            fi
831        fi
832
833        if [[ "$ans" == 'y'  ||  "$ans" == 'yes'  ||  "$ans" == 'n'  ||  "$ans" == 'no' ]]; then
834            ok=1
835        fi
836
837        if [[ $ok -eq 0 ]]; then warning "Valid answers are: yes y no n"; fi
838    done
839    [[ "$ans" = "y" || "$ans" == "yes" ]]
840}
841 
Note: See TracBrowser for help on using the repository browser.