source: client/engine/Protocol.lib @ 6bb748b

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 6bb748b was c1c2997, checked in by ramon <ramongomez@…>, 7 years ago

#823: Corregir errata en r5576 al eliminar / inicial en función ogGetPath y adaptar llamdas desde ogUpdateCacheIsNecesary.

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

  • Property mode set to 100755
File size: 39.3 KB
Line 
1#!/bin/bash
2#/**
3#@file    Protocol.lib
4#@brief   Librería o clase Protocol
5#@class   Protocol
6#@brief   Funciones para transmisión de datos
7#@version 1.0.5
8#@warning License: GNU GPLv3+
9#*/
10
11
12##################### FUNCIONES UNICAST ################
13
14#/**
15#         ogUcastSyntax
16#@brief   Función para generar la instrucción de transferencia de datos unicast
17#@param 1 Tipo de operación [ SENDPARTITION RECEIVERPARTITION SENDFILE RECEIVERFILE ]
18#@param 2 Sesion Unicast
19#@param 3 Dispositivo (opción PARTITION) o fichero(opción FILE) que será enviado.
20#@param 4 Tools de clonación (opcion PARTITION)
21#@param 5 Tools de compresion (opcion PARTITION)
22#@return  instrucción para ser ejecutada.
23#@exception OG_ERR_FORMAT     formato incorrecto.
24#@exception OG_ERR_UCASTSYNTAXT     formato de la sesion unicast incorrecta.
25#@note    Requisitos: mbuffer
26#@todo: controlar que mbuffer esta disponible para los clientes.
27#@version 1.0 -
28#@author  Antonio Doblas Viso, Universidad de Málaga
29#@date    2011/03/09
30#*/ ##
31     
32function ogUcastSyntax ()
33{
34
35local PARM SESSION SESSIONPARM MODE PORTBASE PERROR ADDRESS
36local TOOL LEVEL DEVICE MBUFFER SYNTAXSERVER SYNTAXCLIENT
37
38# Si se solicita, mostrar ayuda.
39if [ "$*" == "help" -o "$2" == "help" ]; then
40    ogHelp "$FUNCNAME SENDPARTITION      str_sessionSERVER     str_device str_tools str_level" \
41                   "$FUNCNAME RECEIVERPARTITION  str_sessionCLIENT     str_device str_tools str_level "\
42                   "$FUNCNAME SENDFILE           str_sessionSERVER     str_file "\
43                   "$FUNCNAME RECEIVERFILE       str_sessionCLIENT     str_file " \
44                   "sessionServer syntax:        portbase:ipCLIENT-1:ipCLIENT-2:ipCLIENT-N " \
45                   "sessionServer example:       8000:172.17.36.11:172.17.36.12" \
46                   "sessionClient syntax:        portbase:ipMASTER " \
47                   "sessionClient example:       8000:172.17.36.249 "
48    return
49fi
50PERROR=0
51
52
53
54
55# Error si no se reciben $PARM parámetros.
56echo "$1" | grep "PARTITION" > /dev/null && PARM=5 || PARM=3
57[ "$#" -eq "$PARM" ] || ogRaiseError $OG_ERR_FORMAT "sin parametros"|| return $?
58
59
60# 1er param check
61ogCheckStringInGroup "$1" "SENDPARTITION sendpartition RECEIVERPARTITION receiverpartition SENDFILE sendfile RECEIVERFILE receiverfile" || ogRaiseError $OG_ERR_FORMAT "1st param: $1" || PERROR=1 #return $?
62
63# 2º param check
64echo "$1" | grep "SEND" > /dev/null && MODE=server || MODE=client
65
66######### No controlamos el numero de elementos de la session unicast porque en el master es variable en numero
67#TODO: diferenciamos los paramatros especificos de la sessión unicast 
68#SI: controlamos todos los parametros de la sessión unicast.
69#[ $MODE == "client" ] && SESSIONPARM=2 || SESSIONPARM=6
70OIFS=$IFS; IFS=':' ; SESSION=($2); IFS=$OIFS
71
72
73#[[ ${#SESSION[*]} == $SESSIONPARM ]]  || ogRaiseError $OG_ERR_FORMAT "parametros session multicast no completa" || PERROR=2# return $?
74
75
76#controlamos el PORTBASE de la sesion. Comun.-
77PORTBASE=${SESSION[0]}
78ogCheckStringInGroup ${SESSION[0]} "8000 8001 8002 8003 8004 8005" || ogRaiseError $OG_ERR_FORMAT "McastSession portbase ${SESSION[0]}" || PERROR=3 #return $?
79
80if [ $MODE == "server" ]
81then   
82    SIZEARRAY=${#SESSION[@]}
83    for (( i = 1 ; i < $SIZEARRAY ; i++ ))
84        do
85                ADDRESS="$ADDRESS  -O ${SESSION[$i]}:$PORTBASE"
86        #echo " -O ${SESSION[$i]}:$PORTBASE"
87        done
88   
89else
90        ADDRESS=${SESSION[1]}:${PORTBASE}
91fi
92
93#3er param check - que puede ser un dispositvo o un fichero.
94#[ -n "$(ogGetPath "$3")" ] || ogRaiseError $OG_ERR_NOTFOUND " device or file $3" || PERROR=9 #return $? 
95DEVICE=$3
96
97#4 y 5 param check .  solo si es sobre particiones.
98if [ "$PARM" == "5" ]
99then
100        # 4 param check
101        ogCheckStringInGroup "$4" "partclone PARTCLONE partimage PARTIMAGE ntfsclone NTFSCLONE" || ogRaiseError $OG_ERR_NOTFOUND " herramienta $4 no soportada" || PERROR=10 #return $?
102        TOOL=$4
103        ogCheckStringInGroup "$5" "lzop gzip LZOP GZIP 0 1" || ogRaiseError $OG_ERR_NOTFOUND " compresor $5 no valido" || PERROR=11 #return $?
104        LEVEL=$5
105fi
106
107[ "$PERROR" == "0" ] || ogRaiseError $OG_ERR_UCASTSYNTAXT " $PERROR" || return $?
108
109# Generamos la instrucción base de unicast -Envio,Recepcion-
110SYNTAXSERVER="mbuffer $ADDRESS"
111SYNTAXCLIENT="mbuffer -I $ADDRESS "
112
113
114case "$1" in
115SENDPARTITION)
116                PROG1=`ogCreateImageSyntax $DEVICE " " $TOOL $LEVEL | awk -F"|" '{print $1 "|" $3}' | tr -d ">"`
117                echo "$PROG1 | $SYNTAXSERVER"
118        ;;
119    RECEIVERPARTITION)
120                COMPRESSOR=`ogRestoreImageSyntax " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $1}'`
121                TOOLS=`ogRestoreImageSyntax " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $NF}'`
122                echo "$SYNTAXCLIENT | $COMPRESSOR | $TOOLS "
123        ;;
124        SENDFILE)
125                echo "$SYNTAXSERVER -i $3"
126    ;;
127    RECEIVERFILE)
128                echo "$SYNTAXCLIENT -i $3"
129    ;;
130   *)
131   ;;
132esac
133}
134
135
136#/**
137#         ogUcastSendPartition
138#@brief   Función para enviar el contenido de una partición a multiples particiones remotas usando UNICAST.
139#@param 1  disk
140#@param 2  partition
141#@param 3  sesionUcast
142#@param 4  tool image
143#@param 5  tool compresor
144#@return
145#@exception $OG_ERR_FORMAT
146#@exception $OG_ERR_UCASTSENDPARTITION
147#@note
148#@todo: ogIsLocked siempre devuelve 1
149#@version 1.0 -
150#@author  Antonio Doblas Viso, Universidad de Málaga
151#@date    2011/03/09
152#*/ ##
153
154function ogUcastSendPartition ()
155{
156
157# Variables locales
158local PART COMMAND RETVAL
159
160# Si se solicita, mostrar ayuda.
161if [ "$*" == "help" ]; then
162    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart SessionUNICAST-SERVER tools compresor" \
163           "$FUNCNAME 1 1 8000:172.17.36.11:172.17.36.12 partclone lzop"
164    return
165fi
166# Error si no se reciben 5 parámetros.
167[ "$#" == 5 ] || ogRaiseError $OG_ERR_FORMAT || return $?
168#chequeamos la particion.
169PART=$(ogDiskToDev "$1" "$2") || return $?
170
171#ogIsLocked $1 $2 || ogRaiseError $OG_ERR_LOCKED "$1,$2" || return $?
172ogUnmount $1 $2
173
174#generamos la instrucción a ejecutar. 
175COMMAND=`ogUcastSyntax SENDPARTITION "$3" $PART $4 $5`
176RETVAL=$?
177
178if [ "$RETVAL" -gt "0" ]
179then 
180        return $RETVAL
181else
182        echo $COMMAND
183        eval $COMMAND || ogRaiseError $OG_ERR_UCASTSENDPARTITION " "; return $?
184fi
185
186}
187
188
189#/**
190#         ogUcastReceiverPartition
191#@brief   Función para recibir directamente en la partición el contenido de un fichero imagen remoto enviado por UNICAST.
192#@param 1   disk
193#@param 2   partition
194#@param 3   session unicast
195#@return
196#@exception OG_ERR_FORMAT
197#@exception OG_ERR_UCASTRECEIVERPARTITION
198#@note
199#@todo:
200#@version 1.0 - Integración para OpenGNSys.
201#@author  Antonio Doblas Viso, Universidad de Málaga
202#@date    2011/03/09
203#*/ ##
204function ogUcastReceiverPartition ()
205{
206# Variables locales
207local PART COMMAND RETVAL
208
209# Si se solicita, mostrar ayuda.
210if [ "$*" == "help" ]; then
211    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart SessionMulticastCLIENT tools compresor" \
212           "$FUNCNAME 1 1 8000:ipMASTER partclone lzop"
213    return
214fi
215# Error si no se reciben 5 parámetros.
216[ "$#" == 5 ] || ogRaiseError $OG_ERR_FORMAT || return $?
217#chequeamos la particion.
218PART=$(ogDiskToDev "$1" "$2") || return $?
219
220#ogIsLocked $1 $2 || ogRaiseError $OG_ERR_LOCKED "$1,$2" || return $?
221ogUnmount $1 $2
222
223#generamos la instrucción a ejecutar. 
224COMMAND=`ogUcastSyntax RECEIVERPARTITION "$3" $PART $4 $5`
225RETVAL=$?
226
227if [ "$RETVAL" -gt "0" ]
228then 
229        return $RETVAL
230else
231        echo $COMMAND
232        eval $COMMAND || ogRaiseError $OG_ERR_UCASTRECEIVERPARTITION " "; return $?
233fi
234}
235
236
237
238#/**
239#         ogUcastSendFile [ str_repo | int_ndisk int_npart ] /Relative_path_file  sessionMulticast
240#@brief   Envía un fichero por unicast   ORIGEN(fichero) DESTINO(sessionmulticast)
241#@param (2 parámetros)  $1 path_aboluto_fichero  $2 sesionMcast
242#@param (3 parámetros)  $1 Contenedor REPO|CACHE $2 path_absoluto_fichero $3 sesionMulticast
243#@param (4 parámetros)  $1 disk $2 particion $3 path_absoluto_fichero $4 sesionMulticast
244#@return 
245#@exception OG_ERR_FORMAT     formato incorrecto.
246#@exception $OG_ERR_NOTFOUND
247#@exception OG_ERR_UCASTSENDFILE
248#@note    Requisitos:
249#@version 1.0 - Definición de Protocol.lib
250#@author  Antonio Doblas Viso, Universidad de Málaga
251#@date    2010/05/09
252#*/ ##
253#
254
255function ogUcastSendFile ()
256{
257# Variables locales.
258local ARG ARGS SOURCE TARGET COMMAND DEVICE RETVAL LOGFILE
259
260
261#ARGS usado para controlar ubicación de la sesion multicast
262# Si se solicita, mostrar ayuda.
263if [ "$*" == "help" ]; then
264    ogHelp "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] /Relative_path_file sesionMcast(puerto:ip:ip:ip)" \
265           "$FUNCNAME  1 1 /aula1/winxp.img 8000:172.17.36.11:172.17.36.12" \
266           "$FUNCNAME  REPO /aula1/ubuntu.iso sesionUcast" \
267           "$FUNCNAME  CACHE /aula1/winxp.img sesionUcast" \
268           "$FUNCNAME  /opt/opengnsys/images/aula1/hd500.vmx sesionUcast"
269    return
270fi
271
272ARGS="$@"
273case "$1" in
274    /*)     # Camino completo.               */ (Comentrio Doxygen)
275        SOURCE=$(ogGetPath "$1")
276        ARG=2
277        DEVICE="$1"
278                ;;
279    [1-9]*) # ndisco npartición.
280        SOURCE=$(ogGetPath "$1" "$2" "$3")
281        ARG=4
282        DEVICE="$1 $2 $3"
283        ;;
284    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
285        SOURCE=$(ogGetPath "$1" "$2")
286        ARG=3
287        DEVICE="$1 $2 "
288        ;;
289esac
290
291
292# Error si no se reciben los argumentos ARG necesarios según la opcion.
293[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
294
295# Comprobar fichero origen
296ogGetPath $SOURCE &> /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $DEVICE not found" || return $? 
297
298
299SESSION=${!ARG}
300
301#generamos la instrucción a ejecutar. 
302COMMAND=`ogUcastSyntax "SENDFILE" "$SESSION" "$SOURCE"`
303RETVAL=$?
304
305if [ "$RETVAL" -gt "0" ]
306then 
307        return $RETVAL
308else
309        echo $COMMAND
310        eval $COMMAND || ogRaiseError $OG_ERR_UCASTSENDFILE " "; return $?
311fi
312
313}
314
315
316
317#/**
318#         ogMcastSyntax
319#@brief   Función para generar la instrucción de ejucción la transferencia de datos multicast
320#@param 1 Tipo de operación [ SENDPARTITION RECEIVERPARTITION SENDFILE RECEIVERFILE ]
321#@param 2 Sesión Mulicast
322#@param 3 Dispositivo (opción PARTITION) o fichero(opción FILE) que será enviado.
323#@param 4 Tools de clonación (opcion PARTITION)
324#@param 5 Tools de compresion (opcion PARTITION)
325#@return  instrucción para ser ejecutada.
326#@exception OG_ERR_FORMAT     formato incorrecto.
327#@exception OG_ERR_NOTEXEC
328#@exception OG_ERR_MCASTSYNTAXT
329#@note    Requisitos: upd-cast 2009 o superior
330#@todo    localvar  check versionudp
331#@version 1.0 -
332#@author  Antonio Doblas Viso, Universidad de Málaga
333#@date    2010/05/09
334#@version 2.0 - cambios en udp-receiver para permitir multicast entre subredes
335#@author  Juan Carlos Garcia, Universidad de Zaragoza
336#@date    2015/11/17
337#@version 1.1 - Control de errores en transferencia multicast (ticket #781)
338#@author  Irina Gomez, ETSII Universidad de Sevilla
339#@date    2017/04/20
340#*/ ##
341#         
342
343function ogMcastSyntax ()
344{
345
346local ISUDPCAST RECEIVERTIMEOUT PARM SESSION SESSIONPARM MODE PORTBASE PERROR
347local METHOD ADDRESS BITRATE NCLIENTS MAXTIME CERROR
348local TOOL LEVEL DEVICE MBUFFER SYNTAXSERVER SYNTAXCLIENT
349
350# Si se solicita, mostrar ayuda.
351if [ "$*" == "help" -o "$2" == "help" ]; then
352    ogHelp "$FUNCNAME SENDPARTITION      str_sessionSERVER     str_device str_tools str_level" \
353                   "$FUNCNAME RECEIVERPARTITION  str_sessionCLIENT     str_device str_tools str_level "\
354                   "$FUNCNAME SENDFILE           str_sessionSERVER     str_file "\
355                   "$FUNCNAME RECEIVERFILE       str_sessionCLIENT     str_file " \
356                   "sessionServer syntax:        portbase:method:mcastaddress:speed:nclients:ntimeWaitingUntilNclients " \
357                   "sessionServer example:       9000:full-duplex|half-duplex|broadcast:239.194.17.36:80M:50:60 " \
358                   "sessionClient syntax:        portbase " \
359                   "sessionClient example:       9000 "
360    return
361fi
362PERROR=0
363
364#si no tenemos updcast o su version superior 2009 udpcast error.
365ISUDPCAST=$(udp-receiver --help 2>&1)
366echo $ISUDPCAST | grep start-timeout > /dev/null || ogRaiseError $OG_ERR_NOTEXEC "upd-cast no existe o version antigua -requerida 2009-"|| return $?
367
368# Si la version de  udp-receiver permite --receive-timeout utilizamos la opción
369if echo $ISUDPCAST | grep receive-timeout &>/dev/null; then
370    RECEIVERTIMEOUT=" --receive-timeout $MCASTWAIT"
371else
372    RECEIVERTIMEOUT=""
373fi
374
375# Error si no se reciben $PARM parámetros.
376echo "$1" | grep "PARTITION" > /dev/null && PARM=5 || PARM=3
377[ "$#" -eq "$PARM" ] || ogRaiseError $OG_ERR_FORMAT "sin parametros"|| return $?
378
379
380# 1er param check
381ogCheckStringInGroup "$1" "SENDPARTITION sendpartition RECEIVERPARTITION receiverpartition SENDFILE sendfile RECEIVERFILE receiverfile" || ogRaiseError $OG_ERR_FORMAT "1st param: $1" || PERROR=1 #return $?
382
383# 2º param check
384echo "$1" | grep "SEND" > /dev/null && MODE=server || MODE=client
385
386#TODO: diferenciamos los paramatros especificos de la sessión multicast 
387#SI: controlamos todos los parametros de la sessión multicast.
388[ $MODE == "client" ] && SESSIONPARM=1 || SESSIONPARM=6
389OIFS=$IFS; IFS=':' ; SESSION=($2); IFS=$OIFS
390
391
392[[ ${#SESSION[*]} == $SESSIONPARM ]]  || ogRaiseError $OG_ERR_FORMAT "parametros session multicast no completa" || PERROR=2# return $?
393
394
395#controlamos el PORTBASE de la sesion. Comun.-
396PORTBASE=${SESSION[0]}
397ogCheckStringInGroup ${SESSION[0]} "$(seq 9000 2 9050)" || ogRaiseError $OG_ERR_FORMAT "McastSession portbase ${SESSION[0]}" || PERROR=3 #return $?
398if [ $MODE == "server" ]
399then   
400        ogCheckStringInGroup ${SESSION[1]} "full-duplex FULL-DUPLEX half-duplex HALF-DUPLEX broadcast BROADCAST" || ogRaiseError $OG_ERR_FORMAT "McastSession method ${SESSION[1]}" || PERROR=4 #return $?
401        METHOD=${SESSION[1]}
402        ogCheckIpAddress ${SESSION[2]}  || ogRaiseError $OG_ERR_FORMAT "McastSession address ${SESSION[2]}" || PERROR=5 #return $?
403        ADDRESS=${SESSION[2]}
404        ogCheckStringInReg ${SESSION[3]} "^[0-9]{1,3}\M$" || ogRaiseError $OG_ERR_FORMAT "McastSession bitrate ${SESSION[3]}" || PERROR=6 # return $?
405        BITRATE=${SESSION[3]}
406        ogCheckStringInReg ${SESSION[4]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_FORMAT "McastSession nclients ${SESSION[4]}" || PERROR=7 # return $?
407        NCLIENTS=${SESSION[4]}
408        ogCheckStringInReg ${SESSION[5]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_FORMAT "McastSession maxtime ${SESSION[5]}" || PERROR=8 # return $?
409        MAXTIME=${SESSION[5]}
410fi
411
412#3er param check - que puede ser un dispositvo o un fichero.
413#ogGetPath "$3" > /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $3" || PERROR=9 #return $? 
414DEVICE=$3
415
416#4 y 5 param check .  solo si es sobre particiones.
417if [ "$PARM" == "5" ]
418then
419        # 4 param check
420        ogCheckStringInGroup "$4" "partclone PARTCLONE partimage PARTIMAGE ntfsclone NTFSCLONE" || ogRaiseError $OG_ERR_NOTFOUND " herramienta $4 no soportada" || PERROR=10 #return $?
421        TOOL=$4
422        ogCheckStringInGroup "$5" "lzop LZOP gzip GZIP 0 1" || ogRaiseError $OG_ERR_NOTFOUND " compresor $5 no valido" || PERROR=11 #return $?
423        LEVEL=$5
424fi
425
426
427if [ "$PERROR" != "0" ]; then
428        ogRaiseError $OG_ERR_MCASTSYNTAXT " $PERROR"; return $?
429fi
430
431
432# Valores estandar no configurables.
433CERROR="8x8/128"
434
435# opción del usuo de tuberia intermedia en memoria mbuffer.
436which mbuffer > /dev/null && MBUFFER=" --pipe 'mbuffer -q -m 20M' "
437
438# Generamos la instrucción base de multicast -Envio,Recepcion-
439SYNTAXSERVER="udp-sender $MBUFFER --nokbd --portbase $PORTBASE --$METHOD --mcast-data-address $ADDRESS --fec $CERROR --max-bitrate $BITRATE --ttl 16 --min-clients $NCLIENTS --max-wait $MAXTIME --autostart $MAXTIME --log /tmp/mcast.log"
440#SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE "
441
442
443# Deteccion automatica de la subred del cliente para anadir la  IP del repositorio a la orden udp-receiver en el caso de encontrarse en distinta subred del repo
444REPOIP="$(ogGetRepoIp)"
445CLIENTIP=$(ip -o address show up | awk '$2!~/lo/ {if ($3~/inet$/) {printf ("%s ", $4)}}')
446MASCARA=`echo $CLIENTIP | cut -f2 -d/`
447CLIENTIP=`echo $CLIENTIP | cut -f1 -d/`
448RIPBT=""
449IPBT=""
450for (( i = 1 ; i < 5 ; i++ ))
451do
452        RIP=`echo $REPOIP | cut -f$i -d.`
453        RIP=`echo "$[$RIP + 256]"`
454        RIPB=""
455        while [ $RIP -gt 0 ]
456        do
457                let COCIENTE=$RIP/2
458                let RESTO=$RIP%2
459                RIPB=$RESTO$RIPB
460                RIP=$COCIENTE
461        done
462        RIPB=`echo "$RIPB" | cut -c2-`
463        RIPBT=$RIPBT$RIPB
464        IP=`echo $CLIENTIP | cut -f$i -d.`
465        IP=`echo "$[$IP + 256]"`
466        IPB=""
467        while [ $IP -gt 0 ]
468        do
469                let COCIENTE=$IP/2
470                let RESTO=$IP%2
471                IPB=$RESTO$IPB
472                IP=$COCIENTE
473        done
474        IPB=`echo "$IPB" | cut -c2-`
475        IPBT=$IPBT$IPB
476done
477MCASTWAIT=${MCASTWAIT:-120}
478REPOSUBRED=`echo $RIPBT | cut -c1-$MASCARA`
479CLIENTSUBRED=`echo $IPBT | cut -c1-$MASCARA`
480if [ $REPOSUBRED == $CLIENTSUBRED ]; then
481        SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE $RECEIVERTIMEOUT --start-timeout $MCASTWAIT"
482else
483        SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE --mcast-rdv-address $REPOIP $RECEIVERTIMEOUT --start-timeout $MCASTWAIT"
484fi
485
486case "$1" in
487SENDPARTITION)
488                PROG1=`ogCreateImageSyntax $DEVICE " " $TOOL $LEVEL | awk -F"|" '{print $1 "|" $3}' | tr -d ">"`
489                echo "$PROG1 | $SYNTAXSERVER"
490        ;;
491    RECEIVERPARTITION)
492                COMPRESSOR=`ogRestoreImageSyntax " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $1}'`
493                TOOLS=`ogRestoreImageSyntax " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $NF}'`
494                echo "$SYNTAXCLIENT | $COMPRESSOR | $TOOLS "
495        ;;
496        SENDFILE)
497                echo "$SYNTAXSERVER --file $3"
498    ;;
499    RECEIVERFILE)
500                echo "$SYNTAXCLIENT --file $3"
501    ;;
502   *)
503   ;;
504esac
505}
506
507
508
509#/**
510#         ogMcastSendFile [ str_repo | int_ndisk int_npart ] /Relative_path_file  sessionMulticast
511#@brief   Envía un fichero por multicast   ORIGEN(fichero) DESTINO(sessionmulticast)
512#@param (2 parámetros)  $1 path_aboluto_fichero  $2 sesionMcast
513#@param (3 parámetros)  $1 Contenedor REPO|CACHE $2 path_absoluto_fichero $3 sesionMulticast
514#@param (4 parámetros)  $1 disk $2 particion $3 path_absoluto_fichero $4 sesionMulticast
515#@return 
516#@exception OG_ERR_FORMAT     formato incorrecto.
517#@exception $OG_ERR_NOTFOUND
518#@exception OG_ERR_MCASTSENDFILE
519#@note    Requisitos:
520#@version 1.0 - Definición de Protocol.lib
521#@author  Antonio Doblas Viso, Universidad de Málaga
522#@date    2010/05/09
523#*/ ##
524#
525
526function ogMcastSendFile ()
527{
528# Variables locales.
529local ARGS ARG SOURCE TARGET COMMAND DEVICE RETVAL LOGFILE
530
531#LOGFILE="/tmp/mcast.log"
532
533#ARGS usado para controlar ubicación de la sesion multicast
534# Si se solicita, mostrar ayuda.
535if [ "$*" == "help" ]; then
536    ogHelp "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] /Relative_path_file sesionMcast" \
537           "$FUNCNAME  1 1 /aula1/winxp.img sesionMcast" \
538           "$FUNCNAME  REPO /aula1/ubuntu.iso sesionMcast" \
539           "$FUNCNAME  CACHE /aula1/winxp.img sesionMcast" \
540           "$FUNCNAME  /opt/opengnsys/images/aula1/hd500.vmx sesionMcast"
541    return
542fi
543
544ARGS="$@"
545case "$1" in
546    /*)     # Camino completo.               */ (Comentrio Doxygen)
547        SOURCE=$(ogGetPath "$1")
548        ARG=2
549        DEVICE="$1"
550                ;;
551    [1-9]*) # ndisco npartición.
552        SOURCE=$(ogGetPath "$1" "$2" "$3")
553        ARG=4
554        DEVICE="$1 $2 $3"
555        ;;
556    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
557        SOURCE=$(ogGetPath "$1" "$2")
558        ARG=3
559        DEVICE="$1 $2 "
560        ;;
561esac
562
563
564# Error si no se reciben los argumentos ARG necesarios según la opcion.
565[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
566
567# Comprobar fichero origen
568ogGetPath $SOURCE &> /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $DEVICE not found" || return $? 
569
570# eliminamos ficheros antiguos de log
571#rm $LOGFILE
572
573SESSION=${!ARG}
574
575
576#generamos la instrucción a ejecutar. 
577COMMAND=`ogMcastSyntax "SENDFILE" "$SESSION" "$SOURCE"`
578RETVAL=$?
579
580if [ "$RETVAL" -gt "0" ]
581then 
582        return $RETVAL
583else
584        echo $COMMAND
585        eval $COMMAND || ogRaiseError $OG_ERR_MCASTSENDFILE " "; return $?
586        #[ -s "$LOGFILE" ] || return 21
587fi
588
589}
590
591
592
593#/**
594#         ogMcastReceiverFile  sesion Multicast [ str_repo | int_ndisk int_npart ] /Relative_path_file
595#@brief   Recibe un fichero multicast   ORIGEN(sesionmulticast) DESTINO(fichero)
596#@param (2 parámetros)  $1 sesionMcastCLIENT $2 path_aboluto_fichero_destino 
597#@param (3 parámetros)  $1 sesionMcastCLIENT $2 Contenedor REPO|CACHE $3 path_absoluto_fichero_destino
598#@param (4 parámetros)  $1 sesionMcastCLIENT $2 disk $3 particion $4 path_absoluto_fichero_destino
599#@return 
600#@exception OG_ERR_FORMAT     formato incorrecto.
601#@exception $OG_ERR_MCASTRECEIVERFILE
602#@note    Requisitos:
603#@version 1.0 - Definición de Protocol.lib
604#@author  Antonio Doblas Viso, Universidad de Málaga
605#@date    2010/05/09
606#*/ ##
607#
608
609function ogMcastReceiverFile ()
610{
611
612# Variables locales.
613local ARGS ARG TARGETDIR TARGETFILE
614
615
616# Si se solicita, mostrar ayuda.
617if [ "$*" == "help" ]; then
618    ogHelp "$FUNCNAME" "$FUNCNAME [ str_portMcast] [ [Relative_path_file] | [str_REPOSITORY path_file] |  [int_ndisk int_npart path_file ]  ]" \
619           "$FUNCNAME 9000 /PS1_PH1.img" \
620           "$FUNCNAME 9000 CACHE /aula1/PS2_PH4.img" \
621           "$FUNCNAME 9000 1 1 /isos/linux.iso"
622    return
623fi
624
625ARGS="$@"
626case "$2" in
627    /*)     # Camino completo.          */ (Comentrio Doxygen)
628        TARGETDIR=$(ogGetParentPath "$2")
629                ARG=2           
630        ;;
631    [1-9]*) # ndisco npartición.
632        TARGETDIR=$(ogGetParentPath "$2" "$3" "$4")
633        ARG=4     
634    ;;
635    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
636        TARGETDIR=$(ogGetParentPath "$2" "$3")
637        ARG=3
638    ;;
639esac
640
641# Error si no se reciben los argumentos ARG necesarios según la opcion.
642[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT "Parametros no admitidos"|| return $?
643
644#obtenemos el nombre del fichero a descargar.
645TARGETFILE=`basename ${!ARG}`
646
647#generamos la instrucción a ejecutar. 
648COMMAND=`ogMcastSyntax RECEIVERFILE "$1" $TARGETDIR/$TARGETFILE `
649RETVAL=$?
650
651if [ "$RETVAL" -gt "0" ]
652then 
653        return $RETVAL
654else
655        echo $COMMAND
656        eval $COMMAND || ogRaiseError $OG_ERR_MCASTRECEIVERFILE "$TARGETFILE"; return $?
657        #[ -s "$LOGFILE" ] || return 21
658fi
659}
660
661
662#/**
663#         ogMcastSendPartition
664#@brief   Función para enviar el contenido de una partición a multiples particiones remotas.
665#@param 1   disk
666#@param 2  partition
667#@param 3  session multicast
668#@param 4  tool clone
669#@param 5  tool compressor
670#@return
671#@exception OG_ERR_FORMAT
672#@exception OG_ERR_MCASTSENDPARTITION
673#@note
674#@todo: ogIsLocked siempre devuelve 1. crear ticket
675#@version 1.0 - Definición de Protocol.lib
676#@author  Antonio Doblas Viso, Universidad de Málaga
677#@date    2010/05/09
678#*/ ##
679
680function ogMcastSendPartition ()
681{
682
683# Variables locales
684local PART COMMAND RETVAL
685
686# Si se solicita, mostrar ayuda.
687if [ "$*" == "help" ]; then
688    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart SessionMulticastSERVER tools compresor" \
689           "$FUNCNAME 1 1 9000:full-duplex:239.194.37.31:50M:20:2 partclone lzop"
690    return
691fi
692# Error si no se reciben 5 parámetros.
693[ "$#" == 5 ] || ogRaiseError $OG_ERR_FORMAT || return $?
694#chequeamos la particion.
695PART=$(ogDiskToDev "$1" "$2") || return $?
696
697#ogIsLocked $1 $2 || ogRaiseError $OG_ERR_LOCKED "$1,$2" || return $?
698ogUnmount $1 $2
699
700#generamos la instrucción a ejecutar. 
701COMMAND=`ogMcastSyntax SENDPARTITION "$3" $PART $4 $5`
702RETVAL=$?
703
704if [ "$RETVAL" -gt "0" ]
705then 
706        return $RETVAL
707else
708        echo $COMMAND
709        eval $COMMAND || ogRaiseError $OG_ERR_MCASTSENDPARTITION " "; return $?
710fi
711
712
713}
714
715#/**
716#         ogMcastReceiverPartition
717#@brief   Función para recibir directamente en la partición el contenido de un fichero imagen remoto enviado por multicast.
718#@param 1   disk
719#@param 2  partition
720#@param 3  session multicast
721#@param 4  tool clone
722#@param 5  tool compressor
723#@return
724#@exception $OG_ERR_FORMAT
725#@note
726#@todo:
727#@version 1.0 - Definición de Protocol.lib
728#@author  Antonio Doblas Viso, Universidad de Málaga
729#@date    2010/05/09
730#*/ ##
731function ogMcastReceiverPartition ()
732{
733# Variables locales
734local PART COMMAND RETVAL
735
736# Si se solicita, mostrar ayuda.
737if [ "$*" == "help" ]; then
738    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart SessionMulticastCLIENT tools compresor" \
739           "$FUNCNAME 1 1 9000 partclone lzop"
740    return
741fi
742# Error si no se reciben 5 parámetros.
743[ "$#" == 5 ] || ogRaiseError $OG_ERR_FORMAT || return $?
744#chequeamos la particion.
745PART=$(ogDiskToDev "$1" "$2") || return $?
746
747#ogIsLocked $1 $2 || ogRaiseError $OG_ERR_LOCKED "$1,$2" || return $?
748ogUnmount $1 $2
749
750#generamos la instrucción a ejecutar. 
751COMMAND=`ogMcastSyntax RECEIVERPARTITION "$3" $PART $4 $5`
752RETVAL=$?
753
754if [ "$RETVAL" -gt "0" ]
755then 
756        return $RETVAL
757else
758        echo $COMMAND
759        eval $COMMAND || ogRaiseError $OG_ERR_MCASTSENDPARTITION " "; return $?
760fi
761
762}
763
764
765#/**
766#         ogMcastRequest
767#@brief   Función temporal para solicitar al ogRepoAux el envio de un fichero por multicast
768#@param 1  Fichero a enviar ubicado en el REPO. puede ser ruta absoluta o relatica a /opt/opengnsys/images
769#@param 2  PROTOOPT   opciones protocolo multicast
770#@return
771#@exception
772#@note
773#@todo:
774#@version 1.0.5
775#@author  Antonio Doblas Viso, Universidad de Málaga
776#@date    2012/05/29
777#@version 1.1 - Control de errores en transferencia multicast (ticket #781)
778#@author  Irina Gomez, ETSII Universidad de Sevilla
779#@date    2017/04/20
780#@version 1.1 - Unidades organizativas con directorio de imágenes separado. (ticket #678)
781#@author  Irina Gomez, ETSII Universidad de Sevilla
782#@date    2017/06/23
783#*/ ##
784function ogMcastRequest {
785# Variables locales
786local FILE PROTOOPT PORT PORTAUX REPOIP REPOPORTAUX REPEAT OGUNIT
787
788# Si se solicita, mostrar ayuda.
789if [ "$*" == "help" ]; then
790    ogHelp "$FUNCNAME" "$FUNCNAME path_filename str_mcastoptions"
791    return
792fi
793# Error si no se reciben 2 parámetros.
794[ "$#" == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
795
796OGUNIT="$(df|awk '/ogimages/ {print $1}'|cut -d/ -f5)/"
797FILE="$OGUNIT$1"
798PROTOOPT="$2"
799
800#TODO: CONTROL PARAMETROS
801
802PORT=$(echo $2 | cut -f1 -d":")
803let PORTAUX=$PORT+1
804REPOIP=$(ogGetRepoIp)
805REPOPORTAUX=2009
806REPEAT=0
807until nmap -n -sU -p $PORTAUX $REPOIP | grep open
808do
809    let REPEAT=$REPEAT+1
810    [ "$REPEAT" -lt 6 ] || ogRaiseError session log $OG_ERR_PROTOCOLJOINMASTER "MULTICAST \"$FILE\" \"$PROTOOPT\" $FILELIST" || return $?
811    echo "$MSG_SCRIPTS_TASK_START :  hose $REPOIP $REPOPORTAUX --out sh -c "echo -ne START_MULTICAST $FILE $2""
812    #update-cache:
813    hose $REPOIP $REPOPORTAUX --out sh -c "echo -ne START_MULTICAST "$FILE" "$PROTOOPT""
814    #multicas-direct:  hose $REPOIP 2009 --out sh -c "echo -ne START_MULTICAST /$IMAGE.img $OPTPROTOCOLO"
815    sleep 10
816done
817}
818
819
820##########################################
821############## funciones torrent
822#/**
823#         ogTorrentStart  [ str_repo | int_ndisk int_npart ] Relative_path_file.torrent | SessionProtocol
824#@brief   Función iniciar P2P - requiere un tracker para todos los modos, y un seeder para los modos peer y leecher y los ficheros .torrent.
825#@param   str_pathDirectory  str_Relative_path_file
826#@param  int_disk    int_partition   str_Relative_path_file
827#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
828#@param (2 parámetros)  $1 path_aboluto_fichero_torrent  $2 Parametros_Session_Torrent 
829#@param (3 parámetros)  $1 Contenedor CACHE $2 path_absoluto_fichero_Torrent $3 Parametros_Session_Torrent
830#@param (4 parámetros)  $1 disk $2 particion $3 path_absoluto_fichero_Torrent 4$ Parametros_Session_Torrent
831
832#@return
833#@note
834#@todo:
835#@version 0.1 - Integración para OpenGNSys.
836#@author        Antonio J. Doblas Viso. Universidad de Málaga
837#@date
838#@version 0.2 - Chequeo del tamaño de imagen descargado.
839#@author        Irina . Univesidad de Sevilla.
840#@date
841#@version 0.3 - Control de los modos de operación, y estado de descarga.
842#@author        Antonio J. Doblas Viso. Univesidad de Málaga.
843#@date
844#@version 0.4 - Enviadando señal (2) a ctorrent permiendo la comunicación final con tracker
845#@author        Antonio J. Doblas Viso. Univesidad de Málaga.
846#@date
847#*/ ##
848
849#protocoloTORRENT    mode:time
850#mode=seeder  -> Dejar el equipo seedeando hasta que transcurra el tiempo indicado o un kill desde consola,
851#mode=peer    -> seedear mientras descarga
852#mode=leecher  -> NO seedear mientras descarga
853#time tiempo que una vez descargada la imagen queremos dejar al cliente como seeder.
854
855function ogTorrentStart ()
856{
857
858# Variables locales.
859local ARGS ARG TARGETDIR TARGETFILE SESSION ERROR
860ERROR=0
861
862# Si se solicita, mostrar ayuda.
863if [ "$*" == "help" ]; then
864    ogHelp "$FUNCNAME $FUNCNAME [ str_repo] [ [Relative_path_fileTORRENT] | [str_REPOSITORY path_fileTORRENT] |  [int_ndisk int_npart path_fileTORRENT ]  ] SessionTorrent" \
865           "$FUNCNAME CACHE /PS1_PH1.img.torrent seeder:10000" \
866           "$FUNCNAME /opt/opengnsys/cache/linux.iso peer:60" \
867           "$FUNCNAME 1 1 /linux.iso.torrent leecher:60"
868    return
869fi
870
871case "$1" in
872    /*)     # Camino completo.          */ (Comentrio Doxygen)
873           SOURCE=$(ogGetPath "$1")
874           ARG=2
875     ;;
876    [1-9]*) # ndisco npartición.
877           SOURCE=$(ogGetPath "$1" "$2" "$3")
878           ARG=4
879     ;;
880    *) # Otros: Solo cache (no se permiten caminos relativos).
881        SOURCE=$(ogGetPath "$1" "$2" 2>/dev/null)
882        ARG=3
883     ;;
884esac
885
886# Error si no se reciben los argumentos ARG necesarios según la opcion.
887[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT "Parametros no admitidos"|| return $?
888
889#controlar source, que no se haga al repo.
890if [ $ARG == "3" ]
891then
892    ogCheckStringInGroup "$1" "CACHE cache" || ogRaiseError $OG_ERR_FORMAT "La descarga torrent solo se hace desde local, copia el torrent a la cache y realiza la operación desde esa ubicación" || return $?
893fi
894if [ $ARG == "2" ]
895then
896    if `ogCheckStringInReg "$1" "^/opt/opengnsys/images"`
897    then
898        ogRaiseError $OG_ERR_FORMAT "La descarga torrent solo se hace desde local, copia el torrent a la cache y realiza la operación desde esa ubicación"
899        return $?
900        fi
901fi
902
903#controlar el source, para que sea un torrent.
904ctorrent -x ${SOURCE} &> /dev/null; [ $? -eq 0 ] ||  ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
905
906TARGET=`echo $SOURCE | awk -F.torrent '{print $1}'`
907DIRSOURCE=`ogGetParentPath $SOURCE`
908cd $DIRSOURCE
909
910
911
912SESSION=${!ARG}
913OIFS=$IFS; IFS=':' ; SESSION=($SESSION); IFS=$OIFS
914[[ ${#SESSION[*]} == 2 ]]  || ogRaiseError $OG_ERR_FORMAT "parametros session Torrent no completa:  modo:tiempo" || ERROR=1# return $?
915#controlamos el modo de operación del cliente-
916ogCheckStringInGroup ${SESSION[0]} "seeder SEEDER peer PEER leecher LEECHER" || ogRaiseError $OG_ERR_FORMAT "valor modo Torrent no valido ${SESSION[0]}" || ERROR=1 #return $?
917MODE=${SESSION[0]}
918#contolamos el tiempo para el seeder o una vez descargada la imagen como peer o leecher.
919ogCheckStringInReg ${SESSION[1]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_FORMAT "valor tiempo no valido ${SESSION[1]}" || ERROR=1 # return $?
920TIME=${SESSION[1]}
921# si ha habido error en el control de parametros error.
922[ "$ERROR" == "1" ] && return 1
923
924
925#SYNTAXSEEDER="echo MODE seeder ctorrent ; (sleep \$TIME && kill -9 \`pidof ctorrent\`) & ; ctorrent \${SOURCE}"
926
927# si No fichero .bf, y Si fichero destino    imagen ya descargada y su chequeo fue comprobado en su descarga inicial.
928if [ ! -f ${SOURCE}.bf -a -f ${TARGET} ]
929then
930  echo "imagen ya descargada"
931  case "$MODE" in
932        seeder|SEEDER)
933                echo "MODE seeder ctorrent"     #### ${SOURCE} -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100"
934                (sleep $TIME && kill -2 `pidof ctorrent`) &
935                ctorrent -f ${SOURCE}           
936  esac
937  return 0
938fi
939
940#Si no existe bf ni fichero destino         descarga inicial.
941if [ ! -f ${SOURCE}.bf -a ! -f ${TARGET} ]
942then
943        OPTION=DOWNLOAD
944    echo "descarga inicial"
945fi
946
947# Si fichero bf           descarga anterior no completada -.
948if [ -f ${SOURCE}.bf -a -f ${TARGET} ]
949then       
950        echo Continuar con Descargar inicial no terminada.
951        OPTION=DOWNLOAD
952fi
953
954if [ "$OPTION" == "DOWNLOAD" ]
955then
956        case "$MODE" in
957        peer|PEER)
958                echo "Donwloading Torrent as peer"  ### echo "ctorrent -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100 $SOURCE -s $TARGET -b ${SOURCE}"
959                        # Creamos el fichero de resumen por defecto
960                        touch ${SOURCE}.bf
961                        # ctorrent controla otro fichero -b ${SOURCE}.bfog
962                        ctorrent -f -c -X "sleep $TIME; kill -2 \$(pidof ctorrent)" -C 100 ${SOURCE} -s ${TARGET} -b ${SOURCE}.bfog
963        ;;
964        leecher|LEECHER)
965                echo "Donwloading Torrent as leecher" # echo "ctorrent ${SOURCE} -X 'sleep 30; kill -9 \$(pidof ctorrent)' -C 100 -U 0"
966                ctorrent ${SOURCE} -X "sleep 30; kill -2 \$(pidof ctorrent)" -C 100 -U 0
967        ;;
968        seeder|SEEDER)
969                echo "MODE seeder ctorrent"     #### ${SOURCE} -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100"
970                        # Creamos el fichero de resumen por defecto
971                        touch ${SOURCE}.bf
972                        # ctorrent controla otro fichero -b ${SOURCE}.bfog
973                ctorrent -f -c -X "sleep $TIME; kill -2 \$(pidof ctorrent)" -C 100 ${SOURCE} -s ${TARGET} -b ${SOURCE}.bfog
974                ;;
975        esac
976fi
977cd /tmp
978}
979
980#/**
981#         ogCreateTorrent  [ str_repo | int_ndisk int_npart ] Relative_path_file
982#@brief   Función para crear el fichero torrent.
983#@param   str_pathDirectory  str_Relative_path_file
984#@param  int_disk    int_partition   str_Relative_path_file
985#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
986#@return
987#@exception OG_ERR_FORMAT    Formato incorrecto.
988#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
989#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
990#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
991#@note
992#@version 0.1 - Integración para OpenGNSys.
993#@author        Antonio J. Doblas Viso. Universidad de Málaga
994#@date
995#@version 0.2 - Integración para btlaunch.
996#@author        Irina . Univesidad de Sevilla.
997#@date
998#*/ ##
999
1000function ogCreateTorrent ()
1001{
1002# Variables locales.
1003local ARGS ARG SOURCE EXT IPTORRENT
1004
1005
1006# Si se solicita, mostrar ayuda.
1007if [ "$*" == "help" ]; then
1008    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file IpBttrack" \           "$FUNCNAME 1 1 /aula1/winxp 10.1.15.23" \
1009       "$FUNCNAME REPO /aula1/winxp 10.1.15.45"
1010
1011    return
1012fi
1013
1014# Error si se quiere crear el fichero en cache y no existe
1015[ "$1" != "CACHE" ] || `ogFindCache >/dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE"|| return $?
1016
1017case "$1" in
1018    /*)     # Camino completo.          */ (Comentrio Doxygen)
1019           SOURCE=$(ogGetPath "$1.img")
1020        ARG=2
1021                ;;
1022    [1-9]*) # ndisco npartición.
1023           SOURCE=$(ogGetPath "$1" "$2" "$3.img")
1024        ARG=4
1025        ;;
1026    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
1027        EXT=$(ogGetImageType "$1" "$2")
1028        SOURCE=$(ogGetPath "$1" "$2.$EXT")
1029        ARG=3
1030        ;;
1031esac
1032
1033# Error si no se reciben los argumentos ARG necesarios según la opcion.
1034[ $# -eq "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
1035
1036
1037# Error si no existe la imagen
1038[ $SOURCE ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
1039
1040[ -r $SOURCE.torrent ] && mv "$SOURCE.torrent" "$SOURCE.torrent.ant" && echo "Esperamos que se refresque el servidor" && sleep 20
1041
1042IPTORRENT="${!#}"
1043# Si ponemos el path completo cuando creamos el fichero torrent da error
1044cd `dirname $SOURCE`
1045echo ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
1046ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
1047
1048}
1049
1050
1051#/**
1052#         ogUpdateCacheIsNecesary  [ str_repo ] Relative_path_file_OGIMG_with_/
1053#@brief   Comprueba que el fichero que se desea almacenar en la cache del cliente, no esta.
1054#@param   1 str_REPO
1055#@param   2 str_Relative_path_file_OGIMG_with_/
1056#@param   3 md5 to check: use full to check download image torrent
1057#@return    0 (true) cache sin imagen, SI es necesario actualizar el fichero.
1058#@return    1 (false) imagen en la cache, NO es necesario actualizar el fichero
1059#@return   >1 (false) error de sintaxis (TODO)
1060#@note
1061#@todo:      Proceso en el caso de que el fichero tenga el mismo nombre, pero su contenido sea distinto.
1062#@todo:      Se dejan mensajes mientras se confirma su funcionamiento.
1063#@version 0.1 - Integracion para OpenGNSys.
1064#@author        Antonio J. Doblas Viso. Universidad de Malaga
1065#@date
1066#@version 1.6 - gestiona ficheros hash full.sum (TORRENT) y .sum (MULTICAST)
1067#@author        Antonio J. Doblas Viso. Universidad de Malaga
1068#@date
1069#*/ ##
1070function ogUpdateCacheIsNecesary ()
1071{
1072#echo "admite full check con 3param TORRENT"
1073# Variables locales.
1074local ERROR SOURCE CACHE FILESOURCE MD5SOURCE FILETARGET MD5TARGET
1075ERROR=0
1076
1077# Si se solicita, mostrar ayuda.
1078if [ "$*" == "help" ]; then
1079    ogHelp "$FUNCNAME" "$FUNCNAME str_repo  relative_path_image [protocol|FULL]" \
1080           "$FUNCNAME REPO /PS1_PH1.img UNICAST" \
1081           "$FUNCNAME REPO /ogclient.sqfs FULL"
1082           
1083    return
1084fi
1085
1086#Control de la cache
1087ogFindCache &>/dev/null || return $(ogRaiseError $OG_ERR_NOTCACHE; echo $?)
1088
1089#Control de parametros:  ahora admite tres.
1090[ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG str_repo relative_path_image [protocol|FULL]"; echo $?)
1091
1092ogCheckStringInGroup "$1" "REPO repo" || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?)
1093FILESOURCE=`ogGetPath $1 $2`
1094[ -n "$FILESOURCE" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?)
1095
1096#echo "paso 1. si no existe la imagen, confirmar que es necesario actualizar la cache."
1097FILETARGET=`ogGetPath CACHE $2`
1098if [ -z "$FILETARGET" ]
1099then
1100    # borramos el fichero bf del torrent, en el caso de que se hubiese quedado de algun proceso fallido
1101    [ -n "$(ogGetPath CACHE "/$2.torrent.bf")" ] && ogDeleteFile CACHE "/$2.torrent.bf" &> /dev/null
1102    [ -n "$(ogGetPath CACHE "/$2.sum")" ] && ogDeleteFile CACHE "/$2.sum" &> /dev/null
1103    [ -n "$(ogGetPath CACHE "/$2.full.sum")" ] && ogDeleteFile CACHE "/$2.full.sum" &> /dev/null
1104    echo "TRUE(0), es necesario actualizar. Paso 1, la cache no contiene esa imagen "
1105    return 0
1106fi
1107
1108#echo "Paso 2. Comprobamos que la imagen no estuviese en un proceso previo torrent"
1109if [ -n "$(ogGetPath "$FILETARGET.torrent.bf")" ]; then
1110    #TODO: comprobar los md5 del fichero .torrent para asegurarnos que la imagen a descarga es la misma.
1111    echo "TRUE(0), es necesario actualizar. Paso 2, la imagen esta en un estado de descarga torrent interrumpido"
1112    return 0
1113fi
1114
1115## En este punto la imagen en el repo y en la cache se llaman igual,
1116#echo "paso 4. Obtener los md5 del fichero imagen en la cacha segun PROTOCOLO  $3"
1117case "${3^^}" in
1118        FULL|TORRENT)
1119                #Buscamos MD5 en el REPO SOURCE
1120                if [ -f $FILESOURCE.full.sum ]
1121                then
1122                        MD5SOURCE=$(cat $FILESOURCE.full.sum)
1123                else
1124                        MD5SOURCE=$(ogCalculateFullChecksum $FILESOURCE)
1125                fi
1126                # Generamos el MD5 (full) en la CACHE
1127                [ ! -f $FILETARGET.full.sum ] && ogCalculateFullChecksum $FILETARGET > $FILETARGET.full.sum
1128                MD5TARGET=$(cat $FILETARGET.full.sum)
1129                # Generamos el MD5 (little) en la CACHE para posteriores usos del protocolo MULTICAST
1130                [ ! -f $FILETARGET.sum ] &&  ogCalculateChecksum $FILETARGET > $FILETARGET.sum
1131        ;;
1132        *)
1133                #Buscamos MD5 en el REPO SOURCE
1134                if [ -f $FILESOURCE.sum ]
1135                then
1136                        MD5SOURCE=$(cat $FILESOURCE.sum)
1137                else
1138                        MD5SOURCE=$(ogCalculateChecksum $FILESOURCE)
1139                fi
1140                # Generamos el MD5 (little) en la CACHE
1141                [ ! -f $FILETARGET.sum ] && ogCalculateChecksum $FILETARGET > $FILETARGET.sum
1142                MD5TARGET=$(cat $FILETARGET.sum)
1143        #Generamos o copiamos MD5 (full) en la CACHE para posteriores usos con Torrent
1144        # Si no existe el full.sum y si existe el .sum es porque el upateCACHE multicast o unicast ha sido correcto.
1145        if [ ! -f $FILETARGET.full.sum -a $FILETARGET.sum ]
1146        then
1147            if [ -f $FILESOURCE.full.sum ]
1148            then
1149                #Existe el .full.sum en REPO realizamos COPIA
1150                cp $FILESOURCE.full.sum $FILETARGET.full.sum
1151            else
1152                #No existe .full.sum no en REPO LO GENERAMOS en la cache: situacion dificil que ocurra
1153                ogCalculateFullChecksum $FILETARGET > $FILETARGET.full.sum
1154            fi
1155        fi             
1156               
1157esac
1158
1159#echo "Paso 5. comparar los md5"
1160if [ "$MD5SOURCE" == "$MD5TARGET" ]
1161then   
1162        echo "FALSE (1), No es neceario actualizar. Paso5.A la imagen esta en cache"
1163    return 1
1164else
1165    echo "imagen en cache distinta,  borramos la imagen anterior"
1166    rm -f $FILETARGET $FILETARGET.sum $FILETARGET.torrent $FILETARGET.full.sum
1167    echo "TRUE (0), Si es necesario actualizar."
1168    return 0
1169fi
1170}
1171
Note: See TracBrowser for help on using the repository browser.