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

filebeat-installermain
Last change on this file since 1ef837e was c1dc13e, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#917: Fixed bug when ogLive mounts a Samba share from a server based on Ubuntu 18.04

  • Property mode set to 100644
File size: 25.3 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       
245        #configuramos el host.conf
246        echo "order hosts,bind" > /etc/host.conf
247        echo "multi on" >> /etc/host.conf
248       
249        #configuramos el dns anterior ubuntu 12.04 (parámetro del Kernel "ogdns=IP_DNS")
250        if [ -n "$ogdns" ]; then
251                mkdir -p /run/resolvconf
252                echo "nameserver $ogdns" > /run/resolvconf/resolv.conf
253        fi
254       
255        #configuramos el uso del servicio http proxy (parámetro del Kernel "ogproxy=URL_Proxy")
256        if [ -n "${ogproxy}" ]; then
257                export http_proxy="$ogproxy"
258                export https_proxy="$ogproxy"
259                export ftp_proxy="$ogproxy"
260                export ftps_proxy="$ogproxy"   
261        fi     
262       
263        # configuramos el /etc/networks
264        #read -e NETIP NETDEFAULT <<<$(route -n | grep eth0 | awk -F" " '{print $1}')
265        NETIP=$(route -n | grep eth0 | awk -F" " '{print $1}') && NETIP=$(echo $NETIP | cut -f1 -d" ")
266        echo "default 0.0.0.0" > /etc/networks
267        echo "loopback 127.0.0.0" >> /etc/networks
268        echo "link-local 169.254.0.0" >> /etc/networks
269        echo "localnet $NETIP" >> /etc/networks
270        #route
271
272        #echo "ogLive1.0.2" > /etc/debian_chroot
273
274        #enlace si iniciamos desde ogprotocolo=local { cdrom, usb, cache } .
275        # monta el raiz del dispositivo local en /opt/og2fs/tftpboot  - acceso al fichero .sqfs
276        # y monta el sistema root sqfs en /opt/og2fs/2ndfs
277        #[ "$LOCALMEDIA" == "CACHE" ] && ln -s $DSTOGLIVE /opt/opengnsys/cache
278        #[ "$ogprotocol" == "local" ] &&  ln -s ${OGLIVEROOTFS}/opt/opengnsys/* /opt/opengnsys/
279        if [ "$ogprotocol" == "local" ]; then
280           # Creamos los subdirectorios de /opt/opengnsys/
281           [ "$ogstatus" == "offline" ] && ln -s ${OGLIVEROOTFS}/opt/opengnsys/* /opt/opengnsys/
282           # Montamos CACHE
283           # Si existe particion identificada como CACHE se monta.
284           DEVICECACHE=$(blkid -L "CACHE")
285           if [ "$DEVICECACHE" != "" ]; then
286                # Se monta diferente segun el dispositivo de cache igual o no al de ogclient.
287                DEVICEOGLIVE=$(df |grep $DSTOGLIVE|awk '{print $1}')
288                if [[ "$DEVICECACHE" == "*$DEVICEOGLIVE*" ]];then
289                   mount --bind $DSTOGLIVE /opt/opengnsys/cache
290                else
291                   mount $DEVICECACHE /opt/opengnsys/cache
292                fi
293                if [ "$ogstatus" == "offline" ]; then
294                   [ -d /opt/opengnsys/cache/log ] || mkdir /opt/opengnsys/cache/log
295                   mount --bind /opt/opengnsys/cache/log /opt/opengnsys/log
296                fi
297           fi
298           # Montamos REPO
299           if [ "$ogstatus" == "offline" ]; then
300                # Si estatus distinto de online buscamos un dispositivo con etiqueta repo
301                # y si no existe montamos la cache como repo (si existe).
302                TYPE=$(blkid | grep REPO | awk -F"TYPE=" '{print $2}' | tr -d \")
303                if [ "$TYPE" == "" ]; then
304                   [ -d "/opt/opengnsys/cache$DSTOGIMAGES" ] && mount --bind  /opt/opengnsys/cache$DSTOGIMAGES $DSTOGIMAGES
305                else
306                   mount -t $TYPE LABEL=REPO $DSTOGIMAGES &>/dev/null
307                fi
308           fi
309        fi
310
311        #Montamos un directorio temporal para permitir instalacion de softare desde el comando apt-get (parametor kernel "ogtmpfs=50" valor en megas
312    ogtmpfs="${ogtmpfs:-15}"
313    mount tmpfs /var/cache/apt/archives -t tmpfs -o size=${ogtmpfs}M
314    mkdir -p /var/cache/apt/archives/partial
315}
316
317
318#/**
319#     ogGetROOTSERVER
320#@brief   Determina los puntos de accesos a los distintos recursos.
321#Requiere ogConfigureNetworking.
322#Exporta ROOTSERVER
323# si la red ha sido configurada con dhcp el valor de ROOTSERVER será el valor de next-server del dhcp
324# si la red ha sido configurada con el parametro de kernel ip, será el segundo valor.
325## ip=iphost:ipnext-server:ipgateway:netmask:hostname:iface:none
326## ip=172.17.36.21:62.36.225.150:172.17.36.254:255.255.255.0:prueba1:eth0:none
327#@param   
328#@return 
329#@exception OG_ERR_FORMAT    Formato incorrecto.
330#@version 0.9
331#@author Antonio J. Doblas. Universidad de Malaga.
332#@date    2010/05/24
333#*/ ##
334ogGetROOTSERVER ()
335{
336        # get nfs root from dhcp
337        if [ "x${NFSROOT}" = "xauto" ]; then
338                # check if server ip is part of dhcp root-path
339                if [ "${ROOTPATH#*:}" = "${ROOTPATH}" ]; then
340                        NFSROOT=${ROOTSERVER}:${ROOTPATH}
341                else
342                        NFSROOT=${ROOTPATH}
343                fi
344
345        # nfsroot=[<server-ip>:]<root-dir>[,<nfs-options>]
346        elif [ -n "${NFSROOT}" ]; then
347                # nfs options are an optional arg
348                if [ "${NFSROOT#*,}" != "${NFSROOT}" ]; then
349                        NFSOPTS="-o ${NFSROOT#*,}"
350                fi
351                NFSROOT=${NFSROOT%%,*}
352                if [ "${NFSROOT#*:}" = "$NFSROOT" ]; then
353                        NFSROOT=${ROOTSERVER}:${NFSROOT}
354                fi
355        fi
356        export ROOTSERVER
357        echo "ROOTSERVER=$ROOTSERVER" >> $CFGINITRD
358       
359        #si oglive no oglive=R
360        export OGSERVERIMAGES="${ogrepo:-$ROOTSERVER}" && echo "OGSERVERIMAGES=$OGSERVERIMAGES" >> $CFGINITRD
361        export OGSERVERSHARE="${ogshare:-$ROOTSERVER}" && echo "OGSERVERSHARE=$OGSERVERSHARE" >> $CFGINITRD
362        export OGSERVERLOG="${oglog:-$ROOTSERVER}" && echo "OGSERVERLOG=$OGSERVERLOG" >> $CFGINITRD
363        export OGSERVERLIVE="${oglive:-$OGSERVERIMAGES}" && echo "OGSERVERLIVE=$OGSERVERLIVE" >> $CFGINITRD
364               
365        return 0
366}
367
368
369
370#       ogUpdateInitrd
371#@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.
372#@param1
373#@return 
374#@exception OG_ERR_FORMAT    Formato incorrecto.
375#@version 0.9
376#@author Antonio J. Doblas. Universidad de Malaga.
377#@date    2011/05/24
378#@version 1.1.0 - Permite varios ogLive dentro de subdirectorios
379#@author Irina Gómez. ETSII Universidad de Sevilla
380#@date    2017/04/27
381#@version 1.1.0 - Se permite varios ogLives en la CACHE
382#@author Antonio J. Doblas Viso. Universidad de Malaga
383#@date    2017/05/31
384#*/ ##
385
386ogUpdateInitrd ()
387{
388        local OGLIVEDIR
389        OGLIVEDIR=${oglivedir:-"ogclient"}
390        cd /tmp
391        mkdir /tmp/cache
392        TYPE=$(blkid -po export $(blkid -L CACHE) 2>/dev/null | awk -F= '$1=="TYPE" { print $2}')
393        # Salir si no se detecta caché.
394        [ -z "$TYPE" ] && return
395        mount -t $TYPE LABEL=CACHE /tmp/cache || return
396        mkdir -p /tmp/cache/boot/$OGLIVEDIR
397       
398       
399        # comparamos los del server
400        busybox tftp -g -r $OGLIVEDIR/ogvmlinuz.sum $ROOTSERVER
401        busybox tftp -g -r $OGLIVEDIR/oginitrd.img.sum $ROOTSERVER
402        SERVERVMLINUZ=`cat ogvmlinuz.sum`
403        SERVERINITRD=`cat oginitrd.img.sum`
404
405       
406        #comparamos los de la cache
407        CACHEVMLINUZ=`cat /tmp/cache/boot/$OGLIVEDIR/ogvmlinuz.sum`
408        CACHEINITRD=`cat /tmp/cache/boot/$OGLIVEDIR/oginitrd.img.sum`
409       
410        echo "MD5 on SERVER: $SERVERVMLINUZ $SERVERINITRD"
411        echo "MD5 on  CACHE: $CACHEVMLINUZ $CACHEINITRD"
412       
413        cd /tmp/cache/boot/$OGLIVEDIR || mkdir -p /tmp/cache/boot/$OGLIVEDIR
414       
415        if [ "$CACHEVMLINUZ" != "$SERVERVMLINUZ" ]
416        then           
417                echo "ogvmlinuz updating"
418                busybox tftp -g -r $OGLIVEDIR/ogvmlinuz $ROOTSERVER
419                busybox tftp -g -r $OGLIVEDIR/ogvmlinuz.sum $ROOTSERVER
420                DOREBOOT=true
421        fi
422        if [ "$CACHEINITRD" != "$SERVERINITRD" ]
423        then
424                echo "oginitrd updating"
425                busybox tftp -g -r $OGLIVEDIR/oginitrd.img $ROOTSERVER
426                busybox tftp -g -r $OGLIVEDIR/oginitrd.img.sum $ROOTSERVER
427                DOREBOOT=true
428        fi
429
430        cd /; umount /tmp/cache
431
432        [ "$DOREBOOT" == "true" ] && reboot -f
433
434}
435
436#/**
437#       ogConnect
438#@brief   Conecta con los recursos necesarios para opengnsys
439#@param1 ip del servidor TODO:dns
440#@param2 protocolo
441#@param3 punto de acceso remoto
442#@param4  punto de montaje local
443#@param5 acceso de lectura tipo ",ro"
444#@return 
445#@exception OG_ERR_FORMAT    Formato incorrecto.
446#@version 0.9
447#@author Antonio J. Doblas. Universidad de Malaga.
448#@date    2011/05/24
449#*/ ##
450   
451ogConnect ()
452{
453        SERVER=$1
454        PROTOCOL=$2
455        SRC=$3
456        DST=$4
457        READONLY=$5
458       
459        case "$PROTOCOL" in
460                nfs)
461                        nfsmount  ${SERVER}:${SRC} ${DST} -o nolock${READONLY} 2> /dev/null || mount.nfs ${SERVER}:${SRC} ${DST} -o nolock${READONLY}
462                ;;
463                smb)
464                        mount.cifs //${SERVER}/${SRC} ${DST} ${OPTIONS}${READONLY}             
465                ;;
466                local)
467                   # Comprobamos que estatus sea online y que la variable del server no esta vacia.
468                   if [ "$ogstatus" != "offline" -a "$SERVER" != "" -a "$SRC" != "" ]; then
469                        # Comprobamos que existe un servicio de samba.
470                        smbclient -L $SERVER -N &>/dev/null
471                        if [ $? -eq 0 ]; then
472                           mount.cifs //${SERVER}/og${SRC} ${DST} ${OPTIONS}${READONLY}
473                        fi
474                        # TODO: buscar condicion para NFS
475                   fi
476                ;;
477                *)
478                        return 1
479                ;;
480        esac
481        return $?
482}
483
484
485#/**
486#       ogConnectOgLive
487#@brief   Conecta con el recurso para usar el sistema raiz externo, remoto o local
488#@param1
489#@return 
490#@exception OG_ERR_FORMAT    Formato incorrecto.
491#@version 0.9
492#@author Antonio J. Doblas. Universidad de Malaga.
493#@date    2011/05/24   
494ogConnectOgLive ()
495{
496# Si ogprotocol=local, la funcion ogExportVar => SRCOGLIVE=local
497        if [ "$SRCOGLIVE" == "local" ]
498        then           
499                echo  "Montar imagen del sistema root desde dispositivo local"
500                for i in $(blkid /dev/s* | grep $OGLIVELABEL  | awk -F: '{print $2}' | tr -d \"); do export $i; done
501                # si local usb| cd con partcion es identificada como label $OGLIVELABEL         
502                mount -t $TYPE LABEL=$OGLIVELABEL $DSTOGLIVE 
503                if [ $? != 0 ]
504                then
505                        # Si local es particion CACHE es identificada como CACHE
506                        mount LABEL=CACHE $DSTOGLIVE
507                        #export LOCALMEDIA=CACHE
508                fi
509        else
510                # Si ogprotocol es remoto.    TODO en smb rw y en nfs ro??
511                ogConnect $OGSERVERLIVE $OGPROTOCOL $SRCOGLIVE $DSTOGLIVE               
512        fi             
513# Si el montaje ha sido correcto, tanto en local como en remoto. Procedemos con la union
514        ogMergeLive
515}
516
517
518#/**
519#       ogMergeLive
520#@brief   Metafuncion para fusionar el initrd con el sistema raiz.
521#@param1
522#@return 
523#@exception OG_ERR_FORMAT    Formato incorrecto.
524#@version 0.9
525#@author Antonio J. Doblas. Universidad de Malaga.
526#@date    2011/05/24   
527ogMergeLive()
528{
529#Si existe en el punto de acceso del del oglive el fichero ogclient.sqfs       
530if [ ! -d $DSTOGLIVE/$OGLIVEDIR ]; then
531        echo "Usando ogLive por defecto."
532        export OGLIVEDIR=$DEFOGLIVE
533fi
534if [ -f $DSTOGLIVE/$OGLIVEDIR/ogclient.sqfs ]
535then   
536        cat /proc/mounts > /tmp/mtab.preunion
537        if [ "$og2nd" == "img" ]
538        then
539                #Montamos el ROOTFS tipo  img, para desarrolladores
540                #TODO: comprobar que se tiene acceso de escritura
541                losetup /dev/loop0 $DSTOGLIVE/$OGLIVEDIR/ogclient.img -o 32256
542                mount /dev/loop0 $OGLIVEROOTFS
543        else
544                ## Montamos el ROOTFS tipo squashfs
545                mount $DSTOGLIVE/$OGLIVEDIR/ogclient.sqfs $OGLIVEROOTFS -t squashfs -o loop
546        fi
547# Realizamos la union entre el ogliveram(initrd) y el ogliverootfs(ogclient.sqfs)       
548# Nota: el orden es muy importante para evitar errores de montaje.
549        [ -d $OGLIVEROOTFS/lib32 ] && LIBS=lib32
550        for i in bin sbin lib $LIBS etc var usr root boot; do
551                ogUnionLiveDir $i
552        done
553        [ -L /etc/mtab ] || cat /tmp/mtab.preunion > /etc/mtab
554else
555        echo "Fichero imagen del cliente no encontrado"
556        return 1
557fi
558}
559
560
561
562#/**
563#       ogUnionLiveDir
564#@brief  fusiona dos directorios con unionfs
565#@param1
566#@return 
567#@exception OG_ERR_FORMAT    Formato incorrecto.
568#@version 0.9
569#@author Antonio J. Doblas. Universidad de Malaga.
570#@date    2011/05/24
571ogUnionLiveDir()
572{
573        TMPDIR=/$1              #dir
574        FUSE_OPT="-o default_permissions -o allow_other -o use_ino -o nonempty -o suid"
575        UNION_OPT="-o cow -o noinitgroups"
576        UBIN="unionfs-fuse"
577
578        mkdir -p $OGLIVERAMFS$TMPDIR
579        U1STDIR="${OGLIVERAMFS}${TMPDIR}=RW"
580        U2NDDIR="${OGLIVEROOTFS}${TMPDIR}=RO"
581        UNIONDIR=${OGLIVEUNIONFS}${TMPDIR}
582        mkdir -p $UNIONDIR $TMPDIR
583        $UBIN $FUSE_OPT $UNION_OPT ${U1STDIR}:${U2NDDIR} $UNIONDIR
584        mount --bind  $UNIONDIR $TMPDIR
585}
586
587
588
589#/**
590#     ogConfigureLoopback
591#@brief   Configura la interfaz loopback para cliente torrent
592#@param   
593#@return 
594#@exception OG_ERR_FORMAT    Formato incorrecto.
595#@version 0.9   Usando funciones generales de ubuntu
596#@author Antonio J. Doblas. Universidad de Malaga.
597#@date    2010/05/24
598#@version 1.0.1   Deteccion automatica de interfaz con enlace activo.
599#@author Antonio J. Doblas. Universidad de Malaga.
600#@date    2011/05/24
601#*/ ##
602ogConfigureLoopback()
603{
604        # for the portmapper we need localhost
605        ifconfig lo 127.0.0.1
606        #/etc/init.d/portmap start
607}
608
609#/**
610#    ogConfigureNetworking
611#@brief   Configura la interfaz de red usada en el pxe
612#@param   
613#@return 
614#@exception OG_ERR_FORMAT    Formato incorrecto.
615#@version 0.9
616#@author Antonio J. Doblas. Universidad de Malaga.
617#@date    2010/05/24
618#*/ ##
619ogConfigureNetworking()
620{
621#echo "ogConfigureNetworking: Buscando interfaz a configurar DEVICE"
622if [ -n "${BOOTIF}" ]
623then
624        #echo " variable BOOTIF exportada con pxelinux.0 con valor $BOOTIF"
625        IP=$IPOPTS
626        temp_mac=${BOOTIF#*-}
627        # convert to typical mac address format by replacing "-" with ":"
628        bootif_mac=""
629        IFS='-'
630        for x in $temp_mac ; do
631                if [ -z "$bootif_mac" ]; then
632        bootif_mac="$x"
633        else
634                bootif_mac="$x:$bootif_mac"
635        fi
636        done
637        unset IFS
638        # look for devices with matching mac address, and set DEVICE to
639        # appropriate value if match is found.
640        for device in /sys/class/net/* ; do
641                if [ -f "$device/address" ]; then
642                        current_mac=$(cat "$device/address")
643                        if [ "$bootif_mac" = "$current_mac" ]; then
644                                DEVICE=${device##*/}
645                                break
646                        fi
647                fi
648        done
649else
650        #echo "variable BOOTIF no exportada, intentamos detectar que interfaz se ha iniciado"
651        IP=$ip
652        #TODO Detectar que interfaz se ha iniciado
653        case "$IP" in
654                none|off)
655                        return 0
656                        ;;
657                ""|on|any)
658                        # Bring up device
659                        DEVICE=1
660                        ;;
661                dhcp|bootp|rarp|both)
662                        DEVICE=1
663                        ;;
664                *)
665                        DEVICE=`echo $IP | cut -f6 -d:`
666                        ;;
667        esac
668fi
669DEVICE=$(ogGetNetworkDevice $DEVICE)
670if [ -z "${DEVICE}" ]; then
671        echo "variable DEVICE con valor $DEVICE no encontrada, llamamos de nuevo a ogconfigure_networking"
672        ogConfigureNetworking
673fi
674
675[ -n "${DEVICE}" ] && [ -e /run/net-"${DEVICE}".conf ] && return 0
676#if [ -n "${DEVICE}" ] && [ -e /run/net-"${DEVICE}".conf ]; then
677#       echo "variable DEVICE con valor $DEVICE  y fichero /run/net-$DEVICE encontrados"
678#       return 0
679#else
680#       echo "variable DEVICE con valor $DEVICE encontrada, procedemos a configurala y a crear el fichero /run/net-$DEVICE"
681#fi
682
683# Activamos la interfaz antes de configurar.
684ip address flush $DEVICE
685ip link set dev $DEVICE up
686# Si no se detecta señal portadora volver a configurar.
687sleep 1
688CARRIER=$(cat /sys/class/net/${DEVICE}/carrier)
689if [ "$CARRIER" != "1" ]
690then
691        ogConfigureNetworking
692fi
693
694# support ip options see linux sources
695# Documentation/filesystems/nfsroot.txt
696# Documentation/frv/booting.txt
697for ROUNDTTT in 2 3 4 6 9 16 25 36 64 100; do
698        # The NIC is to be configured if this file does not exist.
699        # Ip-Config tries to create this file and when it succeds
700        # creating the file, ipconfig is not run again.
701        if [ -e /run/net-"${DEVICE}".conf ]; then
702                break;
703        fi
704        case "$IP" in
705                none|off)
706                        return 0
707                ;;
708                ""|on|any)
709                        # Bring up device
710                        echo "Setting $DEVICE  with option:on|any and Variable IP= $IP: ipconfig -t ${ROUNDTTT} ${DEVICE} "
711                        ipconfig -t ${ROUNDTTT} ${DEVICE}
712                ;;
713                dhcp|bootp|rarp|both)
714                        echo "Setting $DEVICE with option:dhcp|bootp|rarp|both and Variable IP=  $IP: ipconfig -t ${ROUNDTTT} -c ${IP} -d ${DEVICE} "
715                        ipconfig -t ${ROUNDTTT} -c ${IP} -d ${DEVICE}
716                ;;
717                *)
718                        echo "Setting $DEVICE with option *  and Variable IP= $IP: ipconfig -t ${ROUNDTTT} -d $IP  "
719                        ipconfig -t ${ROUNDTTT} -d $IP
720                        # grab device entry from ip option
721                        NEW_DEVICE=${IP#*:*:*:*:*:*}
722                        if [ "${NEW_DEVICE}" != "${IP}" ]; then
723                                NEW_DEVICE=${NEW_DEVICE%:*}
724                        else
725                                # wrong parse, possibly only a partial string
726                                NEW_DEVICE=
727                        fi
728                        if [ -n "${NEW_DEVICE}" ]; then
729                                DEVICE="${NEW_DEVICE}"
730                        fi
731                ;;
732        esac
733done
734
735# source ipconfig output
736if [ -n "${DEVICE}" ]; then     
737        export DEVICE
738        export DEVICECFG="/run/net-${DEVICE}.conf"
739        # En algunos casos, el fichero de configuración está en /tmp.
740        [ ! -f $DEVICECFG -a -f ${DEVICECFG/run/tmp} ] && mv ${DEVICECFG/run/tmp} $DEVICECFG
741        source $DEVICECFG
742        echo "DEVICE=$DEVICE" >> $CFGINITRD
743        echo "DEVICECFG=$DEVICECFG" >> $CFGINITRD
744        echo "exportando variable DEVICE con valor = $DEVICE y DEVICECFG con valor $DEVICECFG"
745        # Compatibilidad con versiones anteriores.
746        ln -fs $DEVICECFG /tmp
747else
748        # source any interface as not exaclty specified
749        source /run/net-*.conf
750fi
751}
752
753
754#/**
755#    ogYesNo
756#@brief   Gestion de peticiones de usuario en modo ogdebug=true
757#@param1  OPTIONS    --timeout N    --default ANSWER
758#@param1 Questions   
759#@return  1=yes 0=no
760#@exception OG_ERR_FORMAT    Formato incorrecto.
761#@version 0.9
762#@author: 
763#@date    2010/05/24
764#*/ ##
765ogYesNo()
766{
767    local ans
768    local ok=0
769    local timeout=0
770    local default
771    local t
772
773    while [[ "$1" ]]
774    do
775        case "$1" in
776        --default)
777            shift
778            default=$1
779            if [[ ! "$default" ]]; then error "Missing default value"; fi
780            t=$(echo $default | tr '[:upper:]' '[:lower:]')
781
782            if [[ "$t" != 'y'  &&  "$t" != 'yes'  &&  "$t" != 'n'  &&  "$t" != 'no' ]]; then
783                error "Illegal default answer: $default"
784            fi
785            default=$t
786            shift
787            ;;
788
789        --timeout)
790            shift
791            timeout=$1
792            if [[ ! "$timeout" ]]; then error "Missing timeout value"; fi
793            #if [[ ! "$timeout" =~ ^[0-9][0-9]*$ ]]; then error "Illegal timeout value: $timeout"; fi
794            shift
795            ;;
796
797        -*)
798            error "Unrecognized option: $1"
799            ;;
800
801        *)
802            break
803            ;;
804        esac
805    done
806
807    if [[ $timeout -ne 0  &&  ! "$default" ]]; then
808        error "Non-zero timeout requires a default answer"
809    fi
810
811    if [[ ! "$*" ]]; then error "Missing question"; fi
812
813    while [[ $ok -eq 0 ]]
814    do
815        if [[ $timeout -ne 0 ]]; then
816            if ! read -t $timeout -p "$*" ans; then
817                ans=$default
818            else
819                # Turn off timeout if answer entered.
820                timeout=0
821                if [[ ! "$ans" ]]; then ans=$default; fi
822            fi
823        else
824            read -p "$*" ans
825            if [[ ! "$ans" ]]; then
826                ans=$default
827            else
828                ans=$(echo $ans | tr '[:upper:]' '[:lower:]')
829            fi
830        fi
831
832        if [[ "$ans" == 'y'  ||  "$ans" == 'yes'  ||  "$ans" == 'n'  ||  "$ans" == 'no' ]]; then
833            ok=1
834        fi
835
836        if [[ $ok -eq 0 ]]; then warning "Valid answers are: yes y no n"; fi
837    done
838    [[ "$ans" = "y" || "$ans" == "yes" ]]
839}
840 
Note: See TracBrowser for help on using the repository browser.