source: client/engine/Protocol.lib @ dd08d02

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 dd08d02 was bd390f1, checked in by adv <adv@…>, 15 years ago

trunk engine Protocol.lib control parámetros funciones multicast

git-svn-id: https://opengnsys.es/svn/trunk@1014 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100644
File size: 28.0 KB
Line 
1#!/bin/bash
2#/**
3#@file    Protocol.lib
4#@brief   Librería o clase Protocol
5#@class   FileTransfer
6#@brief   Funciones para transmisión de datos
7#@version 0.91
8#@warning License: GNU GPLv3+
9#*/
10
11
12#/**
13#         ogCheckStringInGroup
14#@brief   Función para determinar si el elemento pertenece a un conjunto
15#@param 1 elemento a comprobar
16#@param 2 grupo de elementos para comprobar tipo "valor1 valor2 valor3"
17#@return  0 si pertenece al grupo
18#@return  1 si NO pertenece al grupo
19#@exception OG_ERR_FORMAT     formato incorrecto.
20#@note   
21#@TODO:
22#@version 0.91 - Definición de
23#@author  Antonio Doblas Viso, Universidad de Málaga
24#@date    2010/05/09
25#*/ ##
26#/**
27ogCheckStringInGroup ()
28{
29# Si se solicita, mostrar ayuda.
30if [ "$*" == "help" ]; then
31    ogHelp "$FUNCNAME str_elemento    str_grupo" \
32                   "$FUNCNAME full-duplex \"full-duplex half-duplex broadcast\" "
33    return
34fi
35
36# Error si no se recibe 2 parámetro.
37[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
38
39
40for i in `echo $2`
41do
42  if [ "$1" == "$i" ]
43  then
44      return 0
45  fi
46done
47
48return 1
49}
50
51#/**
52#         ogCheckStringInReg
53#@brief   Función para determinar si el elemento contiene una "expresión regular"
54#@param 1 elemento a comprobar
55#@param 2 expresión regular"
56#@return  0 si coincide con la expresión
57#@return  1 si NO coincide con la expresión
58#@exception OG_ERR_FORMAT     formato incorrecto.
59#@note   
60#@TODO:
61#@version 0.91 - Definición de
62#@author  Antonio Doblas Viso, Universidad de Málaga
63#@date    2010/05/09
64#*/ ##
65#/**
66
67
68ogCheckStringInReg()
69{
70
71local REG
72
73# Si se solicita, mostrar ayuda.
74if [ "$*" == "help" ]; then
75    ogHelp "$FUNCNAME str_elemento    str_expresión_regular" \
76                   "$FUNCNAME 50M \"^[0-9]{1,2}\M$\" "
77    return
78fi
79
80# Error si no se recibe 2 parámetro.
81[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
82
83REG=$2
84[[ $1 =~ $REG ]] && return 0 || return 1
85}
86
87
88
89#/**
90#         ogCheckIpAddress
91#@brief   Función para determinar si una cadena es una dirección ipv4 válida
92#@param 1 string de la ip a comprobar
93#@return  0 si es una dirección válida
94#@return  1 si NO es una dirección válida
95#@exception OG_ERR_FORMAT     formato incorrecto.
96#@note   
97#@TODO:
98#@version 0.91 - Definición de
99#@author  Antonio Doblas Viso, Universidad de Málaga
100#@date    2010/05/09
101#*/ ##
102#/**
103ogCheckIpAddress()
104{
105local REG IP arrIP
106
107# Si se solicita, mostrar ayuda.
108if [ "$*" == "help" ]; then
109    ogHelp "$FUNCNAME str_IpAddressToCheck" \
110                   "$FUNCNAME 192.18.35.3"
111    return
112fi
113
114# Error si no se recibe 1 parámetro.
115[ $# == 1 ] || ogRaiseError $OG_ERR_FORMAT || return $?
116   
117   
118IP=$1
119REG="^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
120if [[ "$IP" =~ $REG ]]
121then           
122        OIFS=$IFS;
123    IFS='.' ;
124    arrIP=($IP) 
125    IFS=$OIFS           
126    if [[ ${arrIP[0]} -le 255 && ${arrIP[1]} -le 255 && ${arrIP[2]} -le 255 && ${arrIP[3]} -le 255 ]]
127    then
128        return 0
129    fi
130fi
131return 1
132}
133
134
135
136#/**
137#         ogGenerateSintaxMcast
138#@brief   Función para generar la instrucción de ejucción la transferencia de datos multicast
139#@param 1 Tipo de operación [ SENDPARTITION RECEIVERPARTITION SENDFILE RECEIVERFILE ]
140#@param 2 Sesión Mulicast
141#@param 3 Dispositivo (opción PARTITION) o fichero(opción FILE) que será enviado.
142#@param 4 Tools de clonación (opcion PARTITION)
143#@param 5 Tools de compresion (opcion PARTITION)
144#@return  instrucción para ser ejecutada.
145#@exception OG_ERR_FORMAT     formato incorrecto.
146#@note    Requisitos: upd-cast 2009
147#@TODO: localvar  check versionudp
148#@version 0.91 - Definición de FileTransfer
149#@author  Antonio Doblas Viso, Universidad de Málaga
150#@date    2010/05/09
151#*/ ##
152#/**
153#         
154
155
156function ogGenerateSintaxMcast ()
157{
158
159local ISUDPCAST PARM SESSION SESSIONPARM MODE PORTBASE
160local METHOD ADDRESS BITRATE NCLIENTS MAXTIME CERROR
161local TOOL LEVEL DEVICE MBUFFER SINTAXSERVER SINTAXCLIENT
162
163# Si se solicita, mostrar ayuda.
164if [ "$*" == "help" -o "$2" == "help" ]; then
165    ogHelp "$FUNCNAME SENDPARTITION      str_sessionSERVER     str_device str_tools str_level" \
166                   "$FUNCNAME RECEIVERPARTITION  str_sessionCLIENT     str_device str_tools str_level "\
167                   "$FUNCNAME SENDFILE           str_sessionSERVER     str_file "\
168                   "$FUNCNAME RECEIVERFILE       str_sessionCLIENT     str_file "
169    return
170fi
171
172#si no tenemos updcast o su version superior 2009 udpcast error.
173ISUDPCAST=$(udp-receiver --help 2>&1)
174echo $ISUDPCAST | grep start-timeout > /dev/null || ogRaiseError $OG_ERR_FORMAT "upd-cast no existe o version antigua -requerida 2009-"|| return $?
175
176
177# Error si no se reciben $PARM parámetros.
178echo "$1" | grep "PARTITION" > /dev/null && PARM=5 || PARM=3
179[ "$#" -eq "$PARM" ] || ogRaiseError $OG_ERR_FORMAT "sin parametros"|| return $?
180
181
182# 1er param check
183ogCheckStringInGroup "$1" "SENDPARTITION RECEIVERPARTITION SENDFILE RECEIVERFILE" || ogRaiseError $OG_ERR_FORMAT "1st param: $1" || ERROR=1 #return $?
184
185# 2º param check
186echo "$1" | grep "SEND" > /dev/null && MODE=server || MODE=client
187
188#TODO: diferenciamos o no????
189#controlamos todos los parametros de la sessión multicast.
190#Dejo para el cliente como 6, pero solo necesita el primero.
191[ $MODE == "client" ] && SESSIONPARM=6 || SESSIONPARM=6
192OIFS=$IFS; IFS=':' ; SESSION=($2); IFS=$OIFS
193[[ ${#SESSION[*]} == $SESSIONPARM ]]  || ogRaiseError $OG_ERR_FORMAT "parametros session multicast no completa" || ERROR=1# return $?
194#controlamos el PORTBASE de la sesion. Comun.-
195PORTBASE=${SESSION[0]}
196ogCheckStringInGroup ${SESSION[0]} "9000 9002 9004 9006 9008 9010" || ogRaiseError $OG_ERR_FORMAT "McastSession portbase ${SESSION[0]}" || ERROR=1 #return $?
197if [ $MODE == "server" ]
198then   
199        ogCheckStringInGroup ${SESSION[1]} "full-duplex half-duplex broadcast" || ogRaiseError $OG_ERR_FORMAT "McastSession method ${SESSION[1]}" || ERROR=1 #return $?
200        METHOD=${SESSION[1]}
201        ogCheckIpAddress ${SESSION[2]}  || ogRaiseError $OG_ERR_FORMAT "McastSession address ${SESSION[2]}" || ERROR=1 #return $?
202        ADDRESS=${SESSION[2]}
203        ogCheckStringInReg ${SESSION[3]} "^[0-9]{1,2}\M$" || ogRaiseError $OG_ERR_FORMAT "McastSession bitrate ${SESSION[3]}" || ERROR=1 # return $?
204        BITRATE=${SESSION[3]}
205        ogCheckStringInReg ${SESSION[4]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_FORMAT "McastSession nclients ${SESSION[4]}" || ERROR=1 # return $?
206        NCLIENTS=${SESSION[4]}
207        ogCheckStringInReg ${SESSION[5]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_FORMAT "McastSession maxtime ${SESSION[5]}" || ERROR=1 # return $?
208        MAXTIME=${SESSION[5]}
209fi
210
211
212
213#3er param check - que puede ser un dispositvo o un fichero.
214#ogGetPath "$3" > /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $3" || ERROR=1 #return $? 
215DEVICE=$3
216
217#4 y 5 param check .  solo si es sobre particiones.
218if [ "$PARM" == "5" ]
219then
220        # 4 param check
221        ogCheckStringInGroup "$4" "partclone partimage ntfsclone" || ogRaiseError $OG_ERR_NOTFOUND " herramienta $4 no soportada" || ERROR=1 #return $?
222        TOOL=$4
223        ogCheckStringInGroup "$5" "lzop gzip 0 1" || ogRaiseError $OG_ERR_NOTFOUND " compresor $5 no valido" || ERROR=1 #return $?
224        LEVEL=$5
225fi
226
227[ "$ERROR" == "1" ] && return 1
228
229# Valores estandar no configurables.
230CERROR="8x8/128"
231
232# opción del usuo de tuberia intermedia en memoria mbuffer.
233which mbuffer > /dev/null && MBUFFER=" --pipe 'mbuffer -m 20M' "
234
235# Generamos la instrucción base de multicast -Envio,Recepcion-
236SINTAXSERVER="udp-sender $MBUFFER --portbase $PORTBASE --$METHOD --mcast-data-address $ADDRESS --fec $CERROR --max-bitrate $BITRATE --ttl 1 --min-clients $NCLIENTS --max-wait $MAXTIME "
237SINTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE "
238
239
240case "$1" in
241   SENDPARTITION)
242        PROG1=`ogGenerateSintaxForCreateImage $DEVICE " " $TOOL $LEVEL | awk -F"|" '{print $1 "|" $3}' | tr -d ">"`
243                echo "$PROG1 | $SINTAXSERVER"
244        ;;
245    RECEIVERPARTITION)
246                COMPRESSOR=`ogGenerateSintaxForRestoreImage " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $1}'`
247                TOOLS=`ogGenerateSintaxForRestoreImage " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $3}'`
248                echo "$SINTAXCLIENT | $COMPRESSOR | $TOOLS "
249        ;;
250        SENDFILE)
251                echo "$SINTAXSERVER --file $3"
252    ;;
253    RECEIVERFILE)
254                echo "$SINTAXCLIENT --file $3"
255    ;;
256   *)
257   ;;
258esac
259}
260
261
262
263#/**
264#         ogMcastSendFile [ str_repo | int_ndisk int_npart ] /Relative_path_file  sessionMulticast
265#@brief   Envía un fichero por multicast   ORIGEN(fichero) DESTINO(sessionmulticast)
266#@param (2 parámetros)  $1 path_aboluto_fichero  $2 sesionMcast
267#@param (3 parámetros)  $1 Contenedor REPO|CACHE $2 path_absoluto_fichero $3 sesionMulticast
268#@param (4 parámetros)  $1 disk $2 particion $3 path_absoluto_fichero $4 sesionMulticast
269#@return 
270#@exception OG_ERR_FORMAT     formato incorrecto.
271#@note    Requisitos:
272#@version 0.91 - Definición de Protocol.lib
273#@author  Antonio Doblas Viso, Universidad de Málaga
274#@date    2010/05/09
275#*/ ##
276#/**
277#
278
279function ogMcastSendFile ()
280{
281# Variables locales.
282local ARGS SOURCE TARGET COMMAND DEVICE
283#ARGS usado para controlar ubicación de la sesion multicast
284
285# Si se solicita, mostrar ayuda.
286if [ "$*" == "help" ]; then
287    ogHelp "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] /Relative_path_file sesionMcast" \
288           "$FUNCNAME  1 1 /aula1/winxp.img sesionMcast" \
289           "$FUNCNAME  REPO /aula1/ubuntu.iso sesionMcast" \
290           "$FUNCNAME  CACHE /aula1/winxp.img sesionMcast" \
291           "$FUNCNAME  /opt/opengnsys/images/aula1/hd500.vmx sesionMcast"
292    return
293fi
294
295ARGS="$@"
296case "$1" in
297    /*)     # Camino completo.               */ (Comentrio Doxygen)
298        SOURCE=$(ogGetPath "$1")
299        ARG=2
300        DEVICE="$1"
301                ;;
302    [1-9]*) # ndisco npartición.
303        SOURCE=$(ogGetPath "$1" "$2" "$3")
304        ARG=4
305        DEVICE="$1 $2 $3"
306        ;;
307    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
308        SOURCE=$(ogGetPath "$1" "$2")
309        ARG=3
310        DEVICE="$1 $2 "
311        ;;
312esac
313
314
315# Error si no se reciben los argumentos ARG necesarios según la opcion.
316[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
317
318# Comprobar fichero origen
319ogGetPath $SOURCE &> /dev/null || ogRaiseError $OG_ERR_NOTFOUND " device or file $DEVICE not found" || return $? 
320
321SESSION=${!ARG}
322# llamando a la funcion con param1 session $SESSION y param2 $SOURCE
323COMMAND=`ogGenerateSintaxMcast "SENDFILE" "$SESSION" "$SOURCE"`
324echo $COMMAND
325eval $COMMAND
326}
327
328
329
330#/**
331#         ogMcastReceiverFile  sesion Multicast [ str_repo | int_ndisk int_npart ] /Relative_path_file
332#@brief   Recibe un fichero multicast   ORIGEN(sesionmulticast) DESTINO(fichero)
333#@param (2 parámetros)  $1 sesionMcastCLIENT $2 path_aboluto_fichero_destino 
334#@param (3 parámetros)  $1 sesionMcastCLIENT $2 Contenedor REPO|CACHE $3 path_absoluto_fichero_destino
335#@param (4 parámetros)  $1 sesionMcastCLIENT $2 disk $3 particion $4 path_absoluto_fichero_destino
336#@return 
337#@exception OG_ERR_FORMAT     formato incorrecto.
338#@note    Requisitos:
339#@version 0.91 - Definición de Protocol.lib
340#@author  Antonio Doblas Viso, Universidad de Málaga
341#@date    2010/05/09
342#*/ ##
343#/**
344#
345
346ogMcastReceiverFile ()
347{
348
349# Variables locales.
350local ARGS ARG TARGETDIR TARGETFILE
351
352
353# Si se solicita, mostrar ayuda.
354if [ "$*" == "help" ]; then
355    ogHelp "$FUNCNAME" "$FUNCNAME [ str_portMcast] [ [Relative_path_file] | [str_REPOSITORY path_file] |  [int_ndisk int_npart path_file ]  ]" \
356           "$FUNCNAME 9000 /PS1_PH1.img" \
357           "$FUNCNAME 9000 CACHE /aula1/PS2_PH4.img" \
358           "$FUNCNAME 9000 1 1 /isos/linux.iso"
359    return
360fi
361
362ARGS="$@"
363case "$2" in
364    /*)     # Camino completo.          */ (Comentrio Doxygen)
365        TARGETDIR=$(ogGetParentPath "$2")
366                ARG=2           
367        ;;
368    [1-9]*) # ndisco npartición.
369        TARGETDIR=$(ogGetParentPath "$2" "$3" "$4")
370        ARG=4     
371    ;;
372    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
373        TARGETDIR=$(ogGetParentPath "$2" "$3")
374        ARG=3
375    ;;
376esac
377
378# Error si no se reciben los argumentos ARG necesarios según la opcion.
379[ $# == "$ARG" ] || ogRaiseError $OG_ERR_FORMAT "Parametros no admitidos"|| return $?
380
381#obtenemos el nombre del fichero a descargar.
382TARGETFILE=`basename ${!ARG}`
383
384#generamos la instrucción a ejecutar. 
385COMMAND=`ogGenerateSintaxMcast RECEIVERFILE "$1" $TARGETDIR/$TARGETFILE `
386echo $COMMAND
387eval $COMMAND
388}
389
390
391
392
393
394##########################################
395############## funciones torrent
396
397#/**
398#         ogCreateTorrent  [ str_repo | int_ndisk int_npart ] Relative_path_file
399#@brief   Función para crear el fichero torrent.
400#@param   str_pathDirectory  str_Relative_path_file
401#@param  int_disk    int_partition   str_Relative_path_file
402#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
403#@return
404#@exception OG_ERR_FORMAT    Formato incorrecto.
405#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
406#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
407#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
408#@note
409#@version 0.1 - Integración para OpenGNSys.
410#@author        Antonio J. Doblas Viso. Universidad de Málaga
411#@date
412#@version 0.2 - Integración para btlaunch.
413#@author        Irina . Univesidad de Sevilla.
414#@date
415#*/ ##
416
417ogCreateTorrent ()
418{
419# Variables locales.
420local ARGS ARG SOURCE IPTORRENT
421
422
423# Si se solicita, mostrar ayuda.
424if [ "$*" == "help" ]; then
425    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file IpBttrack" \           "$FUNCNAME 1 1 /aula1/winxp 10.1.15.23" \
426       "$FUNCNAME REPO /aula1/winxp 10.1.15.45"
427
428    return
429fi
430
431# Error si se quiere crear el fichero en cache y no existe
432[ "$1" != "CACHE" ] || `ogFindCache >/dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE"|| return $?
433
434case "$1" in
435    /*)     # Camino completo.          */ (Comentrio Doxygen)
436           SOURCE=$(ogGetPath "$1.img")
437        ARG=2
438                ;;
439    [1-9]*) # ndisco npartición.
440           SOURCE=$(ogGetPath "$1" "$2" "$3.img")
441        ARG=4
442        ;;
443    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
444           SOURCE=$(ogGetPath "$1" "$2.img")
445        ARG=3
446        ;;
447esac
448
449# Error si no se reciben los argumentos ARG necesarios según la opcion.
450[ $# -eq "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
451
452
453# Error si no existe la imagen
454[ $SOURCE ] ||  ogRaiseError $OG_ERR_NOTFOUND || return $?
455
456[ -r $SOURCE.torrent ] && mv "$SOURCE.torrent" "$SOURCE.torrent.ant" && echo "Esperamos que se refresque el servidor" && sleep 20
457
458IPTORRENT="${!#}"
459# Si ponemos el path completo cuando creamos el fichero torrent da error
460cd `dirname $SOURCE`
461echo ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
462ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
463
464}
465
466
467#/**
468#         ogTorrentStart  [ str_repo | int_ndisk int_npart ] Relative_path_file | SessionProtocol
469#@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.
470#@param   str_pathDirectory  str_Relative_path_file
471#@param  int_disk    int_partition   str_Relative_path_file
472#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
473#@return
474#@note
475#@todo:
476#@version 0.1 - Integración para OpenGNSys.
477#@author        Antonio J. Doblas Viso. Universidad de Málaga
478#@date
479#@version 0.2 - Chequeo del tamaño de imagen descargado.
480#@author        Irina . Univesidad de Sevilla.
481#@date
482#@version 0.3 - Control de los modos de operación, y estado de descarga.
483#@author        Antonio J. Doblas Viso. Univesidad de Málaga.
484#@date
485#*/ ##
486#Lee el fichero torrent y descarga o comparte el fichero destino en el mismo subdirectorio.
487# Parametros para el orgien del fichero file.df.torrent
488# 1 camino completo al fichero
489# 1 2   Contenedor /fichero relativo
490# 1 2 3  disco particion y /fichero relativo.
491#protocoloTORRENT    mode:time
492# posicion 2, 3, 4
493#mode=seeder  -> Dejar el equipo seedeando hasta que transcurra el tiempo indicado o un kill desde consola,
494#mode=peer    -> seedear mientras descarga
495#mode=leecher  -> NO seedear mientras descarga
496#time tiempo que una vez descargada la imagen queremos dejar al cliente como seeder.
497
498ogTorrentStart ()
499{
500#TODO ayuda
501#TODO: control parametros.
502
503case "$1" in
504    /*)     # Camino completo.          */ (Comentrio Doxygen)
505           SOURCE=$(ogGetPath "$1")
506           ARG=1
507           SESSION=$2
508     ;;
509    [1-9]*) # ndisco npartición.
510           SOURCE=$(ogGetPath "$1" "$2" "$3")
511           ARG=3
512           SESSION=$4
513     ;;
514    *) # Otros: repo, cache, cdrom (no se permiten caminos relativos).
515        SOURCE=$(ogGetPath "$1" "$2" 2>/dev/null)
516        ARG=2
517        SESSION=$3
518        ;;
519esac
520
521ctorrent -x ${SOURCE}; [ $? -eq 0 ] ||  ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
522
523TARGET=`echo $SOURCE | awk -F.torrent '{print $1}'`
524DIRSOURCE=`ogGetParentPath $SOURCE`
525cd $DIRSOURCE
526
527#analizando SESSION
528MODE=`echo $SESSION | cut -f1 -d:`
529TIME=`echo $SESSION | cut -f2 -d:`
530
531
532#echo $MODE $TIME
533#echo ${SOURCE}.bf  ${TARGET}
534
535# si No fichero .bf, y Si fichero destino    imagen ya descargada y su chequeo fue comprobado en su descarga inicial.
536if [ ! -f ${SOURCE}.bf -a -f ${TARGET} ]
537then
538  echo "imagen ya descargada"
539  case "$MODE" in
540        seeder|SEEDER)
541                (sleep $TIME && kill -9 `pidof ctorrent`) &
542                echo "MODE seeder ctorrent ${SOURCE} -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100"
543                ctorrent ${SOURCE}
544  esac
545  return 0
546fi
547
548#Si no existe bf ni fichero destino         descarga inicial.
549if [ ! -f ${SOURCE}.bf -a ! -f ${TARGET} ]
550then
551        OPTION=DOWNLOAD
552    echo "descarga inicial"
553fi
554
555# Si fichero bf           descarga anterior no completada -.
556if [ -f ${SOURCE}.bf -a -f ${TARGET} ]
557then       
558        echo Continuar con Descargar inicial no terminada.
559        OPTION=DOWNLOAD
560fi
561
562case "$OPTION" in
563        download|DOWNLOAD)
564        if [ "$MODE" == "peer" ]
565        then
566                        echo "ctorrent -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100 $SOURCE -s $TARGET -b ${SOURCE}.bf"
567            ctorrent -f -X "sleep $TIME; kill -9 \$(pidof ctorrent)" -C 100 ${SOURCE} -s ${TARGET} -b ${SOURCE}.bf
568        fi
569
570        if [ "$MODE" == "leecher" ]
571        then
572          echo "ctorrent ${SOURCE} -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100 -U 0"
573          ctorrent ${SOURCE} -X "sleep $TIME; kill -9 \$(pidof ctorrent)" -C 100 -U 0
574        fi
575;;
576esac
577
578if [ "$OPTION" == "DOWNLOAD" ]
579then
580        echo "comprobando el fichero descargado"
581        echo " ctorrent -s $TARGET -c $SOURCE | tail -n1 | cut -f2 -d\( "
582        TOTAL=`ctorrent -s $TARGET -c $SOURCE | tail -n1 | cut -f2 -d\(`
583        if [ "$TOTAL" == "100%)" ]
584        then
585         return 0
586        else
587         return 1
588        fi
589 
590 fi
591 
592cd /tmp
593}
594
595
596
597############################################################
598##################### FUNCIONES MULTICAST EN DESARROLLO ##########
599
600
601#/**
602#         ogMcastSessionCheck [session]
603#@brief   Controla los parámetros de una sessión multicast
604#@param   str_session   
605#@return  (nada, por determinar)
606#@exception OG_ERR_FORMAT     formato incorrecto.
607#@note    Requisitos:
608#@version 0.91 - Definición de FileTransfer
609#@author  Antonio Doblas Viso, Universidad de Málaga
610#@date    2010/05/09
611#*/ ##
612ogMcastSessionCheck ()
613{
614echo "en pruebas"
615#sessionSERVER  PORTBASE:METHOD:ADDRESS:BITRATE:NCLINTS:MAXTIME:TOOLCLONE:COMPRESSOR
616#sessionCLIENT  PORTBASE:TOOLCLONE:COMPRESSOR
617#PORTBASE: 9000 (incluye el 9001), 9002 (incluye el 9003), 9004
618#METHOD: full-duplex half-duplex brodcast
619#ADDRESS: Dirección habilitada para la transferencia. 339.194.ip2.ip3
620#BITRATE: 90M   80M   70M
621#NCLIENTS:
622#MAXTIME:
623#TOOLCLONE:
624#COMPRESSOR:
625}
626
627
628#/**
629#         ogMcastSessionList
630#@brief   Lista las sessiones abiertas multicast.
631#@param   (en pruebas)
632#@return  (nada, por determinar)
633#@exception OG_ERR_FORMAT     formato incorrecto.
634#@note    Requisitos:
635#@version 0.91 - Definición de FileTransfer
636#@author  Antonio Doblas Viso, Universidad de Málaga
637#@date    2010/05/09
638#*/ ##
639ogMcastSessionList()
640{
641echo "en preubas"
642#puertos a utilizar 9000 - 9008 => se definen 10 sesiones
643#lsof -i -nP | grep 900 | awk '{print $9}' | awk -F: '{print $2}' | uniq
644}
645
646#/**
647#         ogMcastSessionDelete
648#@brief   Libera una session Mulitcast.
649#@param   (en pruebas)
650#@return  (nada, por determinar)
651#@exception OG_ERR_FORMAT     formato incorrecto.
652#@note    Requisitos:
653#@version 0.91 - Definición de FileTransfer
654#@author  Antonio Doblas Viso, Universidad de Málaga
655#@date    2010/05/09
656#*/ ##
657ogMcastSessionDelete()
658{
659echo "en pruebas"
660}
661
662#/**
663#         ogMcastSendPartition
664#@brief   Función para enviar el contenido de una partición a multiples particiones remotas.
665#@param
666#@param
667#@param
668#@return
669#@exception
670#@note
671#@todo:
672#@version 0.1 - Integración para OpenGNSys.
673#@author
674#@date
675#*/ ##
676
677ogMcastSendPartition ()
678{
679
680# Variables locales
681local PART  ERRCODE
682
683# Si se solicita, mostrar ayuda.
684if [ "$*" == "help" ]; then
685    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart " \
686           "$FUNCNAME 1 1 "
687    return
688fi
689# Error si no se reciben 2 parámetros.
690[ $# -lt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
691
692PART=$(ogDiskToDev "$1" "$2") || return $?
693if ogIsLocked $1 $2; then
694    ogRaiseError $OG_ERR_LOCKED "$1,$2"
695    return $?
696fi
697
698
699echo "en pruebas"
700
701}
702
703
704#/**
705#         ogMcastRestorePartition
706#@brief   Función para recibir directamente en la partición el contenido de un fichero imagen remoto enviado por multicast.
707#@param
708#@param
709#@param
710#@return
711#@exception
712#@note
713#@todo:
714#@version 0.1 - Integración para OpenGNSys.
715#@author
716#@date
717#*/ ##
718ogMcastRestorePartition ()
719{
720echo "en pruebas"
721}
722
723########################## FUNCIONES TORRENT EN DESARROLLO
724##################################################
725#/**
726#         ogStartTracker
727#@brief   Inicia el tracker
728#@param   str_pathDirectory  str_Relative_path_file
729#@param  int_disk    int_partition   str_Relative_path_file
730#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
731#@return
732#@exception OG_ERR_FORMAT    Formato incorrecto.
733#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
734#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
735#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
736#@note
737#@version 0.1 - Integración para OpenGNSys.
738#@author
739#@date
740#*/ ##
741ogStartTracker ()
742{
743        echo " bug2: usar el tracker del bittornado. "
744        echo " solucion bug2: apt-get autoremove bittorrent python-bittorrent "
745        echo "soulución bug2: apt-get install bittornado. "
746        echo "#Paso 2: iniciar track "
747local TESTBTT
748TESTBTT=`ps aux | grep bttrack | egrep -v grep | wc -l`
749if [ "$TESTBTT" == "0" ]; then
750        bttrack --reannounce_interval 10 --port 6969 --dfile /root/dstate --logfile /root/bttracker.log --save_dfile_interval 10 --timeout_downloaders_interval 10 2>/dev/null &
751else
752        echo "bttrack iniciado"
753fi
754
755}
756
757ogShareTorrent ()
758{
759# Variables locales.
760local ARGS SOURCE TARGET
761
762
763# Si se solicita, mostrar ayuda.
764if [ "$*" == "help" ]; then
765    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
766           "$FUNCNAME 1 1 /aula1/winxp" \
767           "$FUNCNAME REPO /aula1/winxp"
768
769    return
770fi
771
772# Error si se quiere compartir un fichero en cache y no existe la cache
773[ "$1" != "CACHE" ] || `ogFindCache >/dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE"|| return $?
774
775case "$1" in
776    /*)     # Camino completo.          */ (Comentrio Doxygen)
777           SOURCE=$(ogGetPath "$1.img")
778           ARG=1
779                ;;
780    [1-9]*) # ndisco npartición.
781           SOURCE=$(ogGetPath "$1" "$2" "$3.img")
782        ARG=3
783        ;;
784    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
785           SOURCE=$(ogGetPath "$1" "$2.img" 2>/dev/null)
786        ARG=2
787        ;;
788esac
789
790
791# Error si no se reciben los argumentos ARG necesarios según la opcion.
792[ $# -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
793
794# Comprobar fichero origen
795[ -n "$SOURCE.torrent" ] || ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
796
797echo ctorrent $SOURCE.torrent -d
798ctorrent $SOURCE.torrent -d
799
800}
801
802
803ogTorrentReceiverFile ()
804{
805# obligatorio disponer de cache
806# origen destino.
807#origen es el .torrent
808# origen: REPO /file.torrent
809# Si REPO, (nfs, http) copiamos a CACHE.
810
811# destino es el fichero final.
812# destino: CACHE /file
813# destino: disk part /file
814
815# Variables locales.
816    local ARGS ARG SOURCEDIR SOURCEFILE TARGETDIR TARGETFILE
817
818# Si se solicita, mostrar ayuda.
819if [ "$*" == "help" ]; then
820    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
821           "$FUNCNAME REPO /aula1/winxp.torrent CACHE /aula1/winxp" \
822           "$FUNCNAME REPO /aula1/winxp.torrent 1 1 /iso"
823fi
824# Comprobamos que existe Cache
825`ogFindCache > /dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE" || return $?
826
827# guardamos torrent. controlamos tamaño del fichero y comprobamos con cache.
828ogCopyFile $1 $2 $3 $4
829
830
831}
832
833ogReceiveTorrent ()
834{
835# Variables locales.
836    local ARGS ARG TARGETDIR TARGETFILE
837
838
839
840# Si se solicita, mostrar ayuda.
841if [ "$*" == "help" ]; then
842    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
843           "$FUNCNAME 1 1 /aula1/winxp" \
844           "$FUNCNAME REPO /aula1/winxp" \
845           "$FUNCNAME /mnt/sda2/winxp"
846
847
848    return
849fi
850
851# Comprobamos que existe Cache
852`ogFindCache > /dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE" || return $?
853
854ARGS="$*"
855case "$1" in
856    /*)     # Camino completo.          */ (Comentrio Doxygen)
857    TARGETDIR=$(ogGetParentPath "$1")
858        ARG=1
859                ;;
860    [1-9]*) # ndisco npartición.
861    TARGETDIR=$(ogGetParentPath "$1" "$2" "$3")
862        ARG=3
863        ;;
864    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
865    TARGETDIR=$(ogGetParentPath "$1" "$2")
866        ARG=2
867        ;;
868esac
869#echo $TARGETDIR
870
871# Error si no se reciben los argumentos ARG necesarios según la opcion.
872[ "$#" -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
873
874#obtenemos el nombre del fichero a descargar.
875TARGETFILE=`basename ${!ARG}`
876CACHE=`ogMountCache`
877
878# Error si no existe el fichero torrent
879[ -r $TARGETDIR/$TARGETFILE.img.torrent ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
880[ -d ${CACHE}/$OGIMG ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
881
882TimeToWaitForCloseAfterDownload=20  # tiempo que deseamos que el cliente este como semilla, despues de la descarga.
883
884# Si el fichero ya se ha bajado antes de iniciar el ctorrent no se ejecuta el comando kill, siguen encendido siempre
885# Comprobamos si se ha descargado antes, si es asi nos salimos
886Total=`ctorrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -c $TARGETDIR/$TARGETFILE.img.torrent|tail -n1|cut -f2 -d\(`
887[ $Total == "100%)" ] &&  return 0
888
889echo "ctorrent -X 'sleep $TimeToWaitForCloseAfterDownload; kill -9 \$(pidof ctorrent)' $TARGETDIR/$TARGETFILE.img.torrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -b ${CACHE}/$OGIMG/$TARGETFILE.bf -C 100"
890ctorrent -X "sleep $TimeToWaitForCloseAfterDownload; kill -9 \$(pidof ctorrent)" $TARGETDIR/$TARGETFILE.img.torrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -b ${CACHE}/$OGIMG/$TARGETFILE.bf -C 100
891
892[ -r ${CACHE}/$OGIMG/$TARGETFILE.bf ] && rm ${CACHE}/$OGIMG/$TARGETFILE.bf
893}
894
895ogCheckSessionMulticast ()
896{
897# $1 tipo de sesion server client
898# 2 la sesisón.
899#variables locales
900local NPARM MODE SESSION
901
902# Si se solicita, mostrar ayuda.
903if [ "$*" == "help" ]; then
904    ogHelp "$FUNCNAME str_mode    array_session" \
905                   "$FUNCNAME client PORTBASE"\
906                   "$FUNCNAME server PORTBASE:METHOD:ADDRESS:BITRATE:NCLIENTS:MAXTIME"
907    return
908fi
909
910
911# Error si no se recibe 2 parámetro.
912[ $# == 2 ] || ogRaiseError $OG_ERR_FORMAT || return $?
913
914# controlamos el primer parametro.
915ogCheckStringInGroup "$1" "client server" || ogRaiseError $OG_ERR_OUTOFLIMIT || return $?
916
917#controlamos el segundo parametro. La sessión multicast.
918[ $1 == "client" ] && NPARM=1 || NPARM=6
919OIFS=$IFS; IFS=':' ; SESSION=($2); IFS=$OIFS
920[[ ${#SESSION[*]} == $NPARM ]]  || ogRaiseError $OG_ERR_OUTOFLIMIT || return $?
921
922#controlamos el PORTBASE de la sesion. Comun.-
923ogCheckStringInGroup ${SESSION[0]} "9000 9002 9004 9006 9008 9010" || ogRaiseError $OG_ERR_OUTOFLIMIT || return $?
924
925if [ "$1" == "server" ]
926then
927    # $METHOD
928        ogCheckStringInGroup ${SESSION[1]} "full-duplex half-duplex broadcast" || ogRaiseError $OG_ERR_OUTOFLIMIT || return $?
929        # $ADDRESS
930        ogCheckIpAddress ${SESSION[2]}  || ogRaiseError $OG_ERR_OUTOFLIMIT || return $?
931        #BITRATE
932        ogCheckStringInReg ${SESSION[3]} "^[1-9]{1,2}M$" || ogRaiseError $OG_ERR_OUTOFLIMIT || return $?
933        #NCLIENTS
934        ogCheckStringInReg ${SESSION[4]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_OUTOFLIMIT || return $?
935        #MAXTIME
936        ogCheckStringInReg ${SESSION[5]} "^[0-9]{1,10}$" || ogRaiseError $OG_ERR_OUTOFLIMIT "  " || return $?
937fi
938return 0
939}
Note: See TracBrowser for help on using the repository browser.