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

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 a86a15b was 36919af0, checked in by ramon <ramongomez@…>, 9 years ago

#724: Adaptación de ogLive basado en Ubuntu 16.04:

  • Actualizar lista de módulos de vídeo que no deben cargarse y cargar módulo de ratón USB.
  • Mostrar resolución de pantalla y driver por defecto, si solo hay una opción disponible.
  • Soportar resolución por defecto para módulo uvesafb (video=uvesafb:D).

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

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