source: client/engine/Protocol.lib @ d372e6e

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 d372e6e was 12e8e382, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.4, #489: Integrar ticket:489 en rama de desarrollo.

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

  • Property mode set to 100755
File size: 33.8 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
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#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
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#*/ ##
335#         
336
337function ogMcastSyntax ()
338{
339
340local ISUDPCAST PARM SESSION SESSIONPARM MODE PORTBASE PERROR
341local METHOD ADDRESS BITRATE NCLIENTS MAXTIME CERROR
342local TOOL LEVEL DEVICE MBUFFER SYNTAXSERVER SYNTAXCLIENT
343
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 "\
349                   "$FUNCNAME RECEIVERFILE       str_sessionCLIENT     str_file " \
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 " \
352                   "sessionClient syntax:        portbase " \
353                   "sessionClient example:       9000 "
354    return
355fi
356PERROR=0
357
358#si no tenemos updcast o su version superior 2009 udpcast error.
359ISUDPCAST=$(udp-receiver --help 2>&1)
360echo $ISUDPCAST | grep start-timeout > /dev/null || ogRaiseError $OG_ERR_NOTEXEC "upd-cast no existe o version antigua -requerida 2009-"|| return $?
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
369ogCheckStringInGroup "$1" "SENDPARTITION sendpartition RECEIVERPARTITION receiverpartition SENDFILE sendfile RECEIVERFILE receiverfile" || ogRaiseError $OG_ERR_FORMAT "1st param: $1" || PERROR=1 #return $?
370
371# 2º param check
372echo "$1" | grep "SEND" > /dev/null && MODE=server || MODE=client
373
374#TODO: diferenciamos los paramatros especificos de la sessión multicast 
375#SI: controlamos todos los parametros de la sessión multicast.
376[ $MODE == "client" ] && SESSIONPARM=1 || SESSIONPARM=6
377OIFS=$IFS; IFS=':' ; SESSION=($2); IFS=$OIFS
378
379
380[[ ${#SESSION[*]} == $SESSIONPARM ]]  || ogRaiseError $OG_ERR_FORMAT "parametros session multicast no completa" || PERROR=2# return $?
381
382
383#controlamos el PORTBASE de la sesion. Comun.-
384PORTBASE=${SESSION[0]}
385ogCheckStringInGroup ${SESSION[0]} "9000 9002 9004 9006 9008 9010" || ogRaiseError $OG_ERR_FORMAT "McastSession portbase ${SESSION[0]}" || PERROR=3 #return $?
386if [ $MODE == "server" ]
387then   
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 $?
389        METHOD=${SESSION[1]}
390        ogCheckIpAddress ${SESSION[2]}  || ogRaiseError $OG_ERR_FORMAT "McastSession address ${SESSION[2]}" || PERROR=5 #return $?
391        ADDRESS=${SESSION[2]}
392        ogCheckStringInReg ${SESSION[3]} "^[0-9]{1,3}\M$" || ogRaiseError $OG_ERR_FORMAT "McastSession bitrate ${SESSION[3]}" || PERROR=6 # return $?
393        BITRATE=${SESSION[3]}
394        ogCheckStringInReg ${SESSION[4]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_FORMAT "McastSession nclients ${SESSION[4]}" || PERROR=7 # return $?
395        NCLIENTS=${SESSION[4]}
396        ogCheckStringInReg ${SESSION[5]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_FORMAT "McastSession maxtime ${SESSION[5]}" || PERROR=8 # return $?
397        MAXTIME=${SESSION[5]}
398fi
399
400#3er param check - que puede ser un dispositvo o un fichero.
401#ogGetPath "$3" > /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $3" || PERROR=9 #return $? 
402DEVICE=$3
403
404#4 y 5 param check .  solo si es sobre particiones.
405if [ "$PARM" == "5" ]
406then
407        # 4 param check
408        ogCheckStringInGroup "$4" "partclone PARTCLONE partimage PARTIMAGE ntfsclone NTFSCLONE" || ogRaiseError $OG_ERR_NOTFOUND " herramienta $4 no soportada" || PERROR=10 #return $?
409        TOOL=$4
410        ogCheckStringInGroup "$5" "lzop LZOP gzip GZIP 0 1" || ogRaiseError $OG_ERR_NOTFOUND " compresor $5 no valido" || PERROR=11 #return $?
411        LEVEL=$5
412fi
413
414
415if [ "$PERROR" != "0" ]; then
416        ogRaiseError $OG_ERR_MCASTSYNTAXT " $PERROR"; return $?
417fi
418
419
420# Valores estandar no configurables.
421CERROR="8x8/128"
422
423# opción del usuo de tuberia intermedia en memoria mbuffer.
424which mbuffer > /dev/null && MBUFFER=" --pipe 'mbuffer -q -m 20M' "
425
426# Generamos la instrucción base de multicast -Envio,Recepcion-
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"
428SYNTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE "
429
430
431case "$1" in
432SENDPARTITION)
433                PROG1=`ogCreateImageSyntax $DEVICE " " $TOOL $LEVEL | awk -F"|" '{print $1 "|" $3}' | tr -d ">"`
434                echo "$PROG1 | $SYNTAXSERVER"
435        ;;
436    RECEIVERPARTITION)
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 "
440        ;;
441        SENDFILE)
442                echo "$SYNTAXSERVER --file $3"
443    ;;
444    RECEIVERFILE)
445                echo "$SYNTAXCLIENT --file $3"
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.
462#@exception $OG_ERR_NOTFOUND
463#@exception OG_ERR_MCASTSENDFILE
464#@note    Requisitos:
465#@version 1.0 - Definición de Protocol.lib
466#@author  Antonio Doblas Viso, Universidad de Málaga
467#@date    2010/05/09
468#*/ ##
469#
470
471function ogMcastSendFile ()
472{
473# Variables locales.
474local ARGS ARG SOURCE TARGET COMMAND DEVICE RETVAL LOGFILE
475
476#LOGFILE="/tmp/mcast.log"
477
478#ARGS usado para controlar ubicación de la sesion multicast
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
491    /*)     # Camino completo.               */ (Comentrio Doxygen)
492        SOURCE=$(ogGetPath "$1")
493        ARG=2
494        DEVICE="$1"
495                ;;
496    [1-9]*) # ndisco npartición.
497        SOURCE=$(ogGetPath "$1" "$2" "$3")
498        ARG=4
499        DEVICE="$1 $2 $3"
500        ;;
501    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
502        SOURCE=$(ogGetPath "$1" "$2")
503        ARG=3
504        DEVICE="$1 $2 "
505        ;;
506esac
507
508
509# Error si no se reciben los argumentos ARG necesarios según la opcion.
510[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
511
512# Comprobar fichero origen
513ogGetPath $SOURCE &> /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $DEVICE not found" || return $? 
514
515# eliminamos ficheros antiguos de log
516#rm $LOGFILE
517
518SESSION=${!ARG}
519
520
521#generamos la instrucción a ejecutar. 
522COMMAND=`ogMcastSyntax "SENDFILE" "$SESSION" "$SOURCE"`
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
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.
546#@exception $OG_ERR_MCASTRECEIVERFILE
547#@note    Requisitos:
548#@version 1.0 - Definición de Protocol.lib
549#@author  Antonio Doblas Viso, Universidad de Málaga
550#@date    2010/05/09
551#*/ ##
552#
553
554function ogMcastReceiverFile ()
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 ]  ]" \
564           "$FUNCNAME 9000 /PS1_PH1.img" \
565           "$FUNCNAME 9000 CACHE /aula1/PS2_PH4.img" \
566           "$FUNCNAME 9000 1 1 /isos/linux.iso"
567    return
568fi
569
570ARGS="$@"
571case "$2" in
572    /*)     # Camino completo.          */ (Comentrio Doxygen)
573        TARGETDIR=$(ogGetParentPath "$2")
574                ARG=2           
575        ;;
576    [1-9]*) # ndisco npartición.
577        TARGETDIR=$(ogGetParentPath "$2" "$3" "$4")
578        ARG=4     
579    ;;
580    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
581        TARGETDIR=$(ogGetParentPath "$2" "$3")
582        ARG=3
583    ;;
584esac
585
586# Error si no se reciben los argumentos ARG necesarios según la opcion.
587[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT "Parametros no admitidos"|| return $?
588
589#obtenemos el nombre del fichero a descargar.
590TARGETFILE=`basename ${!ARG}`
591
592#generamos la instrucción a ejecutar. 
593COMMAND=`ogMcastSyntax RECEIVERFILE "$1" $TARGETDIR/$TARGETFILE `
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
604}
605
606
607#/**
608#         ogMcastSendPartition
609#@brief   Función para enviar el contenido de una partición a multiples particiones remotas.
610#@param 1   disk
611#@param 2  partition
612#@param 3  session multicast
613#@param 4  tool clone
614#@param 5  tool compressor
615#@return
616#@exception OG_ERR_FORMAT
617#@exception OG_ERR_MCASTSENDPARTITION
618#@note
619#@todo: ogIsLocked siempre devuelve 1. crear ticket
620#@version 1.0 - Definición de Protocol.lib
621#@author  Antonio Doblas Viso, Universidad de Málaga
622#@date    2010/05/09
623#*/ ##
624
625function ogMcastSendPartition ()
626{
627
628# Variables locales
629local PART COMMAND RETVAL
630
631# Si se solicita, mostrar ayuda.
632if [ "$*" == "help" ]; then
633    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart SessionMulticastSERVER tools compresor" \
634           "$FUNCNAME 1 1 9000:full-duplex:239.194.37.31:50M:20:2 partclone lzop"
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. 
646COMMAND=`ogMcastSyntax SENDPARTITION "$3" $PART $4 $5`
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
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.
663#@param 1   disk
664#@param 2  partition
665#@param 3  session multicast
666#@param 4  tool clone
667#@param 5  tool compressor
668#@return
669#@exception $OG_ERR_FORMAT
670#@note
671#@todo:
672#@version 1.0 - Definición de Protocol.lib
673#@author  Antonio Doblas Viso, Universidad de Málaga
674#@date    2010/05/09
675#*/ ##
676function ogMcastReceiverPartition ()
677{
678# Variables locales
679local PART COMMAND RETVAL
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. 
696COMMAND=`ogMcastSyntax RECEIVERPARTITION "$3" $PART $4 $5`
697RETVAL=$?
698
699if [ "$RETVAL" -gt "0" ]
700then 
701        return $RETVAL
702else
703        echo $COMMAND
704        eval $COMMAND || ogRaiseError $OG_ERR_MCASTSENDPARTITION " "; return $?
705fi
706
707}
708
709
710##########################################
711############## funciones torrent
712#/**
713#         ogTorrentStart  [ str_repo | int_ndisk int_npart ] Relative_path_file.torrent | SessionProtocol
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.
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
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
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
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
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
737#*/ ##
738
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.
744
745function ogTorrentStart ()
746{
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
760
761case "$1" in
762    /*)     # Camino completo.          */ (Comentrio Doxygen)
763           SOURCE=$(ogGetPath "$1")
764           ARG=2
765     ;;
766    [1-9]*) # ndisco npartición.
767           SOURCE=$(ogGetPath "$1" "$2" "$3")
768           ARG=4
769     ;;
770    *) # Otros: Solo cache (no se permiten caminos relativos).
771        SOURCE=$(ogGetPath "$1" "$2" 2>/dev/null)
772        ARG=3
773     ;;
774esac
775
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 $?
795
796TARGET=`echo $SOURCE | awk -F.torrent '{print $1}'`
797DIRSOURCE=`ogGetParentPath $SOURCE`
798cd $DIRSOURCE
799
800
801
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
815#SYNTAXSEEDER="echo MODE seeder ctorrent ; (sleep \$TIME && kill -9 \`pidof ctorrent\`) & ; ctorrent \${SOURCE}"
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} ]
819then
820  echo "imagen ya descargada"
821  case "$MODE" in
822        seeder|SEEDER)
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}           
826  esac
827  return 0
828fi
829
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
842fi
843
844if [ "$OPTION" == "DOWNLOAD" ]
845then
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"
849            ctorrent -f -X "sleep 15; kill -2 \$(pidof ctorrent)" -C 100 ${SOURCE} -s ${TARGET} -b ${SOURCE}.bf
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
861cd /tmp
862}
863
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
884function ogCreateTorrent ()
885{
886# Variables locales.
887local ARGS ARG SOURCE EXT IPTORRENT
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).
911        EXT=$(ogGetImageType "$1" "$2")
912        SOURCE=$(ogGetPath "$1" "$2.$EXT")
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
922[ $SOURCE ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
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
935#/**
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
942#@note
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
947#@date
948#*/ ##
949function ogUpdateCacheIsNecesary ()
950{
951
952# Variables locales.
953local ERROR SOURCE CACHE FILESOURCE MD5SOURCE FILETARGET MD5TARGET
954ERROR=0
955
956# Si se solicita, mostrar ayuda.
957if [ "$*" == "help" ]; then
958    ogHelp "$FUNCNAME $FUNCNAME [ str_repo] [ [Relative_path_image] " \
959           "$FUNCNAME REPO /PS1_PH1.img" \
960           "$FUNCNAME REPO /ogclient.sqfs"
961           
962    return
963fi
964
965#TODO:  return 0->true, 1->false; si error, aunque sintaxis devuelve > 1
966
967# Error si no se reciben los argumentos ARG necesarios según la opcion.
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 $?
970
971[ $# == "2" ] || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?)
972ogCheckStringInGroup "$1" "REPO repo" || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?)
973
974
975FILESOURCE=`ogGetPath $1 $2` || return $(ogRaiseError $OG_ERR_NOTFOUND " $1 $2"; echo $?)
976
977#echo "paso 1. si no existe la imagen, confirmamos que es necesaria la actualizacion de la cache."
978FILETARGET=`ogGetPath CACHE $2`
979if [ -z $FILETARGET ]
980then
981        # borramos el fichero bf del torrent, en el caso de que se hubiese quedado de algun proceso fallido
982        ogDeleteFile CACHE "/$2.torrent.bf" &> /dev/null
983        ogDeleteFile CACHE "/$2.sum" &> /dev/null
984        echo "TRUE=0, es necesario actualizar. Paso 1, la cache no contiene esa imagen "
985        return 0
986fi
987
988#echo "Paso 2. Comprobamos que la imagen no estuviese en un proceso previo torrent"
989if ogGetPath $FILETARGET.torrent.bf  > /dev/null
990then
991    #TODO: comprobar los md5 para asegurarnos que la imagen es la misma.
992    echo "TRUE=0, es necesario actualizar. Paso 2, la imagen esta en un estado de descarga torrent interrumpido"
993    return 0
994fi
995
996
997## En este punto la imagen en el repo y en la cache se llaman igual,
998#echo "paso 4. recuperamos o calculamos los md5 de los ficheros"
999if [ -f $FILESOURCE.sum ]
1000then
1001        MD5SOURCE=$(cat $FILESOURCE.sum)
1002else
1003        MD5SOURCE=$(ogCalculateChecksum $FILESOURCE)
1004fi
1005[ ! -f $FILETARGET.sum ] && ogCalculateChecksum $FILETARGET > $FILETARGET.sum
1006MD5TARGET=$(cat $FILETARGET.sum)
1007
1008#echo "Paso 5. comparamos los md5"
1009#TODO: que hacer cuando los md5 son distintos. Por defecto borrar.
1010if [ "$MD5SOURCE" == "$MD5TARGET" ]
1011then
1012        echo "FALSE=1, No es neceario actualizar. Paso5.A la imagen esta en cache"
1013        return 1
1014else
1015    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"
1016        rm -f $FILETARGET
1017        return 0
1018fi
1019
1020}
1021
1022
1023
Note: See TracBrowser for help on using the repository browser.