-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistener.py
executable file
·2996 lines (2441 loc) · 131 KB
/
listener.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#the peer's distributed tracker part, manages transfers and connection speeds
#TODO: reuse redis pipes where possible
#TODO: make sure you don't forget to enable large files (>64GB) in rtorrent
import os, sys, traceback, threading, socket, time, random, subprocess, signal, logging
import socket as socketmodule #some sockets inside connectToPeer just refuse to get created as normal sockets, yet as socketmodule.socket it works just fine [and before, it worked even with sockets, no problems]
import redis, xmlrpc2scgi
from xmlrpc2scgi import RTorrentXMLRPCClient
from datetime import datetime
import logging.handlers
#the WorkDir is actually a sessionDir, since this script gets started there
WorkDir = os.getcwd()
#DOESN'T WORK, because xmlrpc cannot transfer such a large number
#global max_file_size #this is a hack for rtorrent: normally it doesn't support files >64GB, but if you specify a bigger max size via d.set_max_file_size, then it works
#max_file_size = 137438953472 #4398046511104 = 4TB - it if is really 4TB is to be seen, IMO it overflows... safe value should be 137438953472, which is 128GB (i guess 255 GB should be also safe)
global recvSendBuf #TODO: make a loops which read multiple times and join reads instead of relying on larger buffer [but still, i am sending messages myself of a known few bytes size]
recvSendBuf = 16384 #this is the buffer size for sending & receiving
global reconnSec
reconnSec = 1 #how many seconds to wait before trying to reconnect to redis
global transfers
transfers = 0 #how many transfers are currently going on
global timeout
timeout = 60.0 #how many seconds keep seeding after the file is downloaded
global refresh
refresh = 10.0 #each refresh seconds check out if the transfer is finished - for init seeder
global keepalive #after how many seconds will speed info keys expire in redis; if it's expired, you know that the system is dead/disconnected
keepalive = 30.0 #beware that keepalive has to be higher than monitoringInterval, which states how often they will be refreshed; good value is 3x higher
global monitoringInterval
monitoringInterval = 10 #each monitoringInterval seconds retrieve and upload new statistics...
global throttled
throttled = dict() #list of peers already added to throttle groups
#TODO: check if new rtorrent 0.8.7 can handle multiple concurrent xmlrpc commands...
global rLock #lock for avoiding two threads calling xmlrpc command simultaneously
rLock = threading.Lock()
global grpConnLock #lock for add_to_group mutex over throttled[peer] variable
grpConnLock = threading.Lock()
#some defaults; they get overwritten at start when reading settings
PORT = 10002 # Port on which this script listens
rtPORT = 10001 # Port on which rtorrent runs/does transfers
rdPORT = 6379 # Port on which redis runs
MGMT = WorkDir+"/MGMT.socket" # Path to the management unix socket where the rtorrListener listens and processes commands...
SCGI = 'scgi://'+WorkDir+'/SCGI.socket' # path to SCGI socket, which is in the rtorrent session directory
#BWmain = 'p2p-bootserver.internal' #the main BW manager; this one should be replicated and have hot standby
#BWMAIN would be used for dynamic BW and R management
myWeight = 0 #for dynamic BW mgmt
maxSPD = 700 #700mbit per peer maximum
DCdefault = 2000 #2gbit per DC
#myUP/myDOWN is my cumulative up/down speed per all the transfers...
global upDownLock
upDownLock = threading.Lock()
global myUP
global myDOWN
global lastUP
global lastDOWN
myUP = myDOWN = lastUP = lastDOWN = 0
global TR #all the transfer's specific and shared data
TR = {} #TR[HASH][variable] is the transfer specific and shared (among more transfer managing threads) variable
global TRlock
TRlock = threading.Lock()
#MAIN starts here already:
#connect to rtorrent SCGI socket
try:
rtorr = RTorrentXMLRPCClient(SCGI)
except:
print datetime.now(), 'MAIN: Couldn\'t connect to rtorrent on', SCGI,':', sys.exc_info()[0], sys.exc_info()[1]
sys.exit(255)
#try to create logfiles
try:
connLog = open(WorkDir+'/connect.log', 'a+')
grpLog = open(WorkDir+'/groups.log', 'a+')
annLog = open(WorkDir+'/announce.log', 'a+')
except:
print datetime.now(), "MAIN: Couldn't create/open files for logging"
sys.exit(255)
#TODO?: change this into reading a configfile
#Read commandline settings
try:
myIP = sys.argv[1]
myHOST = sys.argv[2]
myCHNL = sys.argv[3]
myRack = sys.argv[4]
myDC = sys.argv[5]
rtPORT = int(sys.argv[6])
PORT = int(sys.argv[7])
Rmain = sys.argv[8]
rdPORT = int(sys.argv[9])
try:
logHOST= sys.argv[10]
logPORT= sys.argv[11]
except:
logHOST= ''
Rhost = Rmain
#BWmain = Rmain #that's for dyn bw & r mgmt
except:
print datetime.now(), 'MAIN: parameters are (comma separated): <myIP> <myHOST> <myChannel> <myRack> <myDC> <rtorrent port> <overlay port> <main bandwidth manager ip/hostname> <redis port> [<log_HOST> <log_PORT>]'
print datetime.now(), 'MAIN: parameters given:', sys.argv[1:]
print datetime.now(), 'MAIN: exception ', sys.exc_info()[0], sys.exc_info()[1]
sys.stdout.flush()
sys.exit(255)
#create main listener socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((myIP, PORT))
s.listen(5) #the more the better, since I should expects some hoardes in the transfer start
except:
#TODO: >>stderr?
print datetime.now(), 'MAIN: Could not open socket on port', PORT, 'for listening: ', sys.exc_info()[0],sys.exc_info()[1]
sys.stdout.flush()
sys.exit(255)
global log
#initialize logging:
log = logging.getLogger("hyves.p2p.f")
tlog = logging.getLogger("hyves.p2p.t")
if logHOST == '':
print datetime.now(), 'MAIN: using local logging'
sys.stdout.flush()
handler = logging.handlers.SysLogHandler("/dev/log", logging.handlers.SysLogHandler.LOG_DAEMON)
thandler = logging.handlers.SysLogHandler("/dev/log", logging.handlers.SysLogHandler.LOG_DAEMON)
else:
print datetime.now(), 'MAIN: using remote logging'
sys.stdout.flush()
handler = logging.handlers.SysLogHandler((str(logHOST),int(logPORT)),logging.handlers.SysLogHandler.LOG_DAEMON)
thandler = logging.handlers.SysLogHandler((str(logHOST),int(logPORT)),logging.handlers.SysLogHandler.LOG_DAEMON)
format = logging.Formatter("%(name)-9s %(levelname)-8s %(funcName)-16s %(message)s")
tformat = logging.Formatter("%(name)-9s %(levelname)-8s %(threadName)-16s %(message)s")
handler.setFormatter(format)
thandler.setFormatter(tformat)
handler.setLevel(logging.DEBUG)
thandler.setLevel(logging.DEBUG)
log.addHandler(handler)
tlog.addHandler(thandler)
log.setLevel(logging.DEBUG)
tlog.setLevel(logging.DEBUG)
log.info("%s MAIN: starting..." % datetime.now() )
def mutex(function, parameters, lock):
''' Mutual exclusion on lock: run the function(parameters) and return result'''
global log
result = False
lock.acquire()
try:
#log.debug("%s About to call %s with parameters %s" % (datetime.now(), function , parameters) )
result = function(parameters)
except:
log.error("%s Failed calling %s, parameters %s, error: %s %s" % (datetime.now(), function, parameters, sys.exc_info()[0], sys.exc_info()[1] ))
sys.stdout.flush()
raise
finally:
lock.release()
return result
def RTex(function, parameters): #just a wrapper; unfortunatelly doesn't work for d.add_peer, because of some xmlrpc2scgi.py trouble (but at least if I call it directly, it works)
return mutex(function, parameters, rLock)
#TODO: v 0.8.7 is supposed to support multithreaded xmlrpc handling, lock may no more be needed;
#still, this needs to be tested well, if the rtorrent implementation doesn't have any trouble with race conditions etc. (e.g. 2 concurrent xmlrpc calls to modify the same throttle etc.)
def TRkeys():
'''
Returns list of currently running transfer's HASHes
'''
global TRlock
TRlock.acquire()
try:
keys = TR.keys()
except:
keys = None
finally:
TRlock.release()
return keys
def addToGroup(group, peer):
''' Adds peer to given group, returns true on success (even if the peer has been added to this group already) or false otherwise. '''
global log
result = False
if peer == myIP :
log.info("%s Not adding self to any group..." % datetime.now())
return True
grpConnLock.acquire()
try:
num = throttled[peer]
log.info("%s Already added %s to group %s times" % ( datetime.now(), peer, num ) )
throttled[peer] += 1
result = True
except:
try:
err = RTex(rtorr.throttle_grp, (group, peer) )
throttled[peer] = 1
if err != 0:
log.error("%s Non-zero (%s) return code when adding peer %s to group %s" % (datetime.now(), err, peer, group))
result = False
else:
log.info("%s Adding %s to group %s" % (datetime.now(), peer, group))
result = True
except:
log.error("%s Error adding peer %s to group %s : %s %s" % (datetime.now(), peer, group, sys.exc_info()[0], sys.exc_info()[1]))
result = False
finally:
grpConnLock.release()
return result
def addPeer(HASH, peer):
''' Adds throttled peer to rtorrent download HASH (this means rtorrent will connect to that peer for the given download), returns true on success, false otherwise. '''
global log
result = False
if peer == myIP :
log.info("%s Not adding self to any transfers..." % datetime.now())
return True
grpConnLock.acquire()
try:
num = throttled[peer]
try:
dest = peer+':'+str(rtPORT)
rLock.acquire()
try:
err = rtorr.d.add_peer(HASH, dest)
except:
log.error("%s Error adding peer %s to transfer %s : %s %s" % (datetime.now(), peer, HASH, sys.exc_info()[0], sys.exc_info()[1]))
err = 255
finally:
rLock.release()
#err=RTex(rtorr.d.add_peer, (HASH, dest) ) #This way it just doesn't work - it never correctly passes the peer (it passes '' instead)
if err !=0:
log.error("%s Non-zero (%s) return code when adding peer %s to transfer %s" % (datetime.now(), err, peer, HASH))
result = False
else:
log.info("%s Adding %s to transfer %s" % (datetime.now(), peer, HASH))
result = True
except:
log.error("%s Error adding peer %s to transfer %s : %s %s" % (datetime.now(), peer, HASH, sys.exc_info()[0], sys.exc_info()[1]))
result = False
except:
log.error("%s %s not added to any group yet!, not adding to transfer %s" % (datetime.now(), peer, HASH))
result = False
finally:
grpConnLock.release()
return result
class connectToPeer(threading.Thread):
''' Let the peer know that we have added him to our throttle groups, thus as soon as he adds us, he can connect to the rtorrent directly... (see addPeer function)'''
def __init__ (self, HASH, peer):
self.HASH = HASH
self.peer = peer
threading.Thread.__init__( self )
self.setName("connectToPeer")
def run(self):
peer = self.peer
HASH = self.HASH
local= threading.local()
global tlog
print "i am alive!"
sys.stdout.flush()
if peer == myIP :
tlog.info("%s Not connecting to self..." % datetime.now())
return True
success = False
try:
local.s = socketmodule.socket(socketmodule.AF_INET, socketmodule.SOCK_STREAM)
except:
tlog.error("%s Couldn't create socket, thus unable to connect to %s : %s %s" % (datetime.now(), peer, sys.exc_info()[0], sys.exc_info()[1]))
return False
try:
local.s.connect((peer, PORT)) #PORT is usually 10002; defined in the config file
except:
tlog.error("%s Couldn't connect to %s:%s : %s %s" % (datetime.now(), peer, PORT, sys.exc_info()[0], sys.exc_info()[1]) )
return False
request = ['CONNECT', myIP, myRack, myDC, HASH]
tlog.info("%s Sending request: %s to %s" % (datetime.now(), str(" ".join(request)), peer ))
local.s.send(" ".join(request))
data = local.s.recv(16384)
local.s.close()
log.info("%s Received: %r from %s" % (datetime.now(), data, peer) )
reply = data.split(' ')
if reply[0] == "200" : success = True
else: log.warning("%s Problem when connecting to %s : %r" % (datetime.now(), peer, data))
return success
class announceTransfer(threading.Thread):
''' Inform the peer that he should join the given transfer '''
def __init__ (self, peer, HASH, destPath, torrentPath, md5Path, speed, priority, localTorrentPath):
self.HASH = HASH
self.peer = peer
self.destPath = destPath
self.torrentPath = torrentPath
self.md5Path = md5Path
self.speed = speed
self.prio = priority
self.ltp = localTorrentPath
threading.Thread.__init__( self )
self.setName("announceTransfer")
def run(self):
peer = self.peer
local= threading.local()
global tlog
#COPY THE FILES FIRST
getTorr = subprocess.Popen(["scp", "-oStrictHostKeyChecking=no", self.ltp, str(self.peer)+":/etc/p2p/" ], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
code = getTorr.wait()
if code != 0:
tlog.error("%s Couldn't get torrent file to %s, scp return code = %s" % (datetime.now(), self.peer, code))
return #no torrent file = nothing to download! = no announce....
tlog.info("%s Got %s to %s" % (datetime.now(), self.ltp, peer))
getMd5 = subprocess.Popen(["scp", "-oStrictHostKeyChecking=no", self.md5Path , str(self.peer)+":/etc/p2p/" ], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
code = getMd5.wait()
if code != 0:
tlog.error("%s Couldn't get md5 file to %s, scp return code = %s" % (datetime.now(), self.peer, code))
return #no md5 file = corrupt download - which in reality might not be corrupt, thus creating a misleading and confusing situation
tlog.info("%s Got %s to %s" % (datetime.now(), self.md5Path, peer))
#THEN ANNOUNCE:
if str(peer) == str(myHOST) :
tlog.info("%s Not announcing to self..." % datetime.now())
return True
success = False
try:
local.s = socketmodule.socket(socketmodule.AF_INET, socketmodule.SOCK_STREAM)
except:
tlog.error("%s Couldn't create socket, thus unable to connect to %s : %s %s" % (datetime.now(), peer, sys.exc_info()[0], sys.exc_info()[1]))
return False
try:
local.s.connect((peer, PORT)) #PORT is usually 10002; defined in the config file
except:
tlog.error("%s Couldn't connect to %s:%s : %s %s" % (datetime.now(), peer, PORT, sys.exc_info()[0], sys.exc_info()[1]) )
return False
request = ['TRANSFER', self.HASH, myIP, self.destPath, self.torrentPath, self.md5Path, str(self.speed), str(self.prio)]
tlog.info("%s Sending request: %s to %s" % (datetime.now(), str(" ".join(request)), peer ))
local.s.send(" ".join(request))
data = local.s.recv(16384)
local.s.close()
tlog.info("%s Received: %r from %s" % (datetime.now(), data, peer) )
reply = data.split(' ')
if reply[0] == "200" :
success = True
else: tlog.warning("%s Problem when connecting to %s : %r" % (datetime.now(), peer, data))
return success
def post(text, lock, msgQueue):
''' Post a redis message containing text to the head of msgQueue protected by the lock... '''
global log
try:
msg = {'pattern': None, 'type': 'message', 'channel': 'like_we_do_care', 'data': text}
lock.acquire()
msgQueue.insert(0, msg) #push the msg. to the shared queue's head
lock.notify()
except:
log.error("%s Exception when trying to post %s : %s %s" % (datetime.now(), text, sys.exc_info()[0], sys.exc_info()[1] ))
finally:
lock.release()
def yielder(shared_variable, condition_variable):
''' The yielder is yielding the messages from the shared_variable protected by condition_variable. The yielder is a typical consumer... '''
while 1:
condition_variable.acquire()
if len(shared_variable) == 0 : condition_variable.wait() #if there's nothing to read, wait until it's delivered/produced ...
local_variable = shared_variable.pop(0) #there will always be st. to get, otherwise we wouldn't be notified
condition_variable.release()
yield local_variable
class subscriber(threading.Thread):
''' Subscribes to a channel on host, receives messages and puts them to a shared_variable protected by the condition_variable... '''
def __init__(self, host, channel, shared_variable, condition_variable):
self.hst = host
self.chn = channel
self.shv = shared_variable
self.cdv = condition_variable
self.DIE = False #if I should quit
threading.Thread.__init__(self)
self.setName("subscriber")
def run(self):
ready = self.cdv
R = redis.Redis(host = self.hst, port = rdPORT, db=0)
#print datetime.now(), "subscriber thread:", self.chn
#sys.stdout.flush()
global tlog
tlog.info("%s Subscriber" % datetime.now())
while 1:
if self.DIE : return
try:
#R['init']=self.getName() #don't - if you're still subscribed on reconnect, you'll get error
R.subscribe(self.chn)
except:
print datetime.now(), "subscriber: Error establishing connection to", str(self.hst)+":"+str(rdPORT), "and subscribing to", self.chn
print sys.exc_info()[0],":",sys.exc_info()[1]
time.sleep(reconnSec)
print datetime.now(), "subscriber: Reconnecting..."
sys.stdout.flush()
continue
try:
print datetime.now(), "subscriber: Connected to", str(self.hst)+":"+str(rdPORT)+", about to listen on", self.chn
sys.stdout.flush()
for msg in R.listen():
#print datetime.now(), 'subscriber', self.getName(), 'got msg', msg
#sys.stdout.flush()
if self.DIE : return #death can come anytime
ready.acquire()
self.shv.append(msg) #push the msg. to the shared queue
ready.notify()
ready.release()
except: #this is to keep trying reconnect
print datetime.now(), "subscriber: Error when listening at", str(self.hst)+":"+str(rdPORT), "on", self.chn
print sys.exc_info()[0], ":", sys.exc_info()[1]
sys.stdout.flush()
finally:
try:
ready.release() #since I might still be holding it, but maybe not - it depends which command raised the exception
except:
pass
if self.DIE : return
print datetime.now(), "subscriber: Reconnecting..."
time.sleep(reconnSec) #this is probably a connection error, so just wait a bit and then try again....
#should be never reached:
#print datetime.now(), 'listener', self.getName(), 'quit'
#sys.stdout.flush()
class rtorrListener(threading.Thread):
''' This thread is listening on MGMT.socket and processes commands both from rtorrent (e.g. transfer finished) and the user - submitted via sockecho.py '''
def __init__(self, socketPath):
self.sPath = socketPath
threading.Thread.__init__(self)
self.setName("rtorrListener")
def run(self):
global TR
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.remove(self.sPath)
except OSError:
pass #it's OK - it will fail if the file doesn't exist yet
try:
s.bind(self.sPath)
except:
print datetime.now(), "rListen: Couldn\'t bind the path for rtorrent communication socket:", self.sPath
sys.exit(255) #this is really serious, so the whole application should exit
s.listen(1)
print datetime.now(), "rListen: Listening on", self.sPath
sys.stdout.flush()
while 1:
conn, addr = s.accept()
#print datetime.now(), "rListen: Got connection from", addr
data = conn.recv(16384)
#TODO: is 1024 enough?
#TODO: if not data: #TROUBLE
print datetime.now(), "rListen: received:", data
sys.stdout.flush()
parse = data.split(' ')
# print datetime.now(), "rListen: parsed", parse
# print datetime.now(), "rListen: HASH =", HASH
# sys.stdout.flush()
try:
if parse[0] == 'HASH' : #this is message from rtorrent (via finished.py)
HASH = parse[1]
try:
a = TRkeys().index(HASH)
except:
print datetime.now(), "rListen: not doing transfer", HASH
sys.stdout.flush()
if parse[2] == "OK":
print datetime.now(), "rListen: posting FINISHED download..."
sys.stdout.flush()
post('*FINISHED download', TR[HASH]['mgr'].ready, TR[HASH]['mgr'].messages)
if parse[2] == "CORRUPT":
print datetime.now(), "rListen: posting CORRUPTED download..."
sys.stdout.flush()
post('*CORRUPTED download', TR[HASH]['mgr'].ready, TR[HASH]['mgr'].messages)
if parse[2] == "UNKNOWN":
print datetime.now(), "rListen: posting CORRUPTED download..."
sys.stdout.flush()
post('*CORRUPTED download', TR[HASH]['mgr'].ready, TR[HASH]['mgr'].messages)
continue
if parse[0] == 'INIT' : #this message from user (via sockecho.py) to start transfer
#TODO: check if message format is OK
HASH = parse[1]
Rhost = parse[2] #=self? but also can specify some other dedicated host....
destPath = parse[3]
torrentPath = parse[4]
md5Path = parse[5]
speed = int(parse[6])
destRemote = parse[7]
try:
priority = parse[8]
except:
priority = 2
#if not(busy):
conn.send("200 OK, starting the transfer...")
transferWrapper(HASH, Rhost, torrentPath, destPath, md5Path, True, destRemote, speed, priority).start()
#else:
# conn.send("400 Already doing a transfer...")
continue
if parse[0] == 'TRANSFER' : #this message is to join a transfer
#TODO: check if message format is OK
HASH = parse[1]
Rhost = parse[2]
destPath = parse[3]
torrentPath = parse[4]
md5Path = parse[5]
speed = int(parse[6])
try:
priority = parse[7]
except:
priority = 2
#if not(busy):
conn.send("200 OK, joining the transfer...")
transferWrapper(HASH, Rhost, torrentPath, destPath, md5Path, False, '', speed, priority).start()
#else:
#conn.send("400 Already doing a transfer...")
continue
if str(parse[0]).upper() == 'PID' : #kind-of PING
conn.send(repr(os.getpid()))
continue
if str(parse[0]).upper() == 'STOPALL' :
try:
a=0
keys = TRkeys()
for HASH in keys:
post('*FINISHED transfer', TR[HASH]['mgr'].ready, TR[HASH]['mgr'].messages)
a += 1
conn.send("200 OK, stopping "+str(a)+" transfers.")
except:
print datetime.now(), "rListen: not doing transfer", HASH
conn.send("200 OK, wasn't doing any transfer already...")
sys.stdout.flush()
continue
conn.send("400 Unknown command: "+repr(parse[0])+" in "+repr(data))
except:
print datetime.now(), "rListen: error processing", data
print datetime.now(), "rListen: exception:", sys.exc_info()
sys.stdout.flush()
#TODO: add more mgmt commands here
sys.stdout.flush()
conn.close()
class connManager(threading.Thread ):
''' This thread is listening on the main script PORT for the incoming requests (or information) about connecting to peers:
The incoming connection comes from the peer who has already added us to his throttle groups and is letting us know that
as soon as we add him to our throttles, we can tell rtorrent to add that peer to the given download. '''
def __init__(self, socket, address ):
self.conn = socket
self.address = address
threading.Thread.__init__(self)
self.setName("connManager")
def run(self):
#global busy
#print datetime.now(), 'Received connection:', self.address
#TODO: is 1024 enough? how does it really read? what if the message is fragmented? I don't expect more than 1024 bytes, but can I expect it arrives intact?
data = self.conn.recv(16384)
print datetime.now(),"connMan: received", repr(data)
# while recv != '':
# recv = self.socket.recv(1024)
# self.data += recv
# if not self.data: break #EOF
# print self.data
try:
parse = data.split(' ') #parse
#print datetime.now(),"connMan: received", parse
sys.stdout.flush()
if parse[0] == 'CONNECT':
if len(parse) < 5: #it should be: <hostname/IP> <rack> <DC> <HASH>
self.conn.send ( "500 couldn't parse your CONNECT request" )
print >>connLog, datetime.now(), 'Failed parsing:', repr(parse), '.'
else:
peer = parse[1]
HASH = parse[4]
success = True
# print 'My peer\'s rack is', parse[2]
# print 'My peer\'s DC is', parse[3]
# print 'My peer\'s HASH is', parse[4]
if parse[2] == myRack \
and parse[3] == myDC: group='myRack'
elif parse[3] == myDC: group='myDC'
else: group='outside'
#print datetime.now(), 'I would add this peer to group', group
success = addToGroup(group, peer)
#if successfully added to group, then connect:
if success: success = addPeer(HASH, peer)
if success: self.conn.send ( '200 OK' )
else: self.conn.send ( "400 Couldn't complete connection attempt")
elif parse[0] == 'TRANSFER' : #this message is to join a transfer
if len(parse) < 7:
self.conn.send ( "500 couldn't parse your TRANSFER request" )
print datetime.now(),"connMan: couldn't parse TRANSFER request:", parse
sys.stdout.flush()
else:
HASH = parse[1]
Rhost = parse[2]
destPath = parse[3]
torrentPath = parse[4]
md5Path = parse[5]
speed = int(parse[6])
try:
priority = parse[7]
except:
priority = 2
#if not(busy):
self.conn.send("200 OK, joining the transfer...")
transferWrapper(HASH, Rhost, torrentPath, destPath, md5Path, False, '', speed, priority).start()
#else:
# self.conn.send("400 Already doing a transfer...")
elif str(parse[0]).upper() == 'PID' : #kind-of PING
self.conn.send(repr(os.getpid()))
elif str(parse[0]).upper() == 'STOPALL' :
try:
a=0
keys = TRkeys()
for HASH in keys:
post('*FINISHED transfer', TR[HASH]['mgr'].ready, TR[HASH]['mgr'].messages)
a += 1
self.conn.send("200 OK, stopping "+str(a)+" transfers.")
except:
print datetime.now(), "rListen: not doing transfer", HASH
self.conn.send("200 OK, wasn't doing any transfer already...")
sys.stdout.flush()
else: self.conn.send("500 Unknown command: "+repr(parse[0])+" in "+repr(data))
except:
print datetime.now(), "rListen: error processing", data
print datetime.now(), "rListen: exception:", sys.exc_info()
sys.stdout.flush()
finally:
#that's it, request processed...
self.conn.close()
#print datetime.now(), 'Closed connection:', self.address [ 0 ]
def updateSpeeds():
''' Computes cumulative myUP and myDOWN (for throttles) and updates outside throttles if they have changed '''
global TR
global upDownLock
global myUP
global myDOWN
global lastUP
global lastDOWN
global maxSPD
sumOutUP = 0
sumOutDOWN=0
sumDCUP = 0
sumDCDOWN= 0
print datetime.now(), "updSPD: about to compute some stuff..."
sys.stdout.flush()
upDownLock.acquire()
try:
#print datetime.now(), "updSPD: got lock... about to get keys"
#sys.stdout.flush()
keys = TRkeys()
print datetime.now(), "updSPD: found", len(keys), "keys"
sys.stdout.flush()
try:
for a in keys:
#every computation in try except - because some just starting transfers don't have those keys yet
try: sumOutUP += TR[a]['outUP']
except: pass
try: sumOutDOWN += TR[a]['outDOWN']
except: pass
try: sumDCUP += TR[a]['dcUP']
except: pass
try: sumDCDOWN += TR[a]['dcDOWN']
except: pass
except:
print datetime.now(), "updSPD: trouble computing sums:", sys.exc_info()[0], sys.exc_info()[1]
print repr(TR)
sys.stdout.flush()
return
print datetime.now(), "updSPD: computed sums outUP, outDOWN:", sumOutUP, sumOutDOWN
sys.stdout.flush()
if sumDCUP > maxSPD : sumDCUP = maxSPD
if sumDCDOWN > maxSPD : sumDCDOWN = maxSPD
#I can't have higher up/download from outside group than from DC, since it actually goes via the same link
if sumOutUP > sumDCUP : sumOutUP = sumDCUP
if sumOutDOWN > sumDCDOWN : sumOutDOWN = sumDCDOWN
myUP = sumDCUP
myDOWN = sumDCDOWN
print datetime.now(), "updSPD: Set myUP/myDOWN rates:", str(myUP)+"/"+str(myDOWN)
sys.stdout.flush()
update = False
if sumOutUP != lastUP or sumOutDOWN != lastDOWN :
update = True
lastUP = sumOutUP
lastDOWN = sumOutDOWN
#print "updateSpeeds: computed some stuff..."
#sys.stdout.flush()
if update:
th_down=str(sumOutDOWN)+'k'
th_up=str(sumOutUP)+'k'
try:
print datetime.now(), "updSPD: about to update rtorrent"
sys.stdout.flush()
err1 = RTex(rtorr.throttle_down, ('outside',th_down))
err2 = RTex(rtorr.throttle_up, ('outside',th_up))
print datetime.now(), "updSPD: Set outside throttle up/down rates:", str(th_up)+"/"+str(th_down)
sys.stdout.flush()
except:
err1 = 0
err2 = 0
print datetime.now(), "updSPD: Error setting outside throttle up/down rates:", sys.exc_info()
sys.stdout.flush()
if err1 != 0 or err2 != 0:
print datetime.now(), "updSPD: Error setting outside throttle up/down rates, codes=", str(err1), str(err2)
sys.stdout.flush()
except:
print datetime.now(), "updSPD: trouble computing speeds:", sys.exc_info()[0], sys.exc_info()[1]
sys.stdout.flush()
finally:
upDownLock.release()
print datetime.now(), "updSPD: released lock"
sys.stdout.flush()
class speedManager(threading.Thread):
def __init__(self, redisHost, HASH):
self.DIE = False
self.HASH = HASH
self.rHost = redisHost
threading.Thread.__init__(self)
self.setName("speedManager")
def run(self):
global TR
HASH = self.HASH
rHost= self.rHost
speed = TR[HASH]['speed']
#global role
#global defaultSPD
#global myUP
#global myDOWN
print datetime.now(), 'spdMan: starting...'
sys.stdout.flush()
#for now only failsafe mode and for only one transfer
while not(self.DIE):
try:
BW = redis.Redis(host=rHost, port=rdPORT, db=0) #to listen
RD = redis.Redis(host=rHost, port=rdPORT, db=0) #to read
except:
print datetime.now(), "spdMan: Could not connect to", str(rHost)+":"+str(rdPORT), ", is redis running?"
print sys.exc_info()
time.sleep(reconnSec)
print datetime.now(), "spdMan: Reconnecting..."
sys.stdout.flush()
continue
#it actually tries to connect only here:
try:
BW['init']='connected'
RD['init']='connected'
except:
print datetime.now(), "spdMan: Error establishing connection to redis on", str(rHost)+":"+str(rdPORT)
print sys.exc_info()[0], sys.exc_info()[1]
time.sleep(reconnSec)
print datetime.now(), "spdMan: Reconnecting..."
sys.stdout.flush()
continue
#TODO: listen on all the channels where you're R - when you become R there, launch another thread that manages that thing...
print datetime.now(), 'spdMan: about to subscribe to', HASH+'.'+myDC+'.'+myRack+'.all.channel'
sys.stdout.flush()
BW.subscribe(HASH+'.'+myDC+'.'+myRack+'.all.channel')
print datetime.now(), 'spdMan: Waiting for overlay/init managers to join the overlay...'
TR[HASH]['speedEvent'].wait()
print datetime.now(), 'spdMan: finished waiting... and finishing due to embedded spdman'
return
try:
for msg in BW.listen():
#print datetime.now(), 'spdMan: self.DIE=', self.DIE
#sys.stdout.flush()
#if msg['type'] == 'subscribe' : continue
if self.DIE : break
update=False
#if I am an R, then update speeds
print datetime.now(), "spdMan: role is", TR[HASH]['role'], "and message is", msg['data']
if TR[HASH]['role'] >= 2:
uploaders = RD.scard(HASH+'.'+myDC+'.'+myRack+'.uploaders')
downloaders=RD.scard(HASH+'.'+myDC+'.'+myRack+'.downloaders')
print datetime.now(), 'spdMan: found', uploaders, 'uploaders and', downloaders, 'downloaders in my rack'
if uploaders == 0 : uploaders = 1 #&& spit fire!!! as this should never happen
if downloaders== 0 : downloaders = 1 #&& spit fire!!! as this should never happen
myUP = speed/ uploaders
myDOWN= speed/ downloaders
if myUP < 10 : myUP = 10
if myDOWN<10 : myDOWN=10
myUP = myUP / 10
myDOWN=myDOWN/10
myDC_UP = 0
myDC_DOWN=0
update=True
#only if I can also go out
if TR[HASH]['role'] == 3 :
DCuploaders = RD.scard(HASH+'.'+myDC+'.uploaders')
DCdownloaders=RD.scard(HASH+'.'+myDC+'.downloaders')
print datetime.now(), 'spdMan: found', DCuploaders, 'uploaders and', DCdownloaders, 'downloaders in my DC'
if DCuploaders == 0 : DCuploaders = 1 #&& spit fire!!! as this should never happen
if DCdownloaders==0 : DCdownloaders= 1 #&& spit fire!!! as this should never happen
myDC_UP = DCdefault / DCuploaders
myDC_DOWN=DCdefault/DCdownloaders
if myDC_UP < 10 : myDC_UP = 10
if myDC_DOWN<10 : myDC_DOWN=10
myDC_UP = myDC_UP / 10
myDC_DOWN=myDC_DOWN/10
#because if you want to go out of DC, you have to go out of rack - the groups are inclusive
if myDC_UP > myUP : myDC_UP = myUP
if myDC_DOWN > myDOWN : myDC_DOWN = myDOWN
update=True
if update:
try:
TR[HASH]['outUP'] =myDC_UP
TR[HASH]['outDOWN']=myDC_DOWN
TR[HASH]['dcUP'] =myUP
TR[HASH]['dcDOWN'] =myDOWN
updateSpeeds()
except KeyError, e:
print datetime.now(), "spdMan: Couldn't update the speeds in TR[HASH], transfer stopped? Exception: %s" % e
print repr(TR)
sys.stdout.flush()
print datetime.now(), 'spdMan: dcUP/dcDOWN ; outUP/outDOWN: [', str(myUP)+"/"+str(myDOWN),';', str(myDC_UP)+"/"+str(myDC_DOWN),"] for", HASH
sys.stdout.flush()
except:
print datetime.now(), "spdMan: Error when reading messages from", str(rHost)+":"+str(rdPORT), "on", HASH+'.'+myDC+'.'+myRack+'.all.channel'
print sys.exc_info()[0], sys.exc_info()[1]
time.sleep(reconnSec)
print datetime.now(), "spdMan: Reconnecting..."
sys.stdout.flush()