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

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 21bfeb0 was 6acd145, checked in by ramon <ramongomez@…>, 8 years ago

#768: Crear clientes con soporte de variable ogclient para usar varios ogLive, define ogLive por defecto compatible con los clientes OGClient y con soporte basado en Ubuntu 16.04 con Kernel 4.8.

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

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