source: client/engine/Protocol.lib @ f4b737d

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

trunk Protocolos de clonación:
ogTorrentStart file.torrent opcionesP2P
restoreImage utilizando ogTorrentStart y ogMulticastReceiverFile
sendFileScripts usado por el repo. llamada directa a ogMulticastSendFile

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

  • Property mode set to 100644
File size: 20.4 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#@todo: Abriendo puerto para pasar parametros de control al cliente.
254#@version 0.1 - Integración para OpenGNSys.
255#@author        Antonio J. Doblas Viso. Universidad de Málaga
256#@date
257#@version 0.2 - Integración para btlaunch.
258#@author        Irina . Univesidad de Sevilla.
259#@date
260#*/ ##
261
262ogCreateTorrent ()
263{
264# Variables locales.
265local ARGS ARG SOURCE IPTORRENT
266
267
268# Si se solicita, mostrar ayuda.
269if [ "$*" == "help" ]; then
270    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file IpBttrack" \           "$FUNCNAME 1 1 /aula1/winxp 10.1.15.23" \
271       "$FUNCNAME REPO /aula1/winxp 10.1.15.45"
272
273    return
274fi
275
276# Error si se quiere crear el fichero en cache y no existe
277[ "$1" != "CACHE" ] || `ogFindCache >/dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE"|| return $?
278
279case "$1" in
280    /*)     # Camino completo.          */ (Comentrio Doxygen)
281           SOURCE=$(ogGetPath "$1.img")
282        ARG=2
283                ;;
284    [1-9]*) # ndisco npartición.
285           SOURCE=$(ogGetPath "$1" "$2" "$3.img")
286        ARG=4
287        ;;
288    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
289           SOURCE=$(ogGetPath "$1" "$2.img")
290        ARG=3
291        ;;
292esac
293
294# Error si no se reciben los argumentos ARG necesarios según la opcion.
295[ $# -eq "$ARG" ] || ogRaiseError $OG_ERR_FORMAT || return $?
296
297
298# Error si no existe la imagen
299[ $SOURCE ] ||  ogRaiseError $OG_ERR_NOTFOUND || return $?
300
301[ -r $SOURCE.torrent ] && mv "$SOURCE.torrent" "$SOURCE.torrent.ant" && echo "Esperamos que se refresque el servidor" && sleep 20
302
303IPTORRENT="${!#}"
304# Si ponemos el path completo cuando creamos el fichero torrent da error
305cd `dirname $SOURCE`
306echo ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
307ctorrent -t `basename $SOURCE` -u http://$IPTORRENT:6969/announce -s $SOURCE.torrent
308
309}
310
311
312#/**
313#         ogTorrentStart  [ str_repo | int_ndisk int_npart ] Relative_path_file | SessionProtocol
314#@brief   Función iniciar P2P - requiere un tracker y los ficheros .torrent.
315#@param   str_pathDirectory  str_Relative_path_file
316#@param  int_disk    int_partition   str_Relative_path_file
317#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
318#@return
319#@note
320#@todo:
321#@version 0.1 - Integración para OpenGNSys.
322#@author        Antonio J. Doblas Viso. Universidad de Málaga
323#@date
324#@version 0.2 - Chequeo del tamaño de imagen descargado.
325#@author        Irina . Univesidad de Sevilla.
326#@date
327#*/ ##
328
329ogTorrentStart ()
330{
331#protocoloTORRENT
332#mode=seeder|leecher  -> seedear mientras descarga
333#timeAfter -> tiempo de seeder desdpues de la descarga
334#timeServer -> cuando el equipo ya tenía la imagen.
335
336case "$1" in
337    /*)     # Camino completo.          */ (Comentrio Doxygen)
338           SOURCE=$(ogGetPath "$1")
339           ARG=1
340           SESSION=$2
341     ;;
342    [1-9]*) # ndisco npartición.
343           SOURCE=$(ogGetPath "$1" "$2" "$3")
344           ARG=3
345           SESSION=$4
346     ;;
347    *) # Otros: repo, cache, cdrom (no se permiten caminos relativos).
348        SOURCE=$(ogGetPath "$1" "$2" 2>/dev/null)
349        ARG=2
350        SESSION=$3
351        ;;
352esac
353
354ctorrent -x ${SOURCE}; [ $? -eq 0 ] ||  ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
355
356TARGET=`echo $SOURCE | awk -F.torrent '{print $1}'`
357DIRSOURCE=`ogGetParentPath $SOURCE`
358cd $DIRSOURCE
359
360#analizando SESSION
361MODE=`echo $SESSION | cut -f1 -d:`
362TIMECLIENT=`echo $SESSION | cut -f2 -d:`
363TIMESERVER=`echo $SESSION | cut -f3 -d:`
364
365#comprobamos si tenemos la imagen completa
366#echo " ctorrent -s $TARGET -c $SOURCE | tail -n1 | cut -f2 -d\( "
367TOTAL=`ctorrent -s $TARGET -c $SOURCE | tail -n1 | cut -f2 -d\(`
368if [ "$TOTAL" == "100%)" ]
369then
370    TIMECLIENT=$TIMESERVER
371fi
372
373if [ "$MODE" == "seeder" ]
374then
375   echo "ctorrent ${SOURCE} -X 'sleep $TIMECLIENT; kill -9 \$(pidof ctorrent)' -C 100"
376   ctorrent ${SOURCE} -X "sleep $TIMECLIENT; kill -9 \$(pidof ctorrent)" -C 100
377fi
378
379if [ "$MODE" == "leecher" ]
380then
381   echo "ctorrent ${SOURCE} -X 'sleep $TIMECLIENT; kill -9 \$(pidof ctorrent)' -C 100 -U 0"
382   ctorrent ${SOURCE} -X "sleep $TIMECLIENT; kill -9 \$(pidof ctorrent)" -C 100 -U 0
383fi
384cd /tmp
385}
386
387
388
389############################################################
390##################### FUNCIONES MULTICAST EN DESARROLLO ##########
391
392
393#/**
394#         ogMcastSessionCheck [session]
395#@brief   Controla los parámetros de una sessión multicast
396#@param   str_session   
397#@return  (nada, por determinar)
398#@exception OG_ERR_FORMAT     formato incorrecto.
399#@note    Requisitos:
400#@version 0.91 - Definición de FileTransfer
401#@author  Antonio Doblas Viso, Universidad de Málaga
402#@date    2010/05/09
403#*/ ##
404ogMcastSessionCheck ()
405{
406echo "en pruebas"
407#sessionSERVER  PORTBASE:METHOD:ADDRESS:BITRATE:NCLINTS:MAXTIME:TOOLCLONE:COMPRESSOR
408#sessionCLIENT  PORTBASE:TOOLCLONE:COMPRESSOR
409#PORTBASE: 9000 (incluye el 9001), 9002 (incluye el 9003), 9004
410#METHOD: full-duplex half-duplex brodcast
411#ADDRESS: Dirección habilitada para la transferencia. 339.194.ip2.ip3
412#BITRATE: 90M   80M   70M
413#NCLIENTS:
414#MAXTIME:
415#TOOLCLONE:
416#COMPRESSOR:
417}
418
419
420#/**
421#         ogMcastSessionList
422#@brief   Lista las sessiones abiertas multicast.
423#@param   (en pruebas)
424#@return  (nada, por determinar)
425#@exception OG_ERR_FORMAT     formato incorrecto.
426#@note    Requisitos:
427#@version 0.91 - Definición de FileTransfer
428#@author  Antonio Doblas Viso, Universidad de Málaga
429#@date    2010/05/09
430#*/ ##
431ogMcastSessionList()
432{
433echo "en preubas"
434#puertos a utilizar 9000 - 9008 => se definen 10 sesiones
435#lsof -i -nP | grep 900 | awk '{print $9}' | awk -F: '{print $2}' | uniq
436}
437
438#/**
439#         ogMcastSessionDelete
440#@brief   Libera una session Mulitcast.
441#@param   (en pruebas)
442#@return  (nada, por determinar)
443#@exception OG_ERR_FORMAT     formato incorrecto.
444#@note    Requisitos:
445#@version 0.91 - Definición de FileTransfer
446#@author  Antonio Doblas Viso, Universidad de Málaga
447#@date    2010/05/09
448#*/ ##
449ogMcastSessionDelete()
450{
451echo "en pruebas"
452}
453
454#/**
455#         ogMcastSendPartition
456#@brief   Función para enviar el contenido de una partición a multiples particiones remotas.
457#@param
458#@param
459#@param
460#@return
461#@exception
462#@note
463#@todo:
464#@version 0.1 - Integración para OpenGNSys.
465#@author
466#@date
467#*/ ##
468
469ogMcastSendPartition ()
470{
471
472# Variables locales
473local PART  ERRCODE
474
475# Si se solicita, mostrar ayuda.
476if [ "$*" == "help" ]; then
477    ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_npart " \
478           "$FUNCNAME 1 1 "
479    return
480fi
481# Error si no se reciben 2 parámetros.
482[ $# -lt 2 ] && ogRaiseError $OG_ERR_FORMAT && return $?
483
484PART=$(ogDiskToDev "$1" "$2") || return $?
485if ogIsLocked $1 $2; then
486    ogRaiseError $OG_ERR_LOCKED "$1,$2"
487    return $?
488fi
489
490
491echo "en pruebas"
492
493}
494
495
496#/**
497#         ogMcastRestorePartition
498#@brief   Función para recibir directamente en la partición el contenido de un fichero imagen remoto enviado por multicast.
499#@param
500#@param
501#@param
502#@return
503#@exception
504#@note
505#@todo:
506#@version 0.1 - Integración para OpenGNSys.
507#@author
508#@date
509#*/ ##
510ogMcastRestorePartition ()
511{
512echo "en pruebas"
513}
514
515########################## FUNCIONES TORRENT EN DESARROLLO
516##################################################
517#/**
518#         ogStartTracker
519#@brief   Inicia el tracker
520#@param   str_pathDirectory  str_Relative_path_file
521#@param  int_disk    int_partition   str_Relative_path_file
522#@param  str_REPOSITORY(CACHE - LOCAL)  str_Relative_path_file
523#@return
524#@exception OG_ERR_FORMAT    Formato incorrecto.
525#@exception OG_ERR_NOTFOUND  Disco o particion no corresponden con un dispositivo.
526#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar.
527#@exception OG_ERR_NOTOS     La partición no tiene instalado un sistema operativo.
528#@note
529#@version 0.1 - Integración para OpenGNSys.
530#@author
531#@date
532#*/ ##
533ogStartTracker ()
534{
535        echo " bug2: usar el tracker del bittornado. "
536        echo " solucion bug2: apt-get autoremove bittorrent python-bittorrent "
537        echo "soulución bug2: apt-get install bittornado. "
538        echo "#Paso 2: iniciar track "
539local TESTBTT
540TESTBTT=`ps aux | grep bttrack | egrep -v grep | wc -l`
541if [ "$TESTBTT" == "0" ]; then
542        bttrack --reannounce_interval 10 --port 6969 --dfile /root/dstate --logfile /root/bttracker.log --save_dfile_interval 10 --timeout_downloaders_interval 10 2>/dev/null &
543else
544        echo "bttrack iniciado"
545fi
546
547}
548
549ogShareTorrent ()
550{
551# Variables locales.
552local ARGS SOURCE TARGET
553
554
555# Si se solicita, mostrar ayuda.
556if [ "$*" == "help" ]; then
557    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
558           "$FUNCNAME 1 1 /aula1/winxp" \
559           "$FUNCNAME REPO /aula1/winxp"
560
561    return
562fi
563
564# Error si se quiere compartir un fichero en cache y no existe la cache
565[ "$1" != "CACHE" ] || `ogFindCache >/dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE"|| return $?
566
567case "$1" in
568    /*)     # Camino completo.          */ (Comentrio Doxygen)
569           SOURCE=$(ogGetPath "$1.img")
570           ARG=1
571                ;;
572    [1-9]*) # ndisco npartición.
573           SOURCE=$(ogGetPath "$1" "$2" "$3.img")
574        ARG=3
575        ;;
576    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
577           SOURCE=$(ogGetPath "$1" "$2.img" 2>/dev/null)
578        ARG=2
579        ;;
580esac
581
582
583# Error si no se reciben los argumentos ARG necesarios según la opcion.
584[ $# -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
585
586# Comprobar fichero origen
587[ -n "$SOURCE.torrent" ] || ogRaiseError $OG_ERR_NOTFOUND "${ARGS% $*}" || return $?
588
589echo ctorrent $SOURCE.torrent -d
590ctorrent $SOURCE.torrent -d
591
592}
593
594
595ogTorrentReceiverFile ()
596{
597# obligatorio disponer de cache
598# origen destino.
599#origen es el .torrent
600# origen: REPO /file.torrent
601# Si REPO, (nfs, http) copiamos a CACHE.
602
603# destino es el fichero final.
604# destino: CACHE /file
605# destino: disk part /file
606
607# Variables locales.
608    local ARGS ARG SOURCEDIR SOURCEFILE TARGETDIR TARGETFILE
609
610# Si se solicita, mostrar ayuda.
611if [ "$*" == "help" ]; then
612    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
613           "$FUNCNAME REPO /aula1/winxp.torrent CACHE /aula1/winxp" \
614           "$FUNCNAME REPO /aula1/winxp.torrent 1 1 /iso"
615fi
616# Comprobamos que existe Cache
617`ogFindCache > /dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE" || return $?
618
619# guardamos torrent. controlamos tamaño del fichero y comprobamos con cache.
620ogCopyFile $1 $2 $3 $4
621
622
623}
624
625ogReceiveTorrent ()
626{
627# Variables locales.
628    local ARGS ARG TARGETDIR TARGETFILE
629
630
631
632# Si se solicita, mostrar ayuda.
633if [ "$*" == "help" ]; then
634    ogHelp "$FUNCNAME" "$FUNCNAME [str_REPOSITORY] [int_ndisk int_npart] Relative_path_file" \
635           "$FUNCNAME 1 1 /aula1/winxp" \
636           "$FUNCNAME REPO /aula1/winxp" \
637           "$FUNCNAME /mnt/sda2/winxp"
638
639
640    return
641fi
642
643# Comprobamos que existe Cache
644`ogFindCache > /dev/null` || ogRaiseError $OG_ERR_NOTFOUND "CACHE" || return $?
645
646ARGS="$*"
647case "$1" in
648    /*)     # Camino completo.          */ (Comentrio Doxygen)
649    TARGETDIR=$(ogGetParentPath "$1")
650        ARG=1
651                ;;
652    [1-9]*) # ndisco npartición.
653    TARGETDIR=$(ogGetParentPath "$1" "$2" "$3")
654        ARG=3
655        ;;
656    *)      # Otros: repo, cache, cdrom (no se permiten caminos relativos).
657    TARGETDIR=$(ogGetParentPath "$1" "$2")
658        ARG=2
659        ;;
660esac
661#echo $TARGETDIR
662
663# Error si no se reciben los argumentos ARG necesarios según la opcion.
664[ "$#" -ne "$ARG" ] && ogRaiseError $OG_ERR_FORMAT && return $?
665
666#obtenemos el nombre del fichero a descargar.
667TARGETFILE=`basename ${!ARG}`
668CACHE=`ogMountCache`
669
670# Error si no existe el fichero torrent
671[ -r $TARGETDIR/$TARGETFILE.img.torrent ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
672[ -d ${CACHE}/$OGIMG ] || ogRaiseError $OG_ERR_NOTFOUND || return $?
673
674TimeToWaitForCloseAfterDownload=20  # tiempo que deseamos que el cliente este como semilla, despues de la descarga.
675
676# Si el fichero ya se ha bajado antes de iniciar el ctorrent no se ejecuta el comando kill, siguen encendido siempre
677# Comprobamos si se ha descargado antes, si es asi nos salimos
678Total=`ctorrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -c $TARGETDIR/$TARGETFILE.img.torrent|tail -n1|cut -f2 -d\(`
679[ $Total == "100%)" ] &&  return 0
680
681echo "ctorrent -X 'sleep $TimeToWaitForCloseAfterDownload; kill -9 \$(pidof ctorrent)' $TARGETDIR/$TARGETFILE.img.torrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -b ${CACHE}/$OGIMG/$TARGETFILE.bf -C 100"
682ctorrent -X "sleep $TimeToWaitForCloseAfterDownload; kill -9 \$(pidof ctorrent)" $TARGETDIR/$TARGETFILE.img.torrent -s ${CACHE}/$OGIMG/${TARGETFILE}.img -b ${CACHE}/$OGIMG/$TARGETFILE.bf -C 100
683
684[ -r ${CACHE}/$OGIMG/$TARGETFILE.bf ] && rm ${CACHE}/$OGIMG/$TARGETFILE.bf
685}
Note: See TracBrowser for help on using the repository browser.