source: client/boot-tools/includes/etc/initramfs-tools/scripts/ogfunctions @ a79df90a

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 a79df90a was e4060f1, checked in by ramon <ramongomez@…>, 8 years ago

#724 #768: Cambios en generación de cliente ogLive:

  • Script boottoolsgenerator.sh soporta parámetro para generar ogLive basado en distribuciones soportadas.
  • Soporta variable del kernel oglivedir con subdirectorio de instalación de ogLive.
  • Dejar de compilar paquetes incluidos en distribuciones Ubuntu.
  • Procesar ficheros JSON en scripts BASH.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5161 a21b9725-9963-47de-94b9-378ad31fedc9

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