source: client/engine/Protocol.lib @ e4dafd6

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 e4dafd6 was cc42233, checked in by adv <adv@…>, 14 years ago

version1.0.1 #396 modificacion temporal para detectar FALSE en ogIs...

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

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