]> git.mxchange.org Git - quix0rs-apt-p2p.git/blob - apt_dht_Khashmir/krpc.py
Improve the stopping of the krpc protocol so no timeouts are left.
[quix0rs-apt-p2p.git] / apt_dht_Khashmir / krpc.py
1 ## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
2 # see LICENSE.txt for license information
3
4 from bencode import bencode, bdecode
5 from time import asctime
6 import sys
7 from traceback import format_exception
8
9 from twisted.internet.defer import Deferred
10 from twisted.internet import protocol, reactor
11 from twisted.trial import unittest
12
13 KRPC_TIMEOUT = 20
14
15 KRPC_ERROR = 1
16 KRPC_ERROR_METHOD_UNKNOWN = 2
17 KRPC_ERROR_RECEIVED_UNKNOWN = 3
18 KRPC_ERROR_TIMEOUT = 4
19
20 # commands
21 TID = 't'
22 REQ = 'q'
23 RSP = 'r'
24 TYP = 'y'
25 ARG = 'a'
26 ERR = 'e'
27
28 class ProtocolError(Exception):
29     pass
30
31 class hostbroker(protocol.DatagramProtocol):       
32     def __init__(self, server):
33         self.server = server
34         # this should be changed to storage that drops old entries
35         self.connections = {}
36         
37     def datagramReceived(self, datagram, addr):
38         #print `addr`, `datagram`
39         #if addr != self.addr:
40         c = self.connectionForAddr(addr)
41         c.datagramReceived(datagram, addr)
42         #if c.idle():
43         #    del self.connections[addr]
44
45     def connectionForAddr(self, addr):
46         if addr == self.addr:
47             raise Exception
48         if not self.connections.has_key(addr):
49             conn = self.protocol(addr, self.server, self.transport)
50             self.connections[addr] = conn
51         else:
52             conn = self.connections[addr]
53         return conn
54
55     def makeConnection(self, transport):
56         protocol.DatagramProtocol.makeConnection(self, transport)
57         tup = transport.getHost()
58         self.addr = (tup.host, tup.port)
59         
60     def stopProtocol(self):
61         for conn in self.connections.values():
62             conn.stop()
63         protocol.DatagramProtocol.stopProtocol(self)
64
65 ## connection
66 class KRPC:
67     noisy = 1
68     def __init__(self, addr, server, transport):
69         self.transport = transport
70         self.factory = server
71         self.addr = addr
72         self.tids = {}
73         self.mtid = 0
74         self.stopped = False
75
76     def datagramReceived(self, str, addr):
77         if self.stopped:
78             if self.noisy:
79                 print "stopped, dropping message from", addr, str
80         # bdecode
81         try:
82             msg = bdecode(str)
83         except Exception, e:
84             if self.noisy:
85                 print "response decode error: " + `e`
86         else:
87             if self.noisy:
88                 print msg
89             # look at msg type
90             if msg[TYP]  == REQ:
91                 ilen = len(str)
92                 # if request
93                 #       tell factory to handle
94                 f = getattr(self.factory ,"krpc_" + msg[REQ], None)
95                 msg[ARG]['_krpc_sender'] =  self.addr
96                 if f and callable(f):
97                     try:
98                         ret = apply(f, (), msg[ARG])
99                     except Exception, e:
100                         ## send error
101                         out = bencode({TID:msg[TID], TYP:ERR, ERR :`format_exception(type(e), e, sys.exc_info()[2])`})
102                         olen = len(out)
103                         self.transport.write(out, addr)
104                     else:
105                         if ret:
106                             #   make response
107                             out = bencode({TID : msg[TID], TYP : RSP, RSP : ret})
108                         else:
109                             out = bencode({TID : msg[TID], TYP : RSP, RSP : {}})
110                         #       send response
111                         olen = len(out)
112                         self.transport.write(out, addr)
113
114                 else:
115                     if self.noisy:
116                         print "don't know about method %s" % msg[REQ]
117                     # unknown method
118                     out = bencode({TID:msg[TID], TYP:ERR, ERR : KRPC_ERROR_METHOD_UNKNOWN})
119                     olen = len(out)
120                     self.transport.write(out, addr)
121                 if self.noisy:
122                     print "%s %s >>> %s - %s %s %s" % (asctime(), addr, self.factory.node.port, 
123                                                     ilen, msg[REQ], olen)
124             elif msg[TYP] == RSP:
125                 # if response
126                 #       lookup tid
127                 if self.tids.has_key(msg[TID]):
128                     df = self.tids[msg[TID]]
129                     #   callback
130                     del(self.tids[msg[TID]])
131                     df.callback({'rsp' : msg[RSP], '_krpc_sender': addr})
132                 else:
133                     print 'timeout ' + `msg[RSP]['id']`
134                     # no tid, this transaction timed out already...
135             elif msg[TYP] == ERR:
136                 # if error
137                 #       lookup tid
138                 if self.tids.has_key(msg[TID]):
139                     df = self.tids[msg[TID]]
140                     #   callback
141                     df.errback(msg[ERR])
142                     del(self.tids[msg[TID]])
143                 else:
144                     # day late and dollar short
145                     pass
146             else:
147                 print "unknown message type " + `msg`
148                 # unknown message type
149                 df = self.tids[msg[TID]]
150                 #       callback
151                 df.errback(KRPC_ERROR_RECEIVED_UNKNOWN)
152                 del(self.tids[msg[TID]])
153                 
154     def sendRequest(self, method, args):
155         if self.stopped:
156             raise ProtocolError, "connection has been stopped"
157         # make message
158         # send it
159         msg = {TID : chr(self.mtid), TYP : REQ,  REQ : method, ARG : args}
160         self.mtid = (self.mtid + 1) % 256
161         str = bencode(msg)
162         d = Deferred()
163         self.tids[msg[TID]] = d
164         def timeOut(tids = self.tids, id = msg[TID], msg = msg):
165             if tids.has_key(id):
166                 df = tids[id]
167                 del(tids[id])
168                 print ">>>>>> KRPC_ERROR_TIMEOUT"
169                 df.errback(ProtocolError('timeout waiting for %r' % msg))
170         later = reactor.callLater(KRPC_TIMEOUT, timeOut)
171         def dropTimeOut(dict, later_call = later):
172             if later_call.active():
173                 later_call.cancel()
174             return dict
175         d.addBoth(dropTimeOut)
176         self.transport.write(str, self.addr)
177         return d
178     
179     def stop(self):
180         """Timeout all pending requests."""
181         for df in self.tids.values():
182             df.errback(ProtocolError('connection has been closed'))
183         self.tids = {}
184         self.stopped = True
185  
186 def connectionForAddr(host, port):
187     return host
188     
189 class Receiver(protocol.Factory):
190     protocol = KRPC
191     def __init__(self):
192         self.buf = []
193     def krpc_store(self, msg, _krpc_sender):
194         self.buf += [msg]
195     def krpc_echo(self, msg, _krpc_sender):
196         return msg
197
198 def make(port):
199     af = Receiver()
200     a = hostbroker(af)
201     a.protocol = KRPC
202     p = reactor.listenUDP(port, a)
203     return af, a, p
204     
205 class KRPCTests(unittest.TestCase):
206     def setUp(self):
207         KRPC.noisy = 0
208         self.af, self.a, self.ap = make(1180)
209         self.bf, self.b, self.bp = make(1181)
210
211     def tearDown(self):
212         self.ap.stopListening()
213         self.bp.stopListening()
214
215     def bufEquals(self, result, value):
216         self.assertEqual(self.bf.buf, value)
217
218     def testSimpleMessage(self):
219         d = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
220         d.addCallback(self.bufEquals, ["This is a test."])
221         return d
222
223     def testMessageBlast(self):
224         for i in range(100):
225             d = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
226         d.addCallback(self.bufEquals, ["This is a test."] * 100)
227         return d
228
229     def testEcho(self):
230         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
231         df.addCallback(self.gotMsg, "This is a test.")
232         return df
233
234     def gotMsg(self, dict, should_be):
235         _krpc_sender = dict['_krpc_sender']
236         msg = dict['rsp']
237         self.assertEqual(msg, should_be)
238
239     def testManyEcho(self):
240         for i in xrange(100):
241             df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
242             df.addCallback(self.gotMsg, "This is a test.")
243         return df
244
245     def testMultiEcho(self):
246         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
247         df.addCallback(self.gotMsg, "This is a test.")
248
249         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
250         df.addCallback(self.gotMsg, "This is another test.")
251
252         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
253         df.addCallback(self.gotMsg, "This is yet another test.")
254         
255         return df
256
257     def testEchoReset(self):
258         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
259         df.addCallback(self.gotMsg, "This is a test.")
260
261         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
262         df.addCallback(self.gotMsg, "This is another test.")
263         df.addCallback(self.echoReset)
264         return df
265     
266     def echoReset(self, dict):
267         del(self.a.connections[('127.0.0.1', 1181)])
268         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
269         df.addCallback(self.gotMsg, "This is yet another test.")
270         return df
271
272     def testUnknownMeth(self):
273         df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('blahblah', {'msg' : "This is a test."})
274         df.addErrback(self.gotErr, KRPC_ERROR_METHOD_UNKNOWN)
275         return df
276
277     def gotErr(self, err, should_be):
278         self.assertEqual(err.value, should_be)