source: client/engine/Protocol.lib @ 187902b

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 187902b was 1cd64e6, checked in by ramon <ramongomez@…>, 14 years ago

Versión 1.0.2: Continuar depurando el motor de clonación:

  • Revisar variables locales.
  • Ayudas de las funciones.
  • Incluir fecha y hora en mensajes de logs.

Modifica ticket #446.

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