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

main 3.10.1
Last change on this file was 4eb0c9b, checked in by Natalia Serrano <natalia.serrano@…>, 3 weeks ago

refs #2232 increase ulimit for the qt6 browser

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