source: client/engine/Protocol.lib @ 09a65ca

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 09a65ca was 1678fa1, checked in by adv <adv@…>, 15 years ago

trunck engine Protocol.lib: ogTorrentStart corrección detección estado imagen, tiempos para el peer, leecher, seeder

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

  • Property mode set to 100644
File size: 21.9 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#/**
14#         ogGenerateSintaxMcast
15#@brief   Función para generar la instruccion de ejucción la transferencia de datos multicast
16#@param 1 Tipo de operacion [ SENDPARTITION RECEIVERPARTITION SENDFILE RECEIVERFILE ]
17#@param 2 Sesión Mulitcast
18#@param 3 Dispositivo (opcion PARTITION) o fichero(opcion FILE) a ser enviado.
19#@param 4 Tools de clonación (opcion PARTITION)
20#@param 5 Tools de compresion (opcion PARTITION)
21#@return  instrucción para ser ejecutada.
22#@exception OG_ERR_FORMAT     formato incorrecto.
23#@note    Requisitos:
24#@version 0.91 - Definición de FileTransfer
25#@author  Antonio Doblas Viso, Universidad de Málaga
26#@date    2010/05/09
27#*/ ##
28#/**
29#         
30
31
32function ogGenerateSintaxMcast ()
33{
34# Si se solicita, mostrar ayuda.
35if [ "$*" == "help" -o "$2" == "help" ]; then
36    ogHelp "$FUNCNAME SENDPARTITION      str_sessionSERVER     str_device str_tools str_level" \
37                   "$FUNCNAME RECEIVERPARTITION  str_sessionCLIENT     str_device str_tools str_level "\
38                   "$FUNCNAME SENDFILE           str_sessionSERVER     str_file "\
39                   "$FUNCNAME RECEIVERFILE       str_sessionCLIENT     str_file "
40    return
41fi
42
43## Introducir control de errores en parametros.
44
45
46#Obtenemos los datos de la sesión multicast
47# Pendiente para ser procesado y/o proporcionado por ogMcastSessionCheck
48PORTBASE=`echo $2 | awk -F: '{print $1}'`
49[ -z $PORTBASE ] && PORTBASE=9000
50METHOD=`echo $2 | awk -F: '{print $2}'`
51[ -z $METHOD ] && METHOD=full-duplex
52ADDRESS=`echo $2 | awk -F: '{print $3}'`
53[ -z $ADDRESS ] && ADDRESS=prueba
54BITRATE=`echo $2 | awk -F: '{print $4}'`
55[ -z $BITRATE ] && BITRATE=70M
56NCLIENTS=`echo $2 | awk -F: '{print $5}'`
57[ -z $NCLIENTS ] && NCLIENTS=100
58MAXTIME=`echo $2 | awk -F: '{print $6}'`
59[ -z $MAXTIME ] && MAXTIME=360
60# Valores estandar no configurables.
61CERROR="8x8/128"
62
63
64DEVICE=`echo $3`
65TOOL=`echo $4`
66LEVEL=`echo $5`
67
68# opción del usuo de tuberia intermedia en memoria mbuffer.
69which mbuffer > /dev/null && MBUFFER=" --pipe 'mbuffer -m 20M' "
70
71# Generamos la instrucción base de multicast -Envio,Recepcion-
72SINTAXSERVER="udp-sender $MBUFFER --portbase $PORTBASE --$METHOD --mcast-data-address $ADDRESS --fec $CERROR --max-bitrate $BITRATE --ttl 1 --min-clients $NCLIENTS --max-wait $MAXTIME "
73SINTAXCLIENT="udp-receiver $MBUFFER --portbase $PORTBASE "
74
75
76case "$1" in
77   SENDPARTITION)
78        PROG1=`ogGenerateSintaxForCreateImage $DEVICE " " $TOOL $LEVEL | awk -F"|" '{print $1 "|" $3}' | tr -d ">"`
79                echo "$PROG1 | $SINTAXSERVER"
80        ;;
81    RECEIVERPARTITION)
82                COMPRESSOR=`ogGenerateSintaxForRestoreImage " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $1}'`
83                TOOLS=`ogGenerateSintaxForRestoreImage " " $DEVICE $TOOL $LEVEL | awk -F\| '{print $3}'`
84                echo "$SINTAXCLIENT | $COMPRESSOR | $TOOLS "
85        ;;
86        SENDFILE)
87                echo "$SINTAXSERVER --file $3"
88    ;;
89    RECEIVERFILE)
90                echo "$SINTAXCLIENT --file $3"
91    ;;
92   *)
93   ;;
94esac
95}
96
97
98
99#/**
100#         ogMcastSendFile [ str_repo | int_ndisk int_npart ] /Relative_path_file  sessionMulticast
101#@brief   Envía un fichero por multicast   ORIGEN(fichero) DESTINO(sessionmulticast)
102#@param (2 parámetros)  $1 path_aboluto_fichero  $2 sesionMcast
103#@param (3 parámetros)  $1 Contenedor REPO|CACHE $2 path_absoluto_fichero $3 sesionMulticast
104#@param (4 parámetros)  $1 disk $2 particion $3 path_absoluto_fichero $4 sesionMulticast
105#@return 
106#@exception OG_ERR_FORMAT     formato incorrecto.
107#@note    Requisitos:
108#@version 0.91 - Definición de FileTransfer
109#@author  Antonio Doblas Viso, Universidad de Málaga
110#@date    2010/05/09
111#*/ ##
112#/**
113#
114
115function ogMcastSendFile ()
116{
117# Variables locales.
118local ARGS SOURCE TARGET COMMAND
119#ARGS usado para controlar ubicación de la sesion multicast
120
121# Si se solicita, mostrar ayuda.
122if [ "$*" == "help" ]; then
123    ogHelp "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] /Relative_path_file sesionMcast" \
124           "$FUNCNAME  1 1 /aula1/winxp.img sesionMcast" \
125           "$FUNCNAME  REPO /aula1/ubuntu.iso sesionMcast" \
126           "$FUNCNAME  CACHE /aula1/winxp.img sesionMcast" \
127           "$FUNCNAME  /opt/opengnsys/images/aula1/hd500.vmx sesionMcast"
128    return
129fi
130
131ARGS="$@"
132case "$1" in
133    /*)     # Camino completo.          */ (Comentrio Doxygen)
134        SOURCE=$(ogGetPath "$1")
135                ARG=2
136                ;;
137    [1-9]*) # ndisco npartición.
138        SOURCE=$(ogGetPath "$1" "$2" "$3")
139        ARG=4
140        ;;
141    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
142        SOURCE=$(ogGetPath "$1" "$2")
143        ARG=3
144        ;;
145esac
146
147
148# Error si no se reciben los argumentos ARG necesarios según la opcion.
149[ $# -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
150
151# Comprobar fichero origen
152[ -n "$SOURCE" ] || ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
153
154#TODO echo Abriendo puerto para pasar parametros de control al cliente.
155#TODO opcion netcat, netpipes, o un fichero mcast con la info final.
156SESSION=${!ARG}
157# llamando a la funcion con param1 session $SESSION y param2 $SOURCE
158COMMAND=`ogGenerateSintaxMcast "SENDFILE" "$SESSION" "$SOURCE"`
159echo $COMMAND
160eval $COMMAND
161}
162
163
164
165#/**
166#         ogMcastReceiverFile  sesion Multicast [ str_repo | int_ndisk int_npart ] /Relative_path_file
167#@brief   Recibe un fichero multicast   ORIGEN(sesionmulticast) DESTINO(fichero)
168#@param (2 parámetros)  $1 sesionMcastCLIENT $2 path_aboluto_fichero_destino 
169#@param (3 parámetros)  $1 sesionMcastCLIENT $2 Contenedor REPO|CACHE $3 path_absoluto_fichero_destino
170#@param (4 parámetros)  $1 sesionMcastCLIENT $2 disk $3 particion $4 path_absoluto_fichero_destino
171#@return 
172#@exception OG_ERR_FORMAT     formato incorrecto.
173#@note    Requisitos:
174#@version 0.91 - Definición de FileTransfer
175#@author  Antonio Doblas Viso, Universidad de Málaga
176#@date    2010/05/09
177#*/ ##
178#/**
179#
180
181ogMcastReceiverFile ()
182{
183# nota el nombre del fichero debe tener su extension si es img nombre.img
184#Origen
185#$1 puerto de entrada
186
187# Destino
188# un parametro $2 path absoulo.
189# dos parametros $2 CACHE|REPO  y $3 path absoulto(dentro de imagenes)
190# tres parametros $2 disk $3 particion $4 directorio absoluto de la particion.
191
192# Variables locales.
193local ARGS ARG TARGETDIR TARGETFILE
194
195
196# Si se solicita, mostrar ayuda.
197if [ "$*" == "help" ]; then
198    ogHelp "$FUNCNAME" "$FUNCNAME [ str_portMcast] [ [Relative_path_file] | [str_REPOSITORY path_file] |  [int_ndisk int_npart path_file ]  ]" \
199           "$FUNCNAME 9000 /aula1/winxp/file" \
200           "$FUNCNAME 9000 CACHE /aula1/winxp/file" \
201           "$FUNCNAME 9000 1 1 /Descargas/file"
202         
203
204    return
205fi
206
207ARGS="$@"
208case "$2" in
209    /*)     # Camino completo.          */ (Comentrio Doxygen)
210        TARGETDIR=$(ogGetParentPath "$2")
211                ARG=2
212                echo $TARGETDIR
213        ;;
214    [1-9]*) # ndisco npartición.
215        TARGETDIR=$(ogGetParentPath "$2" "$3" "$4")
216        ARG=4
217        echo $TARGETDIR
218    ;;
219    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
220        TARGETDIR=$(ogGetParentPath "$2" "$3")
221        ARG=3
222        echo $TARGETDIR
223    ;;
224esac
225
226# Error si no se reciben los argumentos ARG necesarios según la opcion.
227[ "$#" -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
228
229#obtenemos el nombre del fichero a descargar.
230TARGETFILE=`basename ${!ARG}`
231
232#generamos la instrucción a ejecutar. 
233COMMAND=`ogGenerateSintaxMcast RECEIVERFILE "$1" $TARGETDIR/$TARGETFILE `
234echo $COMMAND
235eval $COMMAND
236}
237
238###########################################3
239############## funciones torrent
240
241#/**
242#         ogCreateTorrent  [ str_repo | int_ndisk int_npart ] Relative_path_file
243#@brief   Función para crear el fichero torrent.
244#@param   str_pathDirectory  str_Relative_path_file
245#@param  int_disk    int_partition   str_Relative_path_file
246#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
247#@return
248#@exception OG_ERR_FORMAT    Formato incorrecto.
249#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
250#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
251#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
252#@note
253#@version 0.1 - Integración para OpenGNSys.
254#@author        Antonio J. Doblas Viso. Universidad de Málaga
255#@date
256#@version 0.2 - Integración para btlaunch.
257#@author        Irina . Univesidad de Sevilla.
258#@date
259#*/ ##
260
261ogCreateTorrent ()
262{
263# Variables locales.
264local ARGS ARG SOURCE IPTORRENT
265
266
267# Si se solicita, mostrar ayuda.
268if [ "$*" == "help" ]; then
269    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file IpBttrack" \           "$FUNCNAME 1 1 /aula1/winxp 10.1.15.23" \
270       "$FUNCNAME REPO /aula1/winxp 10.1.15.45"
271
272    return
273fi
274
275# Error si se quiere crear el fichero en cache y no existe
276[ "$1" != "CACHE" ] || `ogFindCache >/dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE"|| return $?
277
278case "$1" in
279    /*)     # Camino completo.          */ (Comentrio Doxygen)
280           SOURCE=$(ogGetPath "$1.img")
281        ARG=2
282                ;;
283    [1-9]*) # ndisco npartición.
284           SOURCE=$(ogGetPath "$1" "$2" "$3.img")
285        ARG=4
286        ;;
287    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
288           SOURCE=$(ogGetPath "$1" "$2.img")
289        ARG=3
290        ;;
291esac
292
293# Error si no se reciben los argumentos ARG necesarios según la opcion.
294[ $# -eq "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
295
296
297# Error si no existe la imagen
298[ $SOURCE ] ||  ogRaiseError $OG_ERR_NOTFOUND || return $?
299
300[ -r $SOURCE.torrent ] && mv "$SOURCE.torrent" "$SOURCE.torrent.ant" && echo "Esperamos que se refresque el servidor" && sleep 20
301
302IPTORRENT="${!#}"
303# Si ponemos el path completo cuando creamos el fichero torrent da error
304cd `dirname $SOURCE`
305echo ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
306ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
307
308}
309
310
311#/**
312#         ogTorrentStart  [ str_repo | int_ndisk int_npart ] Relative_path_file | SessionProtocol
313#@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.
314#@param   str_pathDirectory  str_Relative_path_file
315#@param  int_disk    int_partition   str_Relative_path_file
316#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
317#@return
318#@note
319#@todo:
320#@version 0.1 - Integración para OpenGNSys.
321#@author        Antonio J. Doblas Viso. Universidad de Málaga
322#@date
323#@version 0.2 - Chequeo del tamaño de imagen descargado.
324#@author        Irina . Univesidad de Sevilla.
325#@date
326#@version 0.3 - Control de los modos de operación, y estado de descarga.
327#@author        Antonio J. Doblas Viso. Univesidad de Málaga.
328#@date
329#*/ ##
330#Lee el fichero torrent y descarga o comparte el fichero destino en el mismo subdirectorio.
331# Parametros para el orgien del fichero file.df.torrent
332# 1 camino completo al fichero
333# 1 2   Contenedor /fichero relativo
334# 1 2 3  disco particion y /fichero relativo.
335#protocoloTORRENT    mode:time
336# posicion 2, 3, 4
337#mode=seeder  -> Dejar el equipo seedeando hasta que transcurra el tiempo indicado o un kill desde consola,
338#mode=peer    -> seedear mientras descarga
339#mode=leecher  -> NO seedear mientras descarga
340#time tiempo que una vez descargada la imagen queremos dejar al cliente como seeder.
341
342ogTorrentStart ()
343{
344#TODO ayuda
345#TODO: control parametros.
346
347case "$1" in
348    /*)     # Camino completo.          */ (Comentrio Doxygen)
349           SOURCE=$(ogGetPath "$1")
350           ARG=1
351           SESSION=$2
352     ;;
353    [1-9]*) # ndisco npartición.
354           SOURCE=$(ogGetPath "$1" "$2" "$3")
355           ARG=3
356           SESSION=$4
357     ;;
358    *) # Otros: repo, cache, cdrom (no se permiten caminos relativos).
359        SOURCE=$(ogGetPath "$1" "$2" 2>/dev/null)
360        ARG=2
361        SESSION=$3
362        ;;
363esac
364
365ctorrent -x ${SOURCE}; [ $? -eq 0 ] ||  ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
366
367TARGET=`echo $SOURCE | awk -F.torrent '{print $1}'`
368DIRSOURCE=`ogGetParentPath $SOURCE`
369cd $DIRSOURCE
370
371#analizando SESSION
372MODE=`echo $SESSION | cut -f1 -d:`
373TIME=`echo $SESSION | cut -f2 -d:`
374
375
376#echo $MODE $TIME
377#echo ${SOURCE}.bf  ${TARGET}
378
379# si No fichero .bf, y Si fichero destino    imagen ya descargada y su chequeo fue comprobado en su descarga inicial.
380if [ ! -f ${SOURCE}.bf -a -f ${TARGET} ]
381then
382  echo "imagen ya descargada"
383  case "$MODE" in
384        seeder|SEEDER)
385                (sleep $TIME && kill -9 `pidof ctorrent`) &
386                echo "MODE seeder ctorrent ${SOURCE} -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100"
387                ctorrent ${SOURCE}
388  esac
389  return 0
390fi
391
392#Si no existe bf ni fichero destino         descarga inicial.
393if [ ! -f ${SOURCE}.bf -a ! -f ${TARGET} ]
394then
395        OPTION=DOWNLOAD
396    echo "descarga inicial"
397fi
398
399# Si fichero bf           descarga anterior no completada -.
400if [ -f ${SOURCE}.bf -a -f ${TARGET} ]
401then       
402        echo Continuar con Descargar inicial no terminada.
403        OPTION=DOWNLOAD
404fi
405
406case "$OPTION" in
407        download|DOWNLOAD)
408        if [ "$MODE" == "peer" ]
409        then
410                        echo "ctorrent -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100 $SOURCE -s $TARGET -b ${SOURCE}.bf"
411            ctorrent -f -X "sleep $TIME; kill -9 \$(pidof ctorrent)" -C 100 ${SOURCE} -s ${TARGET} -b ${SOURCE}.bf
412        fi
413
414        if [ "$MODE" == "leecher" ]
415        then
416          echo "ctorrent ${SOURCE} -X 'sleep $TIME; kill -9 \$(pidof ctorrent)' -C 100 -U 0"
417          ctorrent ${SOURCE} -X "sleep $TIME; kill -9 \$(pidof ctorrent)" -C 100 -U 0
418        fi
419;;
420esac
421
422if [ "$OPTION" == "DOWNLOAD" ]
423then
424        echo "comprobando el fichero descargado"
425        echo " ctorrent -s $TARGET -c $SOURCE | tail -n1 | cut -f2 -d\( "
426        TOTAL=`ctorrent -s $TARGET -c $SOURCE | tail -n1 | cut -f2 -d\(`
427        if [ "$TOTAL" == "100%)" ]
428        then
429         return 0
430        else
431         return 1
432        fi
433 
434 fi
435 
436cd /tmp
437}
438
439
440
441############################################################
442##################### FUNCIONES MULTICAST EN DESARROLLO ##########
443
444
445#/**
446#         ogMcastSessionCheck [session]
447#@brief   Controla los parámetros de una sessión multicast
448#@param   str_session   
449#@return  (nada, por determinar)
450#@exception OG_ERR_FORMAT     formato incorrecto.
451#@note    Requisitos:
452#@version 0.91 - Definición de FileTransfer
453#@author  Antonio Doblas Viso, Universidad de Málaga
454#@date    2010/05/09
455#*/ ##
456ogMcastSessionCheck ()
457{
458echo "en pruebas"
459#sessionSERVER  PORTBASE:METHOD:ADDRESS:BITRATE:NCLINTS:MAXTIME:TOOLCLONE:COMPRESSOR
460#sessionCLIENT  PORTBASE:TOOLCLONE:COMPRESSOR
461#PORTBASE: 9000 (incluye el 9001), 9002 (incluye el 9003), 9004
462#METHOD: full-duplex half-duplex brodcast
463#ADDRESS: Dirección habilitada para la transferencia. 339.194.ip2.ip3
464#BITRATE: 90M   80M   70M
465#NCLIENTS:
466#MAXTIME:
467#TOOLCLONE:
468#COMPRESSOR:
469}
470
471
472#/**
473#         ogMcastSessionList
474#@brief   Lista las sessiones abiertas multicast.
475#@param   (en pruebas)
476#@return  (nada, por determinar)
477#@exception OG_ERR_FORMAT     formato incorrecto.
478#@note    Requisitos:
479#@version 0.91 - Definición de FileTransfer
480#@author  Antonio Doblas Viso, Universidad de Málaga
481#@date    2010/05/09
482#*/ ##
483ogMcastSessionList()
484{
485echo "en preubas"
486#puertos a utilizar 9000 - 9008 => se definen 10 sesiones
487#lsof -i -nP | grep 900 | awk '{print $9}' | awk -F: '{print $2}' | uniq
488}
489
490#/**
491#         ogMcastSessionDelete
492#@brief   Libera una session Mulitcast.
493#@param   (en pruebas)
494#@return  (nada, por determinar)
495#@exception OG_ERR_FORMAT     formato incorrecto.
496#@note    Requisitos:
497#@version 0.91 - Definición de FileTransfer
498#@author  Antonio Doblas Viso, Universidad de Málaga
499#@date    2010/05/09
500#*/ ##
501ogMcastSessionDelete()
502{
503echo "en pruebas"
504}
505
506#/**
507#         ogMcastSendPartition
508#@brief   Función para enviar el contenido de una partición a multiples particiones remotas.
509#@param
510#@param
511#@param
512#@return
513#@exception
514#@note
515#@todo:
516#@version 0.1 - Integración para OpenGNSys.
517#@author
518#@date
519#*/ ##
520
521ogMcastSendPartition ()
522{
523
524# Variables locales
525local PART  ERRCODE
526
527# Si se solicita, mostrar ayuda.
528if [ "$*" == "help" ]; then
529    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart " \
530           "$FUNCNAME 1 1 "
531    return
532fi
533# Error si no se reciben 2 parámetros.
534[ $# -lt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
535
536PART=$(ogDiskToDev "$1" "$2") || return $?
537if ogIsLocked $1 $2; then
538    ogRaiseError $OG_ERR_LOCKED "$1,$2"
539    return $?
540fi
541
542
543echo "en pruebas"
544
545}
546
547
548#/**
549#         ogMcastRestorePartition
550#@brief   Función para recibir directamente en la partición el contenido de un fichero imagen remoto enviado por multicast.
551#@param
552#@param
553#@param
554#@return
555#@exception
556#@note
557#@todo:
558#@version 0.1 - Integración para OpenGNSys.
559#@author
560#@date
561#*/ ##
562ogMcastRestorePartition ()
563{
564echo "en pruebas"
565}
566
567########################## FUNCIONES TORRENT EN DESARROLLO
568##################################################
569#/**
570#         ogStartTracker
571#@brief   Inicia el tracker
572#@param   str_pathDirectory  str_Relative_path_file
573#@param  int_disk    int_partition   str_Relative_path_file
574#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
575#@return
576#@exception OG_ERR_FORMAT    Formato incorrecto.
577#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
578#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
579#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
580#@note
581#@version 0.1 - Integración para OpenGNSys.
582#@author
583#@date
584#*/ ##
585ogStartTracker ()
586{
587        echo " bug2: usar el tracker del bittornado. "
588        echo " solucion bug2: apt-get autoremove bittorrent python-bittorrent "
589        echo "soulución bug2: apt-get install bittornado. "
590        echo "#Paso 2: iniciar track "
591local TESTBTT
592TESTBTT=`ps aux | grep bttrack | egrep -v grep | wc -l`
593if [ "$TESTBTT" == "0" ]; then
594        bttrack --reannounce_interval 10 --port 6969 --dfile /root/dstate --logfile /root/bttracker.log --save_dfile_interval 10 --timeout_downloaders_interval 10 2>/dev/null &
595else
596        echo "bttrack iniciado"
597fi
598
599}
600
601ogShareTorrent ()
602{
603# Variables locales.
604local ARGS SOURCE TARGET
605
606
607# Si se solicita, mostrar ayuda.
608if [ "$*" == "help" ]; then
609    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
610           "$FUNCNAME 1 1 /aula1/winxp" \
611           "$FUNCNAME REPO /aula1/winxp"
612
613    return
614fi
615
616# Error si se quiere compartir un fichero en cache y no existe la cache
617[ "$1" != "CACHE" ] || `ogFindCache >/dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE"|| return $?
618
619case "$1" in
620    /*)     # Camino completo.          */ (Comentrio Doxygen)
621           SOURCE=$(ogGetPath "$1.img")
622           ARG=1
623                ;;
624    [1-9]*) # ndisco npartición.
625           SOURCE=$(ogGetPath "$1" "$2" "$3.img")
626        ARG=3
627        ;;
628    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
629           SOURCE=$(ogGetPath "$1" "$2.img" 2>/dev/null)
630        ARG=2
631        ;;
632esac
633
634
635# Error si no se reciben los argumentos ARG necesarios según la opcion.
636[ $# -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
637
638# Comprobar fichero origen
639[ -n "$SOURCE.torrent" ] || ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
640
641echo ctorrent $SOURCE.torrent -d
642ctorrent $SOURCE.torrent -d
643
644}
645
646
647ogTorrentReceiverFile ()
648{
649# obligatorio disponer de cache
650# origen destino.
651#origen es el .torrent
652# origen: REPO /file.torrent
653# Si REPO, (nfs, http) copiamos a CACHE.
654
655# destino es el fichero final.
656# destino: CACHE /file
657# destino: disk part /file
658
659# Variables locales.
660    local ARGS ARG SOURCEDIR SOURCEFILE TARGETDIR TARGETFILE
661
662# Si se solicita, mostrar ayuda.
663if [ "$*" == "help" ]; then
664    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
665           "$FUNCNAME REPO /aula1/winxp.torrent CACHE /aula1/winxp" \
666           "$FUNCNAME REPO /aula1/winxp.torrent 1 1 /iso"
667fi
668# Comprobamos que existe Cache
669`ogFindCache > /dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE" || return $?
670
671# guardamos torrent. controlamos tamaño del fichero y comprobamos con cache.
672ogCopyFile $1 $2 $3 $4
673
674
675}
676
677ogReceiveTorrent ()
678{
679# Variables locales.
680    local ARGS ARG TARGETDIR TARGETFILE
681
682
683
684# Si se solicita, mostrar ayuda.
685if [ "$*" == "help" ]; then
686    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
687           "$FUNCNAME 1 1 /aula1/winxp" \
688           "$FUNCNAME REPO /aula1/winxp" \
689           "$FUNCNAME /mnt/sda2/winxp"
690
691
692    return
693fi
694
695# Comprobamos que existe Cache
696`ogFindCache > /dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE" || return $?
697
698ARGS="$*"
699case "$1" in
700    /*)     # Camino completo.          */ (Comentrio Doxygen)
701    TARGETDIR=$(ogGetParentPath "$1")
702        ARG=1
703                ;;
704    [1-9]*) # ndisco npartición.
705    TARGETDIR=$(ogGetParentPath "$1" "$2" "$3")
706        ARG=3
707        ;;
708    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
709    TARGETDIR=$(ogGetParentPath "$1" "$2")
710        ARG=2
711        ;;
712esac
713#echo $TARGETDIR
714
715# Error si no se reciben los argumentos ARG necesarios según la opcion.
716[ "$#" -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
717
718#obtenemos el nombre del fichero a descargar.
719TARGETFILE=`basename ${!ARG}`
720CACHE=`ogMountCache`
721
722# Error si no existe el fichero torrent
723[ -r $TARGETDIR/$TARGETFILE.img.torrent ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
724[ -d ${CACHE}/$OGIMG ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
725
726TimeToWaitForCloseAfterDownload=20  # tiempo que deseamos que el cliente este como semilla, despues de la descarga.
727
728# Si el fichero ya se ha bajado antes de iniciar el ctorrent no se ejecuta el comando kill, siguen encendido siempre
729# Comprobamos si se ha descargado antes, si es asi nos salimos
730Total=`ctorrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -c $TARGETDIR/$TARGETFILE.img.torrent|tail -n1|cut -f2 -d\(`
731[ $Total == "100%)" ] &&  return 0
732
733echo "ctorrent -X 'sleep $TimeToWaitForCloseAfterDownload; kill -9 \$(pidof ctorrent)' $TARGETDIR/$TARGETFILE.img.torrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -b ${CACHE}/$OGIMG/$TARGETFILE.bf -C 100"
734ctorrent -X "sleep $TimeToWaitForCloseAfterDownload; kill -9 \$(pidof ctorrent)" $TARGETDIR/$TARGETFILE.img.torrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -b ${CACHE}/$OGIMG/$TARGETFILE.bf -C 100
735
736[ -r ${CACHE}/$OGIMG/$TARGETFILE.bf ] && rm ${CACHE}/$OGIMG/$TARGETFILE.bf
737}
Note: See TracBrowser for help on using the repository browser.